blob: 0089f8f4ebcc883aad729951f11b98253bd2bd3c [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;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000237 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
238 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000239 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000240
Jim Grosbach4b905842013-09-20 23:08:21 +0000241 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000242 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000243 bool parseIdentifier(StringRef &Res) override;
244 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000245
Craig Topper59be68f2014-03-08 07:14:16 +0000246 void checkForValidSection() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000247 /// }
248
249private:
Daniel Dunbare5444a82010-09-09 22:42:59 +0000250
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000251 bool parseStatement(ParseStatementInfo &Info,
252 MCAsmParserSemaCallback *SI);
Jim Grosbach4b905842013-09-20 23:08:21 +0000253 void eatToEndOfLine();
254 bool parseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000255
Jim Grosbach4b905842013-09-20 23:08:21 +0000256 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000257 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000258 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000259 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000260 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Rafael Espindola1134ab232011-06-05 02:43:45 +0000261 const SMLoc &L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000262
Eli Benderskya313ae62013-01-16 18:56:50 +0000263 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000264 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000265
266 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000267 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000268
269 /// \brief Lookup a previously defined macro.
270 /// \param Name Macro name.
271 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000272 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000273
274 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000275 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000276
277 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000278 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000279
280 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000281 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000282
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000283 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000284 ///
285 /// \param M The macro.
286 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000287 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000288
289 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000290 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000291
David Majnemer91fc4c22014-01-29 18:57:46 +0000292 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000293 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000294
295 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000296 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000297
Jim Grosbach4b905842013-09-20 23:08:21 +0000298 void printMacroInstantiations();
299 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000300 ArrayRef<SMRange> Ranges = None) const {
Chris Lattner72845262011-10-16 05:47:55 +0000301 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000302 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000303 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000304
Jim Grosbach4b905842013-09-20 23:08:21 +0000305 /// \brief Enter the specified file. This returns true on failure.
306 bool enterIncludeFile(const std::string &Filename);
307
308 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000309 /// This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000310 bool processIncbinFile(const std::string &Filename);
Daniel Dunbar43235712010-07-18 18:54:11 +0000311
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000312 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000313 /// current token is not set; clients should ensure Lex() is called
314 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000315 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000316 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000317 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000318 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000319
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000320 /// \brief Parse up to the end of statement and a return the contents from the
321 /// current token until the end of the statement; the current token on exit
322 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000323 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000324
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000325 /// \brief Parse until the end of a statement or a comma is encountered,
326 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000327 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000328
Jim Grosbach4b905842013-09-20 23:08:21 +0000329 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000330 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000331
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000332 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
333 MCBinaryExpr::Opcode &Kind);
334
Jim Grosbach4b905842013-09-20 23:08:21 +0000335 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
336 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
337 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000338
Jim Grosbach4b905842013-09-20 23:08:21 +0000339 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000340
Eli Bendersky17233942013-01-15 22:59:42 +0000341 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000342 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000343 DK_NO_DIRECTIVE, // Placeholder
344 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
David Woodhoused6de0d92014-02-01 16:20:59 +0000345 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
346 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000347 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000348 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000349 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000350 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
351 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
352 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
353 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000354 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000355 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
356 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000357 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
358 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
359 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
360 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
361 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
362 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000363 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000364 DK_MACROS_ON, DK_MACROS_OFF,
365 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000366 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000367 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000368 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000369 };
370
Jim Grosbach4b905842013-09-20 23:08:21 +0000371 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000372 /// directives parsed by this class.
373 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000374
375 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000376 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
377 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
David Woodhoused6de0d92014-02-01 16:20:59 +0000378 bool parseDirectiveOctaValue(); // ".octa"
Jim Grosbach4b905842013-09-20 23:08:21 +0000379 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
380 bool parseDirectiveFill(); // ".fill"
381 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000382 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000383 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
384 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000385 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000386 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000387
Eli Bendersky17233942013-01-15 22:59:42 +0000388 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000389 bool parseDirectiveFile(SMLoc DirectiveLoc);
390 bool parseDirectiveLine();
391 bool parseDirectiveLoc();
392 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000393
394 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000395 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000396 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000397 bool parseDirectiveCFISections();
398 bool parseDirectiveCFIStartProc();
399 bool parseDirectiveCFIEndProc();
400 bool parseDirectiveCFIDefCfaOffset();
401 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIAdjustCfaOffset();
403 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
405 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
406 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
407 bool parseDirectiveCFIRememberState();
408 bool parseDirectiveCFIRestoreState();
409 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
410 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
411 bool parseDirectiveCFIEscape();
412 bool parseDirectiveCFISignalFrame();
413 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000414
415 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000416 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000417 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000418 bool parseDirectiveEndMacro(StringRef Directive);
419 bool parseDirectiveMacro(SMLoc DirectiveLoc);
420 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000421
Eli Benderskyf483ff92012-12-20 19:05:53 +0000422 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000423 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000424 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000425 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000426 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000427 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000428
Eli Bendersky17233942013-01-15 22:59:42 +0000429 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000430 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000431
432 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000433 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000434
Jim Grosbach4b905842013-09-20 23:08:21 +0000435 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000436 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000437 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000438
Jim Grosbach4b905842013-09-20 23:08:21 +0000439 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000440
Jim Grosbach4b905842013-09-20 23:08:21 +0000441 bool parseDirectiveAbort(); // ".abort"
442 bool parseDirectiveInclude(); // ".include"
443 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000444
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000445 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
446 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000447 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000448 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000449 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000450 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000451 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
452 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000453 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000454 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
455 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
456 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
457 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000458 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000459
Jim Grosbach4b905842013-09-20 23:08:21 +0000460 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000461 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000462
Rafael Espindola34b9c512012-06-03 23:57:14 +0000463 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000464 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
465 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000466 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000467 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000468 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
469 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
470 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000471
Chad Rosierc7f552c2013-02-12 21:33:51 +0000472 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000473 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000474 size_t Len);
475
476 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000477 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000478
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000479 // "end"
480 bool parseDirectiveEnd(SMLoc DirectiveLoc);
481
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000482 // ".err" or ".error"
483 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000484
Nico Weber404012b2014-07-24 16:26:06 +0000485 // ".warning"
486 bool parseDirectiveWarning(SMLoc DirectiveLoc);
487
Eli Bendersky17233942013-01-15 22:59:42 +0000488 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000489};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000490}
Daniel Dunbar86033402010-07-12 17:54:38 +0000491
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000492namespace llvm {
493
494extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000495extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000496extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000497
498}
499
Chris Lattnerc35681b2010-01-19 19:46:13 +0000500enum { DEFAULT_ADDRSPACE = 0 };
501
David Blaikie9f380a32015-03-16 18:06:57 +0000502AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
503 const MCAsmInfo &MAI)
504 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
505 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
Alp Tokera55b95b2014-07-06 10:33:31 +0000506 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
Oliver Stannardcf6bfb12014-11-03 12:19:03 +0000507 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000508 // Save the old handler.
509 SavedDiagHandler = SrcMgr.getDiagHandler();
510 SavedDiagContext = SrcMgr.getDiagContext();
511 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000512 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000513 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000514
Daniel Dunbarc5011082010-07-12 18:12:02 +0000515 // Initialize the platform / file format parser.
Rafael Espindola90eb70c2015-08-14 13:31:17 +0000516 switch (Ctx.getObjectFileInfo()->getTargetTriple().getObjectFormat()) {
517 case Triple::COFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000518 PlatformParser.reset(createCOFFAsmParser());
519 break;
Rafael Espindola90eb70c2015-08-14 13:31:17 +0000520 case Triple::MachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000521 PlatformParser.reset(createDarwinAsmParser());
522 IsDarwin = true;
523 break;
Rafael Espindola90eb70c2015-08-14 13:31:17 +0000524 case Triple::ELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000525 PlatformParser.reset(createELFAsmParser());
526 break;
Rafael Espindola90eb70c2015-08-14 13:31:17 +0000527 case Triple::UnknownObjectFormat:
528 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000529 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000530
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000531 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000532 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000533
534 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000535}
536
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000537AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000538 assert((HadError || ActiveMacros.empty()) &&
539 "Unexpected active macro instantiation!");
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000540}
541
Jim Grosbach4b905842013-09-20 23:08:21 +0000542void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000543 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000544 for (std::vector<MacroInstantiation *>::const_reverse_iterator
545 it = ActiveMacros.rbegin(),
546 ie = ActiveMacros.rend();
547 it != ie; ++it)
548 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000549 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000550}
551
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000552void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
553 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
554 printMacroInstantiations();
555}
556
Chris Lattnera3a06812011-10-16 04:47:35 +0000557bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000558 if(getTargetParser().getTargetOptions().MCNoWarn)
559 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000560 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Chris Lattnera3a06812011-10-16 04:47:35 +0000561 return Error(L, Msg, Ranges);
Jim Grosbach4b905842013-09-20 23:08:21 +0000562 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
563 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000564 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000565}
566
Chris Lattnera3a06812011-10-16 04:47:35 +0000567bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000568 HadError = true;
Jim Grosbach4b905842013-09-20 23:08:21 +0000569 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
570 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000571 return true;
572}
573
Jim Grosbach4b905842013-09-20 23:08:21 +0000574bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000575 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000576 unsigned NewBuf =
577 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
578 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000579 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000580
Sean Callanan7a77eae2010-01-21 00:19:58 +0000581 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000582 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000583 return false;
584}
Daniel Dunbar43235712010-07-18 18:54:11 +0000585
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000586/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000587/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000588/// returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000589bool AsmParser::processIncbinFile(const std::string &Filename) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000590 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000591 unsigned NewBuf =
592 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
593 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000594 return true;
595
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000596 // Pick up the bytes from the file and emit them.
Rafael Espindola64e1af82013-07-02 15:49:13 +0000597 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderby109f25c2011-12-14 21:47:48 +0000598 return false;
599}
600
Alp Tokera55b95b2014-07-06 10:33:31 +0000601void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
602 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000603 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
604 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000605}
606
Sean Callanan7a77eae2010-01-21 00:19:58 +0000607const AsmToken &AsmParser::Lex() {
608 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000609
Sean Callanan7a77eae2010-01-21 00:19:58 +0000610 if (tok->is(AsmToken::Eof)) {
611 // If this is the end of an included file, pop the parent file off the
612 // include stack.
613 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
614 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000615 jumpToLoc(ParentIncludeLoc);
Sean Callanan7a77eae2010-01-21 00:19:58 +0000616 tok = &Lexer.Lex();
617 }
618 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000619
Sean Callanan7a77eae2010-01-21 00:19:58 +0000620 if (tok->is(AsmToken::Error))
Daniel Dunbard8a18452010-07-18 18:31:45 +0000621 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencer530ce852010-10-09 11:00:50 +0000622
Sean Callanan7a77eae2010-01-21 00:19:58 +0000623 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000624}
625
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000626bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000627 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000628 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000629 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000630
Chris Lattner36e02122009-06-21 20:54:55 +0000631 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000632 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000633
634 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000635 AsmCond StartingCondState = TheCondState;
636
Kevin Enderby6469fc22011-11-01 22:27:22 +0000637 // If we are generating dwarf for assembly source files save the initial text
638 // section and generate a .file directive.
639 if (getContext().getGenDwarfForAssembly()) {
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000640 MCSection *Sec = getStreamer().getCurrentSection().first;
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000641 if (!Sec->getBeginSymbol()) {
642 MCSymbol *SectionStartSym = getContext().createTempSymbol();
643 getStreamer().EmitLabel(SectionStartSym);
644 Sec->setBeginSymbol(SectionStartSym);
645 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000646 bool InsertResult = getContext().addGenDwarfSection(Sec);
647 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000648 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000649 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
650 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000651 }
652
Chris Lattner73f36112009-07-02 21:53:43 +0000653 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000654 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000655 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000656 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000657 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000658
Daniel Dunbar43325c42010-09-09 22:42:56 +0000659 // We had an error, validate that one was emitted and recover by skipping to
660 // the next line.
661 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000662 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000663 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000664
665 if (TheCondState.TheCond != StartingCondState.TheCond ||
666 TheCondState.Ignore != StartingCondState.Ignore)
667 return TokError("unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000668
669 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000670 const auto &LineTables = getContext().getMCDwarfLineTables();
671 if (!LineTables.empty()) {
672 unsigned Index = 0;
673 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
674 if (File.Name.empty() && Index != 0)
675 TokError("unassigned file number: " + Twine(Index) +
676 " for .file directives");
677 ++Index;
678 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000679 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000680
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000681 // Check to see that all assembler local symbols were actually defined.
682 // Targets that don't do subsections via symbols may not want this, though,
683 // so conservatively exclude them. Only do this if we're finalizing, though,
684 // as otherwise we won't necessarilly have seen everything yet.
685 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
686 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
687 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
Jim Grosbach4b905842013-09-20 23:08:21 +0000688 e = Symbols.end();
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000689 i != e; ++i) {
690 MCSymbol *Sym = i->getValue();
691 // Variable symbols may not be marked as defined, so check those
692 // explicitly. If we know it's a variable, we have a definition for
693 // the purposes of this check.
694 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
695 // FIXME: We would really like to refer back to where the symbol was
696 // first referenced for a source location. We need to add something
697 // to track that. Currently, we just point to the end of the file.
Jim Grosbach4b905842013-09-20 23:08:21 +0000698 printMessage(
699 getLexer().getLoc(), SourceMgr::DK_Error,
700 "assembler local symbol '" + Sym->getName() + "' not defined");
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000701 }
702 }
703
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000704 // Finalize the output stream if there are no errors and if the client wants
705 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000706 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000707 Out.Finish();
708
Chris Lattner73f36112009-07-02 21:53:43 +0000709 return HadError;
Chris Lattner36e02122009-06-21 20:54:55 +0000710}
711
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000712void AsmParser::checkForValidSection() {
Peter Collingbourne2f495b92013-04-17 21:18:16 +0000713 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbare5444a82010-09-09 22:42:59 +0000714 TokError("expected section directive before assembly directive");
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000715 Out.InitSections(false);
Daniel Dunbare5444a82010-09-09 22:42:59 +0000716 }
717}
718
Jim Grosbach4b905842013-09-20 23:08:21 +0000719/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000720void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000721 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Sean Callanan686ed8d2010-01-19 20:22:31 +0000722 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000723
Chris Lattnere5074c42009-06-22 01:29:09 +0000724 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000725 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan686ed8d2010-01-19 20:22:31 +0000726 Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000727}
728
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000729StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000730 const char *Start = getTok().getLoc().getPointer();
731
Jim Grosbach4b905842013-09-20 23:08:21 +0000732 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000733 Lex();
734
735 const char *End = getTok().getLoc().getPointer();
736 return StringRef(Start, End - Start);
737}
Chris Lattner78db3622009-06-22 05:51:26 +0000738
Jim Grosbach4b905842013-09-20 23:08:21 +0000739StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000740 const char *Start = getTok().getLoc().getPointer();
741
742 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000743 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000744 Lex();
745
746 const char *End = getTok().getLoc().getPointer();
747 return StringRef(Start, End - Start);
748}
749
Jim Grosbach4b905842013-09-20 23:08:21 +0000750/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000751/// NOTE: This assumes the leading '(' has already been consumed.
752///
753/// parenexpr ::= expr)
754///
Jim Grosbach4b905842013-09-20 23:08:21 +0000755bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
756 if (parseExpression(Res))
757 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000758 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000759 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000760 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000761 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000762 return false;
763}
Chris Lattner78db3622009-06-22 05:51:26 +0000764
Jim Grosbach4b905842013-09-20 23:08:21 +0000765/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000766/// NOTE: This assumes the leading '[' has already been consumed.
767///
768/// bracketexpr ::= expr]
769///
Jim Grosbach4b905842013-09-20 23:08:21 +0000770bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
771 if (parseExpression(Res))
772 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000773 if (Lexer.isNot(AsmToken::RBrac))
774 return TokError("expected ']' in brackets expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000775 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000776 Lex();
777 return false;
778}
779
Jim Grosbach4b905842013-09-20 23:08:21 +0000780/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000781/// primaryexpr ::= (parenexpr
782/// primaryexpr ::= symbol
783/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000784/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000785/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000786bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000787 SMLoc FirstTokenLoc = getLexer().getLoc();
788 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
789 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000790 default:
791 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000792 // If we have an error assume that we've already handled it.
793 case AsmToken::Error:
794 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000795 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000796 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000797 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000798 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000799 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000800 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000801 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000802 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000803 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000804 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000805 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000806 if (parseIdentifier(Identifier)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000807 if (FirstTokenKind == AsmToken::Dollar) {
808 if (Lexer.getMAI().getDollarIsPC()) {
809 // This is a '$' reference, which references the current PC. Emit a
810 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000811 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000812 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000813 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000814 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000815 EndLoc = FirstTokenLoc;
816 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000817 }
818 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000819 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000820 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000821 // Parse symbol variant
822 std::pair<StringRef, StringRef> Split;
823 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000824 if (FirstTokenKind == AsmToken::String) {
825 if (Lexer.is(AsmToken::At)) {
826 Lexer.Lex(); // eat @
827 SMLoc AtLoc = getLexer().getLoc();
828 StringRef VName;
829 if (parseIdentifier(VName))
830 return Error(AtLoc, "expected symbol variant after '@'");
831
832 Split = std::make_pair(Identifier, VName);
833 }
834 } else {
835 Split = Identifier.split('@');
836 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000837 } else if (Lexer.is(AsmToken::LParen)) {
838 Lexer.Lex(); // eat (
839 StringRef VName;
840 parseIdentifier(VName);
841 if (Lexer.isNot(AsmToken::RParen)) {
842 return Error(Lexer.getTok().getLoc(),
843 "unexpected token in variant, expected ')'");
844 }
845 Lexer.Lex(); // eat )
846 Split = std::make_pair(Identifier, VName);
847 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000848
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000849 EndLoc = SMLoc::getFromPointer(Identifier.end());
850
Daniel Dunbard20cda02009-10-16 01:34:54 +0000851 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000852 StringRef SymbolName = Identifier;
853 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000854
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000855 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000856 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000857 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000858 if (Variant != MCSymbolRefExpr::VK_Invalid) {
859 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000860 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000861 Variant = MCSymbolRefExpr::VK_None;
862 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000863 return Error(SMLoc::getFromPointer(Split.second.begin()),
864 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000865 }
866 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000867
Jim Grosbach6f482002015-05-18 18:43:14 +0000868 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000869
Daniel Dunbard20cda02009-10-16 01:34:54 +0000870 // If this is an absolute variable reference, substitute it now to preserve
871 // semantics in the face of reassignment.
Daniel Dunbar7a989da2010-05-05 17:41:00 +0000872 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar55992562010-03-15 23:51:06 +0000873 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +0000874 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +0000875
Daniel Dunbar7a989da2010-05-05 17:41:00 +0000876 Res = Sym->getVariableValue();
Daniel Dunbard20cda02009-10-16 01:34:54 +0000877 return false;
878 }
879
880 // Otherwise create a symbol ref.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000881 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Chris Lattner78db3622009-06-22 05:51:26 +0000882 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +0000883 }
David Woodhousef42a6662014-02-01 16:20:54 +0000884 case AsmToken::BigNum:
885 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +0000886 case AsmToken::Integer: {
887 SMLoc Loc = getTok().getLoc();
888 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000889 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000890 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000891 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +0000892 // Look for 'b' or 'f' following an Integer as a directional label
893 if (Lexer.getKind() == AsmToken::Identifier) {
894 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +0000895 // Lookup the symbol variant if used.
896 std::pair<StringRef, StringRef> Split = IDVal.split('@');
897 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
898 if (Split.first.size() != IDVal.size()) {
899 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +0000900 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +0000901 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000902 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +0000903 }
Jim Grosbach4b905842013-09-20 23:08:21 +0000904 if (IDVal == "f" || IDVal == "b") {
905 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +0000906 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +0000907 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +0000908 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderby0510b482010-05-17 23:08:19 +0000909 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000910 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +0000911 Lex(); // Eat identifier.
912 }
913 }
Chris Lattner78db3622009-06-22 05:51:26 +0000914 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +0000915 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000916 case AsmToken::Real: {
917 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +0000918 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000919 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000920 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000921 Lex(); // Eat token.
922 return false;
923 }
Chris Lattner6b55cb92010-04-14 04:40:28 +0000924 case AsmToken::Dot: {
925 // This is a '.' reference, which references the current PC. Emit a
926 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000927 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000928 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000929 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000930 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000931 Lex(); // Eat identifier.
932 return false;
933 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000934 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000935 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +0000936 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000937 case AsmToken::LBrac:
938 if (!PlatformParser->HasBracketExpressions())
939 return TokError("brackets expression not supported on this target");
940 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +0000941 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000942 case AsmToken::Minus:
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::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000947 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000948 case AsmToken::Plus:
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::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000953 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000954 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000955 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000956 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000957 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000958 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000959 return false;
Chris Lattner78db3622009-06-22 05:51:26 +0000960 }
961}
Chris Lattner7fdbce72009-06-22 06:32:03 +0000962
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000963bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +0000964 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000965 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +0000966}
967
Daniel Dunbar55f16672010-09-17 02:47:07 +0000968const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +0000969AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000970 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +0000971 // Ask the target implementation about this expression first.
972 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
973 if (NewE)
974 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000975 // Recurse over the given expression, rebuilding it to apply the given variant
976 // if there is exactly one symbol.
977 switch (E->getKind()) {
978 case MCExpr::Target:
979 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +0000980 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000981
982 case MCExpr::SymbolRef: {
983 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
984
985 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000986 TokError("invalid variant on expression '" + getTok().getIdentifier() +
987 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000988 return E;
989 }
990
Jim Grosbach13760bd2015-05-30 01:25:56 +0000991 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +0000992 }
993
994 case MCExpr::Unary: {
995 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +0000996 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +0000997 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +0000998 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000999 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001000 }
1001
1002 case MCExpr::Binary: {
1003 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001004 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1005 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001006
1007 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001008 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001009
Jim Grosbach4b905842013-09-20 23:08:21 +00001010 if (!LHS)
1011 LHS = BE->getLHS();
1012 if (!RHS)
1013 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001014
Jim Grosbach13760bd2015-05-30 01:25:56 +00001015 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001016 }
1017 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001018
Craig Toppera2886c22012-02-07 05:05:23 +00001019 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001020}
1021
Jim Grosbach4b905842013-09-20 23:08:21 +00001022/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001023///
Jim Grosbachbd164242011-08-20 16:24:13 +00001024/// expr ::= expr &&,|| expr -> lowest.
1025/// expr ::= expr |,^,&,! expr
1026/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1027/// expr ::= expr <<,>> expr
1028/// expr ::= expr +,- expr
1029/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001030/// expr ::= primaryexpr
1031///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001032bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001033 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001034 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001035 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001036 return true;
1037
Daniel Dunbar55f16672010-09-17 02:47:07 +00001038 // As a special case, we support 'a op b @ modifier' by rewriting the
1039 // expression to include the modifier. This is inefficient, but in general we
1040 // expect users to use 'a@modifier op b'.
1041 if (Lexer.getKind() == AsmToken::At) {
1042 Lex();
1043
1044 if (Lexer.isNot(AsmToken::Identifier))
1045 return TokError("unexpected symbol modifier following '@'");
1046
1047 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001048 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001049 if (Variant == MCSymbolRefExpr::VK_Invalid)
1050 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1051
Jim Grosbach4b905842013-09-20 23:08:21 +00001052 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001053 if (!ModifiedRes) {
1054 return TokError("invalid modifier '" + getTok().getIdentifier() +
1055 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001056 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001057
Daniel Dunbar55f16672010-09-17 02:47:07 +00001058 Res = ModifiedRes;
1059 Lex();
1060 }
1061
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001062 // Try to constant fold it up front, if possible.
1063 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001064 if (Res->evaluateAsAbsolute(Value))
1065 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001066
1067 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001068}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001069
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001070bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001071 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001072 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001073}
1074
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001075bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1076 SMLoc &EndLoc) {
1077 if (parseParenExpr(Res, EndLoc))
1078 return true;
1079
1080 for (; ParenDepth > 0; --ParenDepth) {
1081 if (parseBinOpRHS(1, Res, EndLoc))
1082 return true;
1083
1084 // We don't Lex() the last RParen.
1085 // This is the same behavior as parseParenExpression().
1086 if (ParenDepth - 1 > 0) {
1087 if (Lexer.isNot(AsmToken::RParen))
1088 return TokError("expected ')' in parentheses expression");
1089 EndLoc = Lexer.getTok().getEndLoc();
1090 Lex();
1091 }
1092 }
1093 return false;
1094}
1095
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001096bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001097 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001098
Daniel Dunbar75630b32009-06-30 02:10:03 +00001099 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001100 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001101 return true;
1102
Jim Grosbach13760bd2015-05-30 01:25:56 +00001103 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001104 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001105
1106 return false;
1107}
1108
Ahmed Bougacha457852f2015-04-28 00:17:39 +00001109unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1110 MCBinaryExpr::Opcode &Kind) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001111 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001112 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001113 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001114
Jim Grosbach4b905842013-09-20 23:08:21 +00001115 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001116 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001117 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001118 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001119 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001120 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001121 return 1;
1122
Jim Grosbach4b905842013-09-20 23:08:21 +00001123 // Low Precedence: |, &, ^
1124 //
1125 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001126 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001127 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001128 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001129 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001130 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001131 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001132 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001133 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001134 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001135
Jim Grosbach4b905842013-09-20 23:08:21 +00001136 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001137 case AsmToken::EqualEqual:
1138 Kind = MCBinaryExpr::EQ;
1139 return 3;
1140 case AsmToken::ExclaimEqual:
1141 case AsmToken::LessGreater:
1142 Kind = MCBinaryExpr::NE;
1143 return 3;
1144 case AsmToken::Less:
1145 Kind = MCBinaryExpr::LT;
1146 return 3;
1147 case AsmToken::LessEqual:
1148 Kind = MCBinaryExpr::LTE;
1149 return 3;
1150 case AsmToken::Greater:
1151 Kind = MCBinaryExpr::GT;
1152 return 3;
1153 case AsmToken::GreaterEqual:
1154 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001155 return 3;
1156
Jim Grosbach4b905842013-09-20 23:08:21 +00001157 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001158 case AsmToken::LessLess:
1159 Kind = MCBinaryExpr::Shl;
1160 return 4;
1161 case AsmToken::GreaterGreater:
Ahmed Bougacha177c1482015-04-28 00:21:32 +00001162 Kind = MAI.shouldUseLogicalShr() ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001163 return 4;
1164
Jim Grosbach4b905842013-09-20 23:08:21 +00001165 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001166 case AsmToken::Plus:
1167 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001168 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001169 case AsmToken::Minus:
1170 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001171 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001172
Jim Grosbach4b905842013-09-20 23:08:21 +00001173 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001174 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001175 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001176 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001177 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001178 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001179 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001180 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001181 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001182 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001183 }
1184}
1185
Jim Grosbach4b905842013-09-20 23:08:21 +00001186/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001187/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001188bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001189 SMLoc &EndLoc) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001190 while (1) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001191 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001192 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001193
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001194 // If the next token is lower precedence than we are allowed to eat, return
1195 // successfully with what we ate already.
1196 if (TokPrec < Precedence)
1197 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001198
Sean Callanan686ed8d2010-01-19 20:22:31 +00001199 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001200
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001201 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001202 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001203 if (parsePrimaryExpr(RHS, EndLoc))
1204 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001205
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001206 // If BinOp binds less tightly with RHS than the operator after RHS, let
1207 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001208 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001209 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001210 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1211 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001212
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001213 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001214 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001215 }
1216}
1217
Chris Lattner36e02122009-06-21 20:54:55 +00001218/// ParseStatement:
1219/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001220/// ::= Label* Directive ...Operands... EndOfStatement
1221/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001222bool AsmParser::parseStatement(ParseStatementInfo &Info,
1223 MCAsmParserSemaCallback *SI) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001224 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001225 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001226 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001227 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001228 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001229
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001230 // Statements always start with an identifier or are a full line comment.
Sean Callanan936b0d32010-01-19 21:44:56 +00001231 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001232 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001233 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001234 int64_t LocalLabelVal = -1;
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001235 // A full line comment is a '#' as the first token.
Kevin Enderby72553612011-09-13 23:45:18 +00001236 if (Lexer.is(AsmToken::Hash))
Jim Grosbach4b905842013-09-20 23:08:21 +00001237 return parseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar3f561042011-03-25 17:47:14 +00001238
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001239 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001240 if (Lexer.is(AsmToken::Integer)) {
1241 LocalLabelVal = getTok().getIntVal();
1242 if (LocalLabelVal < 0) {
1243 if (!TheCondState.Ignore)
1244 return TokError("unexpected token at start of statement");
1245 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001246 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001247 IDVal = getTok().getString();
1248 Lex(); // Consume the integer token to be used as an identifier token.
1249 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001250 if (!TheCondState.Ignore)
1251 return TokError("unexpected token at start of statement");
Kevin Enderby0510b482010-05-17 23:08:19 +00001252 }
1253 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001254 } else if (Lexer.is(AsmToken::Dot)) {
1255 // Treat '.' as a valid identifier in this context.
1256 Lex();
1257 IDVal = ".";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001258 } else if (parseIdentifier(IDVal)) {
Chris Lattner926885c2010-04-17 18:14:27 +00001259 if (!TheCondState.Ignore)
1260 return TokError("unexpected token at start of statement");
1261 IDVal = "";
1262 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001263
Chris Lattner926885c2010-04-17 18:14:27 +00001264 // Handle conditional assembly here before checking for skipping. We
1265 // have to do this so that .endif isn't skipped in a ".if 0" block for
1266 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001267 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001268 DirectiveKindMap.find(IDVal);
1269 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1270 ? DK_NO_DIRECTIVE
1271 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001272 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001273 default:
1274 break;
1275 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001276 case DK_IFEQ:
1277 case DK_IFGE:
1278 case DK_IFGT:
1279 case DK_IFLE:
1280 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001281 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001282 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001283 case DK_IFB:
1284 return parseDirectiveIfb(IDLoc, true);
1285 case DK_IFNB:
1286 return parseDirectiveIfb(IDLoc, false);
1287 case DK_IFC:
1288 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001289 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001290 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001291 case DK_IFNC:
1292 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001293 case DK_IFNES:
1294 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001295 case DK_IFDEF:
1296 return parseDirectiveIfdef(IDLoc, true);
1297 case DK_IFNDEF:
1298 case DK_IFNOTDEF:
1299 return parseDirectiveIfdef(IDLoc, false);
1300 case DK_ELSEIF:
1301 return parseDirectiveElseIf(IDLoc);
1302 case DK_ELSE:
1303 return parseDirectiveElse(IDLoc);
1304 case DK_ENDIF:
1305 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001306 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001307
Eli Bendersky88024712013-01-16 19:32:36 +00001308 // Ignore the statement if in the middle of inactive conditional
1309 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001310 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001311 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001312 return false;
1313 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001314
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001315 // FIXME: Recurse on local labels?
1316
1317 // See what kind of statement we have.
1318 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001319 case AsmToken::Colon: {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001320 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001321
Chris Lattner36e02122009-06-21 20:54:55 +00001322 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001323 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001324
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001325 // Diagnose attempt to use '.' as a label.
1326 if (IDVal == ".")
1327 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1328
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001329 // Diagnose attempt to use a variable as a label.
1330 //
1331 // FIXME: Diagnostics. Note the location of the definition as a label.
1332 // FIXME: This doesn't diagnose assignment to a symbol which has been
1333 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001334 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001335 if (LocalLabelVal == -1) {
1336 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001337 StringRef RewrittenLabel =
1338 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1339 assert(RewrittenLabel.size() &&
1340 "We should have an internal name here.");
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001341 Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
1342 IDVal.size(), RewrittenLabel));
1343 IDVal = RewrittenLabel;
1344 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001345 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001346 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001347 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001348
1349 Sym->redefineIfPossible();
1350
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001351 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001352 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001353
Daniel Dunbare73b2672009-08-26 22:13:22 +00001354 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001355 if (!ParsingInlineAsm)
1356 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001357
Kevin Enderbye7739d42011-12-09 18:09:40 +00001358 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001359 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001360 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001361 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1362 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001363
Tim Northover1744d0a2013-10-25 12:49:50 +00001364 getTargetParser().onLabelParsed(Sym);
1365
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001366 // Consume any end of statement token, if present, to avoid spurious
1367 // AddBlankLine calls().
1368 if (Lexer.is(AsmToken::EndOfStatement)) {
1369 Lex();
1370 if (Lexer.is(AsmToken::Eof))
1371 return false;
1372 }
1373
Eli Friedman0f4871d2012-10-22 23:58:19 +00001374 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001375 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001376
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001377 case AsmToken::Equal:
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001378 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001379 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001380
Jim Grosbach4b905842013-09-20 23:08:21 +00001381 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001382
1383 default: // Normal instruction or directive.
1384 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001385 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001386
1387 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001388 if (areMacrosEnabled())
1389 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1390 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001391 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001392
Michael J. Spencer530ce852010-10-09 11:00:50 +00001393 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001394
Eli Bendersky17233942013-01-15 22:59:42 +00001395 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001396 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001397 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001398 //
Eli Bendersky17233942013-01-15 22:59:42 +00001399 // 1. The target-specific assembly parser. Some directives are target
1400 // specific or may potentially behave differently on certain targets.
1401 // 2. Asm parser extensions. For example, platform-specific parsers
1402 // (like the ELF parser) register themselves as extensions.
1403 // 3. The generic directive parser implemented by this class. These are
1404 // all the directives that behave in a target and platform independent
1405 // manner, or at least have a default behavior that's shared between
1406 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001407
Eli Bendersky17233942013-01-15 22:59:42 +00001408 // First query the target-specific parser. It will return 'true' if it
1409 // isn't interested in this directive.
Akira Hatanakad3590752012-07-05 19:09:33 +00001410 if (!getTargetParser().ParseDirective(ID))
1411 return false;
1412
Alp Tokercb402912014-01-24 17:20:08 +00001413 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001414 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001415 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1416 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001417 if (Handler.first)
1418 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1419
1420 // Finally, if no one else is interested in this directive, it must be
1421 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001422 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001423 default:
1424 break;
1425 case DK_SET:
1426 case DK_EQU:
1427 return parseDirectiveSet(IDVal, true);
1428 case DK_EQUIV:
1429 return parseDirectiveSet(IDVal, false);
1430 case DK_ASCII:
1431 return parseDirectiveAscii(IDVal, false);
1432 case DK_ASCIZ:
1433 case DK_STRING:
1434 return parseDirectiveAscii(IDVal, true);
1435 case DK_BYTE:
1436 return parseDirectiveValue(1);
1437 case DK_SHORT:
1438 case DK_VALUE:
1439 case DK_2BYTE:
1440 return parseDirectiveValue(2);
1441 case DK_LONG:
1442 case DK_INT:
1443 case DK_4BYTE:
1444 return parseDirectiveValue(4);
1445 case DK_QUAD:
1446 case DK_8BYTE:
1447 return parseDirectiveValue(8);
David Woodhoused6de0d92014-02-01 16:20:59 +00001448 case DK_OCTA:
1449 return parseDirectiveOctaValue();
Jim Grosbach4b905842013-09-20 23:08:21 +00001450 case DK_SINGLE:
1451 case DK_FLOAT:
1452 return parseDirectiveRealValue(APFloat::IEEEsingle);
1453 case DK_DOUBLE:
1454 return parseDirectiveRealValue(APFloat::IEEEdouble);
1455 case DK_ALIGN: {
1456 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1457 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1458 }
1459 case DK_ALIGN32: {
1460 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1461 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1462 }
1463 case DK_BALIGN:
1464 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1465 case DK_BALIGNW:
1466 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1467 case DK_BALIGNL:
1468 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1469 case DK_P2ALIGN:
1470 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1471 case DK_P2ALIGNW:
1472 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1473 case DK_P2ALIGNL:
1474 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1475 case DK_ORG:
1476 return parseDirectiveOrg();
1477 case DK_FILL:
1478 return parseDirectiveFill();
1479 case DK_ZERO:
1480 return parseDirectiveZero();
1481 case DK_EXTERN:
1482 eatToEndOfStatement(); // .extern is the default, ignore it.
1483 return false;
1484 case DK_GLOBL:
1485 case DK_GLOBAL:
1486 return parseDirectiveSymbolAttribute(MCSA_Global);
1487 case DK_LAZY_REFERENCE:
1488 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1489 case DK_NO_DEAD_STRIP:
1490 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1491 case DK_SYMBOL_RESOLVER:
1492 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1493 case DK_PRIVATE_EXTERN:
1494 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1495 case DK_REFERENCE:
1496 return parseDirectiveSymbolAttribute(MCSA_Reference);
1497 case DK_WEAK_DEFINITION:
1498 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1499 case DK_WEAK_REFERENCE:
1500 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1501 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1502 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1503 case DK_COMM:
1504 case DK_COMMON:
1505 return parseDirectiveComm(/*IsLocal=*/false);
1506 case DK_LCOMM:
1507 return parseDirectiveComm(/*IsLocal=*/true);
1508 case DK_ABORT:
1509 return parseDirectiveAbort();
1510 case DK_INCLUDE:
1511 return parseDirectiveInclude();
1512 case DK_INCBIN:
1513 return parseDirectiveIncbin();
1514 case DK_CODE16:
1515 case DK_CODE16GCC:
1516 return TokError(Twine(IDVal) + " not supported yet");
1517 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001518 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001519 case DK_IRP:
1520 return parseDirectiveIrp(IDLoc);
1521 case DK_IRPC:
1522 return parseDirectiveIrpc(IDLoc);
1523 case DK_ENDR:
1524 return parseDirectiveEndr(IDLoc);
1525 case DK_BUNDLE_ALIGN_MODE:
1526 return parseDirectiveBundleAlignMode();
1527 case DK_BUNDLE_LOCK:
1528 return parseDirectiveBundleLock();
1529 case DK_BUNDLE_UNLOCK:
1530 return parseDirectiveBundleUnlock();
1531 case DK_SLEB128:
1532 return parseDirectiveLEB128(true);
1533 case DK_ULEB128:
1534 return parseDirectiveLEB128(false);
1535 case DK_SPACE:
1536 case DK_SKIP:
1537 return parseDirectiveSpace(IDVal);
1538 case DK_FILE:
1539 return parseDirectiveFile(IDLoc);
1540 case DK_LINE:
1541 return parseDirectiveLine();
1542 case DK_LOC:
1543 return parseDirectiveLoc();
1544 case DK_STABS:
1545 return parseDirectiveStabs();
1546 case DK_CFI_SECTIONS:
1547 return parseDirectiveCFISections();
1548 case DK_CFI_STARTPROC:
1549 return parseDirectiveCFIStartProc();
1550 case DK_CFI_ENDPROC:
1551 return parseDirectiveCFIEndProc();
1552 case DK_CFI_DEF_CFA:
1553 return parseDirectiveCFIDefCfa(IDLoc);
1554 case DK_CFI_DEF_CFA_OFFSET:
1555 return parseDirectiveCFIDefCfaOffset();
1556 case DK_CFI_ADJUST_CFA_OFFSET:
1557 return parseDirectiveCFIAdjustCfaOffset();
1558 case DK_CFI_DEF_CFA_REGISTER:
1559 return parseDirectiveCFIDefCfaRegister(IDLoc);
1560 case DK_CFI_OFFSET:
1561 return parseDirectiveCFIOffset(IDLoc);
1562 case DK_CFI_REL_OFFSET:
1563 return parseDirectiveCFIRelOffset(IDLoc);
1564 case DK_CFI_PERSONALITY:
1565 return parseDirectiveCFIPersonalityOrLsda(true);
1566 case DK_CFI_LSDA:
1567 return parseDirectiveCFIPersonalityOrLsda(false);
1568 case DK_CFI_REMEMBER_STATE:
1569 return parseDirectiveCFIRememberState();
1570 case DK_CFI_RESTORE_STATE:
1571 return parseDirectiveCFIRestoreState();
1572 case DK_CFI_SAME_VALUE:
1573 return parseDirectiveCFISameValue(IDLoc);
1574 case DK_CFI_RESTORE:
1575 return parseDirectiveCFIRestore(IDLoc);
1576 case DK_CFI_ESCAPE:
1577 return parseDirectiveCFIEscape();
1578 case DK_CFI_SIGNAL_FRAME:
1579 return parseDirectiveCFISignalFrame();
1580 case DK_CFI_UNDEFINED:
1581 return parseDirectiveCFIUndefined(IDLoc);
1582 case DK_CFI_REGISTER:
1583 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001584 case DK_CFI_WINDOW_SAVE:
1585 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001586 case DK_MACROS_ON:
1587 case DK_MACROS_OFF:
1588 return parseDirectiveMacrosOnOff(IDVal);
1589 case DK_MACRO:
1590 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001591 case DK_EXITM:
1592 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001593 case DK_ENDM:
1594 case DK_ENDMACRO:
1595 return parseDirectiveEndMacro(IDVal);
1596 case DK_PURGEM:
1597 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001598 case DK_END:
1599 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001600 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001601 return parseDirectiveError(IDLoc, false);
1602 case DK_ERROR:
1603 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001604 case DK_WARNING:
1605 return parseDirectiveWarning(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00001606 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001607
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001608 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001609 }
Chris Lattner36e02122009-06-21 20:54:55 +00001610
Chad Rosierc7f552c2013-02-12 21:33:51 +00001611 // __asm _emit or __asm __emit
1612 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1613 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001614 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001615
1616 // __asm align
1617 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001618 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001619
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001620 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001621
Chris Lattner7cbfa442010-05-19 23:34:33 +00001622 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001623 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001624 ParseInstructionInfo IInfo(Info.AsmRewrites);
Jim Grosbach4b905842013-09-20 23:08:21 +00001625 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001626 Info.ParsedOperands);
Chad Rosier149e8e02012-12-12 22:45:52 +00001627 Info.ParseError = HadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001628
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001629 // Dump the parsed representation, if requested.
1630 if (getShowParsedOperands()) {
1631 SmallString<256> Str;
1632 raw_svector_ostream OS(Str);
1633 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001634 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001635 if (i != 0)
1636 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001637 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001638 }
1639 OS << "]";
1640
Jim Grosbach4b905842013-09-20 23:08:21 +00001641 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001642 }
1643
Oliver Stannard8b273082014-06-19 15:52:37 +00001644 // If we are generating dwarf for the current section then generate a .loc
1645 // directive for the instruction.
Kevin Enderby6469fc22011-11-01 22:27:22 +00001646 if (!HadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00001647 getContext().getGenDwarfSectionSyms().count(
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001648 getStreamer().getCurrentSection().first)) {
1649 unsigned Line;
1650 if (ActiveMacros.empty())
1651 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1652 else
Frederic Riss16238d92015-06-25 21:57:33 +00001653 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1654 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001655
Eli Bendersky88024712013-01-16 19:32:36 +00001656 // If we previously parsed a cpp hash file line comment then make sure the
1657 // current Dwarf File is for the CppHashFilename if not then emit the
1658 // Dwarf File table for it and adjust the line number for the .loc.
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001659 if (CppHashFilename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00001660 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1661 0, StringRef(), CppHashFilename);
1662 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001663
Jim Grosbach4b905842013-09-20 23:08:21 +00001664 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1665 // cache with the different Loc from the call above we save the last
1666 // info we queried here with SrcMgr.FindLineNumber().
1667 unsigned CppHashLocLineNo;
1668 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1669 CppHashLocLineNo = LastQueryLine;
1670 else {
1671 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1672 LastQueryLine = CppHashLocLineNo;
1673 LastQueryIDLoc = CppHashLoc;
1674 LastQueryBuffer = CppHashBuf;
1675 }
1676 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00001677 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001678
Jim Grosbach4b905842013-09-20 23:08:21 +00001679 getStreamer().EmitDwarfLocDirective(
1680 getContext().getGenDwarfFileNumber(), Line, 0,
1681 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1682 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00001683 }
1684
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00001685 // If parsing succeeded, match the instruction.
Chad Rosier49963552012-10-13 00:26:04 +00001686 if (!HadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00001687 uint64_t ErrorInfo;
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001688 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1689 Info.ParsedOperands, Out,
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00001690 ErrorInfo, ParsingInlineAsm);
Chad Rosier49963552012-10-13 00:26:04 +00001691 }
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001692
Chris Lattnera2a9d162010-09-11 16:18:25 +00001693 // Don't skip the rest of the line, the instruction parser is responsible for
1694 // that.
1695 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00001696}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00001697
Jim Grosbach4b905842013-09-20 23:08:21 +00001698/// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
Kevin Enderby72553612011-09-13 23:45:18 +00001699/// since they may not be able to be tokenized to get to the end of line token.
Jim Grosbach4b905842013-09-20 23:08:21 +00001700void AsmParser::eatToEndOfLine() {
Rafael Espindolae0d09082011-10-19 18:48:52 +00001701 if (!Lexer.is(AsmToken::EndOfStatement))
1702 Lexer.LexUntilEndOfLine();
Jim Grosbach4b905842013-09-20 23:08:21 +00001703 // Eat EOL.
1704 Lex();
Kevin Enderby72553612011-09-13 23:45:18 +00001705}
1706
Jim Grosbach4b905842013-09-20 23:08:21 +00001707/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00001708/// ::= # number "filename"
1709/// or just as a full line comment if it doesn't have a number and a string.
Jim Grosbach4b905842013-09-20 23:08:21 +00001710bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
Kevin Enderby72553612011-09-13 23:45:18 +00001711 Lex(); // Eat the hash token.
1712
1713 if (getLexer().isNot(AsmToken::Integer)) {
1714 // Consume the line since in cases it is not a well-formed line directive,
1715 // as if were simply a full line comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001716 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001717 return false;
1718 }
1719
1720 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00001721 Lex();
1722
1723 if (getLexer().isNot(AsmToken::String)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001724 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001725 return false;
1726 }
1727
1728 StringRef Filename = getTok().getString();
1729 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00001730 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00001731
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001732 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1733 CppHashLoc = L;
1734 CppHashFilename = Filename;
1735 CppHashLineNumber = LineNumber;
Kevin Enderby27121c12012-11-05 21:55:41 +00001736 CppHashBuf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00001737
1738 // Ignore any trailing characters, they're just comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001739 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001740 return false;
1741}
1742
Jim Grosbach4b905842013-09-20 23:08:21 +00001743/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001744/// for the Filename and LineNo if any in the diagnostic.
1745void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001746 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001747 raw_ostream &OS = errs();
1748
1749 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1750 const SMLoc &DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00001751 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1752 unsigned CppHashBuf =
1753 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001754
Jim Grosbach4b905842013-09-20 23:08:21 +00001755 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001756 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00001757 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1758 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1759 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001760 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1761 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001762 }
1763
Eric Christophera7c32732012-12-18 00:30:54 +00001764 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001765 // manager changed or buffer changed (like in a nested include) then just
1766 // print the normal diagnostic using its Filename and LineNo.
Jim Grosbach4b905842013-09-20 23:08:21 +00001767 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001768 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001769 if (Parser->SavedDiagHandler)
1770 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1771 else
Craig Topper353eda42014-04-24 06:44:33 +00001772 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001773 return;
1774 }
1775
Eric Christophera7c32732012-12-18 00:30:54 +00001776 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001777 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1778 // the diagnostic.
Jakub Staszakec2ffa92013-09-16 22:03:38 +00001779 const std::string &Filename = Parser->CppHashFilename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001780
1781 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1782 int CppHashLocLineNo =
1783 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001784 int LineNo =
1785 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001786
Jim Grosbach4b905842013-09-20 23:08:21 +00001787 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1788 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00001789 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001790
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001791 if (Parser->SavedDiagHandler)
1792 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1793 else
Craig Topper353eda42014-04-24 06:44:33 +00001794 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001795}
1796
Rafael Espindola2c064482012-08-21 18:29:30 +00001797// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1798// difference being that that function accepts '@' as part of identifiers and
1799// we can't do that. AsmLexer.cpp should probably be changed to handle
1800// '@' as a special case when needed.
1801static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001802 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1803 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00001804}
1805
Rafael Espindola34b9c512012-06-03 23:57:14 +00001806bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00001807 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00001808 ArrayRef<MCAsmMacroArgument> A,
1809 bool EnableAtPseudoVariable, const SMLoc &L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001810 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00001811 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00001812 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00001813 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001814
Preston Gurd05500642012-09-19 20:36:12 +00001815 // A macro without parameters is handled differently on Darwin:
1816 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001817 while (!Body.empty()) {
1818 // Scan for the next substitution.
1819 std::size_t End = Body.size(), Pos = 0;
1820 for (; Pos != End; ++Pos) {
1821 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00001822 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001823 // This macro has no parameters, look for $0, $1, etc.
1824 if (Body[Pos] != '$' || Pos + 1 == End)
1825 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001826
Rafael Espindola1134ab232011-06-05 02:43:45 +00001827 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00001828 if (Next == '$' || Next == 'n' ||
1829 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00001830 break;
1831 } else {
1832 // This macro has parameters, look for \foo, \bar, etc.
1833 if (Body[Pos] == '\\' && Pos + 1 != End)
1834 break;
1835 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001836 }
1837
1838 // Add the prefix.
1839 OS << Body.slice(0, Pos);
1840
1841 // Check if we reached the end.
1842 if (Pos == End)
1843 break;
1844
Benjamin Kramer513e7442014-02-20 13:36:32 +00001845 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001846 switch (Body[Pos + 1]) {
1847 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00001848 case '$':
1849 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001850 break;
1851
Jim Grosbach4b905842013-09-20 23:08:21 +00001852 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00001853 case 'n':
1854 OS << A.size();
1855 break;
1856
Jim Grosbach4b905842013-09-20 23:08:21 +00001857 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00001858 default: {
1859 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00001860 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00001861 if (Index >= A.size())
1862 break;
1863
1864 // Otherwise substitute with the token values, with spaces eliminated.
Eli Benderskya7b905e2013-01-14 19:00:26 +00001865 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Jim Grosbach4b905842013-09-20 23:08:21 +00001866 ie = A[Index].end();
1867 it != ie; ++it)
Rafael Espindola1134ab232011-06-05 02:43:45 +00001868 OS << it->getString();
1869 break;
1870 }
1871 }
1872 Pos += 2;
1873 } else {
1874 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00001875
1876 // Check for the \@ pseudo-variable.
1877 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00001878 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00001879 else
1880 while (isIdentifierChar(Body[I]) && I + 1 != End)
1881 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00001882
Jim Grosbach4b905842013-09-20 23:08:21 +00001883 const char *Begin = Body.data() + Pos + 1;
1884 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00001885 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00001886
Toma Tabacu217116e2015-04-27 10:50:29 +00001887 if (Argument == "@") {
1888 OS << NumOfMacroInstantiations;
1889 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00001890 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00001891 for (; Index < NParameters; ++Index)
1892 if (Parameters[Index].Name == Argument)
1893 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00001894
Toma Tabacu217116e2015-04-27 10:50:29 +00001895 if (Index == NParameters) {
1896 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1897 Pos += 3;
1898 else {
1899 OS << '\\' << Argument;
1900 Pos = I;
1901 }
1902 } else {
1903 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1904 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1905 ie = A[Index].end();
1906 it != ie; ++it)
1907 // We expect no quotes around the string's contents when
1908 // parsing for varargs.
1909 if (it->getKind() != AsmToken::String || VarargParameter)
1910 OS << it->getString();
1911 else
1912 OS << it->getStringContents();
1913
1914 Pos += 1 + Argument.size();
1915 }
Preston Gurd05500642012-09-19 20:36:12 +00001916 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00001917 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001918 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00001919 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001920 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001921
Rafael Espindola1134ab232011-06-05 02:43:45 +00001922 return false;
1923}
Daniel Dunbar43235712010-07-18 18:54:11 +00001924
Nico Weber2a8f9222014-07-24 16:29:04 +00001925MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00001926 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00001927 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00001928 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00001929
Jim Grosbach4b905842013-09-20 23:08:21 +00001930static bool isOperator(AsmToken::TokenKind kind) {
1931 switch (kind) {
1932 default:
1933 return false;
1934 case AsmToken::Plus:
1935 case AsmToken::Minus:
1936 case AsmToken::Tilde:
1937 case AsmToken::Slash:
1938 case AsmToken::Star:
1939 case AsmToken::Dot:
1940 case AsmToken::Equal:
1941 case AsmToken::EqualEqual:
1942 case AsmToken::Pipe:
1943 case AsmToken::PipePipe:
1944 case AsmToken::Caret:
1945 case AsmToken::Amp:
1946 case AsmToken::AmpAmp:
1947 case AsmToken::Exclaim:
1948 case AsmToken::ExclaimEqual:
1949 case AsmToken::Percent:
1950 case AsmToken::Less:
1951 case AsmToken::LessEqual:
1952 case AsmToken::LessLess:
1953 case AsmToken::LessGreater:
1954 case AsmToken::Greater:
1955 case AsmToken::GreaterEqual:
1956 case AsmToken::GreaterGreater:
1957 return true;
Preston Gurd05500642012-09-19 20:36:12 +00001958 }
1959}
1960
David Majnemer16252452014-01-29 00:07:39 +00001961namespace {
1962class AsmLexerSkipSpaceRAII {
1963public:
1964 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1965 Lexer.setSkipSpace(SkipSpace);
1966 }
1967
1968 ~AsmLexerSkipSpaceRAII() {
1969 Lexer.setSkipSpace(true);
1970 }
1971
1972private:
1973 AsmLexer &Lexer;
1974};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001975}
David Majnemer16252452014-01-29 00:07:39 +00001976
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00001977bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1978
1979 if (Vararg) {
1980 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1981 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001982 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00001983 }
1984 return false;
1985 }
1986
Rafael Espindola768b41c2012-06-15 14:02:34 +00001987 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00001988 unsigned AddTokens = 0;
1989
David Majnemer16252452014-01-29 00:07:39 +00001990 // Darwin doesn't use spaces to delmit arguments.
1991 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00001992
1993 for (;;) {
David Majnemer16252452014-01-29 00:07:39 +00001994 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00001995 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00001996
David Majnemer91fc4c22014-01-29 18:57:46 +00001997 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
Preston Gurd05500642012-09-19 20:36:12 +00001998 break;
Preston Gurd05500642012-09-19 20:36:12 +00001999
2000 if (Lexer.is(AsmToken::Space)) {
2001 Lex(); // Eat spaces
2002
2003 // Spaces can delimit parameters, but could also be part an expression.
2004 // If the token after a space is an operator, add the token and the next
2005 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002006 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002007 if (isOperator(Lexer.getKind())) {
Preston Gurd05500642012-09-19 20:36:12 +00002008 // Check to see whether the token is used as an operator,
2009 // or part of an identifier
Jordan Rosee8f1eae2013-01-07 19:00:49 +00002010 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd05500642012-09-19 20:36:12 +00002011 if (*NextChar == ' ')
2012 AddTokens = 2;
2013 }
2014
2015 if (!AddTokens && ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002016 break;
2017 }
2018 }
2019 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002020
Jim Grosbach4b905842013-09-20 23:08:21 +00002021 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002022 // to be able to fill in the remaining default parameter values
2023 if (Lexer.is(AsmToken::EndOfStatement))
2024 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002025
2026 // Adjust the current parentheses level.
2027 if (Lexer.is(AsmToken::LParen))
2028 ++ParenLevel;
2029 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2030 --ParenLevel;
2031
2032 // Append the token to the current argument list.
2033 MA.push_back(getTok());
Preston Gurd05500642012-09-19 20:36:12 +00002034 if (AddTokens)
2035 AddTokens--;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002036 Lex();
2037 }
Preston Gurd05500642012-09-19 20:36:12 +00002038
Rafael Espindola768b41c2012-06-15 14:02:34 +00002039 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002040 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002041 return false;
2042}
2043
2044// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002045bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002046 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002047 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002048 bool NamedParametersFound = false;
2049 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002050
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002051 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002052 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002053
Rafael Espindola768b41c2012-06-15 14:02:34 +00002054 // Parse two kinds of macro invocations:
2055 // - macros defined without any parameters accept an arbitrary number of them
2056 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002057 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002058 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2059 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002060 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002061 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002062
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002063 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002064 if (parseIdentifier(FA.Name)) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002065 Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002066 eatToEndOfStatement();
2067 return true;
2068 }
2069
2070 if (!Lexer.is(AsmToken::Equal)) {
2071 TokError("expected '=' after formal parameter identifier");
2072 eatToEndOfStatement();
2073 return true;
2074 }
2075 Lex();
2076
2077 NamedParametersFound = true;
2078 }
2079
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002080 if (NamedParametersFound && FA.Name.empty()) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002081 Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002082 eatToEndOfStatement();
2083 return true;
2084 }
2085
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002086 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2087 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002088 return true;
2089
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002090 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002091 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002092 unsigned FAI = 0;
2093 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002094 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002095 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002096
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002097 if (FAI >= NParameters) {
Oliver Stannard8b273082014-06-19 15:52:37 +00002098 assert(M && "expected macro to be defined");
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002099 Error(IDLoc,
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002100 "parameter named '" + FA.Name + "' does not exist for macro '" +
Saleem Abdulrasool3f44cd72014-03-17 17:13:57 +00002101 M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002102 return true;
2103 }
2104 PI = FAI;
2105 }
2106
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002107 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002108 if (A.size() <= PI)
2109 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002110 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002111
2112 if (FALocs.size() <= PI)
2113 FALocs.resize(PI + 1);
2114
2115 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002116 }
Jim Grosbach206661622012-07-30 22:44:17 +00002117
Preston Gurd242ed3152012-09-19 20:29:04 +00002118 // At the end of the statement, fill in remaining arguments that have
2119 // default values. If there aren't any, then the next argument is
2120 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002121 if (Lexer.is(AsmToken::EndOfStatement)) {
2122 bool Failure = false;
2123 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2124 if (A[FAI].empty()) {
2125 if (M->Parameters[FAI].Required) {
2126 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2127 "missing value for required parameter "
2128 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2129 Failure = true;
2130 }
2131
2132 if (!M->Parameters[FAI].Value.empty())
2133 A[FAI] = M->Parameters[FAI].Value;
2134 }
2135 }
2136 return Failure;
2137 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002138
2139 if (Lexer.is(AsmToken::Comma))
2140 Lex();
2141 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002142
2143 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002144}
2145
Jim Grosbach4b905842013-09-20 23:08:21 +00002146const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002147 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2148 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002149}
2150
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002151void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2152 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002153}
2154
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002155void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002156
Jim Grosbach4b905842013-09-20 23:08:21 +00002157bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbar43235712010-07-18 18:54:11 +00002158 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2159 // this, although we should protect against infinite loops.
2160 if (ActiveMacros.size() == 20)
2161 return TokError("macros cannot be nested more than 20 levels deep");
2162
Eli Bendersky38274122013-01-14 23:22:36 +00002163 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002164 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002165 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002166
Rafael Espindola1134ab232011-06-05 02:43:45 +00002167 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2168 // to hold the macro body with substitutions.
2169 SmallString<256> Buf;
2170 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002171 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002172
Toma Tabacu217116e2015-04-27 10:50:29 +00002173 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002174 return true;
2175
Eli Bendersky38274122013-01-14 23:22:36 +00002176 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002177 // instantiation.
2178 OS << ".endmacro\n";
2179
Rafael Espindola3560ff22014-08-27 20:03:13 +00002180 std::unique_ptr<MemoryBuffer> Instantiation =
2181 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002182
Daniel Dunbar43235712010-07-18 18:54:11 +00002183 // Create the macro instantiation object and add to the current macro
2184 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002185 MacroInstantiation *MI = new MacroInstantiation(
2186 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002187 ActiveMacros.push_back(MI);
2188
Toma Tabacu217116e2015-04-27 10:50:29 +00002189 ++NumOfMacroInstantiations;
2190
Daniel Dunbar43235712010-07-18 18:54:11 +00002191 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002192 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002193 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002194 Lex();
2195
2196 return false;
2197}
2198
Jim Grosbach4b905842013-09-20 23:08:21 +00002199void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002200 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002201 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002202 Lex();
2203
2204 // Pop the instantiation entry.
2205 delete ActiveMacros.back();
2206 ActiveMacros.pop_back();
2207}
2208
Jim Grosbach4b905842013-09-20 23:08:21 +00002209bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002210 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002211 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002212 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002213 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2214 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002215 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002216
Pete Cooper80d21cb2015-06-22 19:35:57 +00002217 if (!Sym) {
2218 // In the case where we parse an expression starting with a '.', we will
2219 // not generate an error, nor will we create a symbol. In this case we
2220 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002221 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002222 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002223
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002224 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002225 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002226 if (NoDeadStrip)
2227 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2228
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002229 return false;
2230}
2231
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002232/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002233/// ::= identifier
2234/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002235bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002236 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002237 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2238 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002239 // handle this as a context dependent token, instead we detect adjacent tokens
2240 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002241 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2242 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002243
Hans Wennborgce69d772013-10-18 20:46:28 +00002244 // Consume the prefix character, and check for a following identifier.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002245 Lex();
2246 if (Lexer.isNot(AsmToken::Identifier))
2247 return true;
2248
Hans Wennborgce69d772013-10-18 20:46:28 +00002249 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2250 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002251 return true;
2252
2253 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002254 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002255 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002256 Lex();
2257 return false;
2258 }
2259
Jim Grosbach4b905842013-09-20 23:08:21 +00002260 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002261 return true;
2262
Sean Callanan936b0d32010-01-19 21:44:56 +00002263 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002264
Sean Callanan686ed8d2010-01-19 20:22:31 +00002265 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002266
2267 return false;
2268}
2269
Jim Grosbach4b905842013-09-20 23:08:21 +00002270/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002271/// ::= .equ identifier ',' expression
2272/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002273/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002274bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002275 StringRef Name;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002276
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002277 if (parseIdentifier(Name))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002278 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencer530ce852010-10-09 11:00:50 +00002279
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002280 if (getLexer().isNot(AsmToken::Comma))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002281 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002282 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002283
Jim Grosbach4b905842013-09-20 23:08:21 +00002284 return parseAssignment(Name, allow_redef, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002285}
2286
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002287bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002288 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbaref668c12009-08-14 18:19:52 +00002289
2290 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002291 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002292 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2293 if (Str[i] != '\\') {
2294 Data += Str[i];
2295 continue;
2296 }
2297
2298 // Recognize escaped characters. Note that this escape semantics currently
2299 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2300 ++i;
2301 if (i == e)
2302 return TokError("unexpected backslash at end of string");
2303
2304 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002305 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002306 // Consume up to three octal characters.
2307 unsigned Value = Str[i] - '0';
2308
Jim Grosbach4b905842013-09-20 23:08:21 +00002309 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002310 ++i;
2311 Value = Value * 8 + (Str[i] - '0');
2312
Jim Grosbach4b905842013-09-20 23:08:21 +00002313 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002314 ++i;
2315 Value = Value * 8 + (Str[i] - '0');
2316 }
2317 }
2318
2319 if (Value > 255)
2320 return TokError("invalid octal escape sequence (out of range)");
2321
Jim Grosbach4b905842013-09-20 23:08:21 +00002322 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002323 continue;
2324 }
2325
2326 // Otherwise recognize individual escapes.
2327 switch (Str[i]) {
2328 default:
2329 // Just reject invalid escape sequences for now.
2330 return TokError("invalid escape sequence (unrecognized character)");
2331
2332 case 'b': Data += '\b'; break;
2333 case 'f': Data += '\f'; break;
2334 case 'n': Data += '\n'; break;
2335 case 'r': Data += '\r'; break;
2336 case 't': Data += '\t'; break;
2337 case '"': Data += '"'; break;
2338 case '\\': Data += '\\'; break;
2339 }
2340 }
2341
2342 return false;
2343}
2344
Jim Grosbach4b905842013-09-20 23:08:21 +00002345/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002346/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002347bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002348 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002349 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002350
Daniel Dunbara10e5192009-06-24 23:30:00 +00002351 for (;;) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002352 if (getLexer().isNot(AsmToken::String))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002353 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002354
Daniel Dunbaref668c12009-08-14 18:19:52 +00002355 std::string Data;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002356 if (parseEscapedString(Data))
Daniel Dunbaref668c12009-08-14 18:19:52 +00002357 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002358
Rafael Espindola64e1af82013-07-02 15:49:13 +00002359 getStreamer().EmitBytes(Data);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002360 if (ZeroTerminated)
Rafael Espindola64e1af82013-07-02 15:49:13 +00002361 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002362
Sean Callanan686ed8d2010-01-19 20:22:31 +00002363 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002364
2365 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002366 break;
2367
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002368 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002369 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002370 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002371 }
2372 }
2373
Sean Callanan686ed8d2010-01-19 20:22:31 +00002374 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002375 return false;
2376}
2377
Jim Grosbach4b905842013-09-20 23:08:21 +00002378/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002379/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002380bool AsmParser::parseDirectiveValue(unsigned Size) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002381 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002382 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002383
Daniel Dunbara10e5192009-06-24 23:30:00 +00002384 for (;;) {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002385 const MCExpr *Value;
Jim Grosbach76346c32011-06-29 16:05:14 +00002386 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002387 if (parseExpression(Value))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002388 return true;
2389
Daniel Dunbar6738a2e2010-05-23 18:36:38 +00002390 // Special case constant expressions to match code generator.
Jim Grosbach76346c32011-06-29 16:05:14 +00002391 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2392 assert(Size <= 8 && "Invalid size");
2393 uint64_t IntValue = MCE->getValue();
2394 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2395 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindola64e1af82013-07-02 15:49:13 +00002396 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach76346c32011-06-29 16:05:14 +00002397 } else
Kevin Enderby96918bc2014-04-22 17:27:29 +00002398 getStreamer().EmitValue(Value, Size, ExprLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002399
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002400 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002401 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002402
Daniel Dunbara10e5192009-06-24 23:30:00 +00002403 // FIXME: Improve diagnostic.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002404 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002405 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002406 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002407 }
2408 }
2409
Sean Callanan686ed8d2010-01-19 20:22:31 +00002410 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002411 return false;
2412}
2413
David Woodhoused6de0d92014-02-01 16:20:59 +00002414/// ParseDirectiveOctaValue
2415/// ::= .octa [ hexconstant (, hexconstant)* ]
2416bool AsmParser::parseDirectiveOctaValue() {
2417 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2418 checkForValidSection();
2419
2420 for (;;) {
2421 if (Lexer.getKind() == AsmToken::Error)
2422 return true;
2423 if (Lexer.getKind() != AsmToken::Integer &&
2424 Lexer.getKind() != AsmToken::BigNum)
2425 return TokError("unknown token in expression");
2426
2427 SMLoc ExprLoc = getLexer().getLoc();
2428 APInt IntValue = getTok().getAPIntVal();
2429 Lex();
2430
2431 uint64_t hi, lo;
2432 if (IntValue.isIntN(64)) {
2433 hi = 0;
2434 lo = IntValue.getZExtValue();
2435 } else if (IntValue.isIntN(128)) {
David Woodhouse6c9a6f92014-02-01 16:52:33 +00002436 // It might actually have more than 128 bits, but the top ones are zero.
2437 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002438 lo = IntValue.getLoBits(64).getZExtValue();
2439 } else
2440 return Error(ExprLoc, "literal value out of range for directive");
2441
2442 if (MAI.isLittleEndian()) {
2443 getStreamer().EmitIntValue(lo, 8);
2444 getStreamer().EmitIntValue(hi, 8);
2445 } else {
2446 getStreamer().EmitIntValue(hi, 8);
2447 getStreamer().EmitIntValue(lo, 8);
2448 }
2449
2450 if (getLexer().is(AsmToken::EndOfStatement))
2451 break;
2452
2453 // FIXME: Improve diagnostic.
2454 if (getLexer().isNot(AsmToken::Comma))
2455 return TokError("unexpected token in directive");
2456 Lex();
2457 }
2458 }
2459
2460 Lex();
2461 return false;
2462}
2463
Jim Grosbach4b905842013-09-20 23:08:21 +00002464/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002465/// ::= (.single | .double) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002466bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
Daniel Dunbar2af16532010-09-24 01:59:56 +00002467 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002468 checkForValidSection();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002469
2470 for (;;) {
2471 // We don't truly support arithmetic on floating point expressions, so we
2472 // have to manually parse unary prefixes.
2473 bool IsNeg = false;
2474 if (getLexer().is(AsmToken::Minus)) {
2475 Lex();
2476 IsNeg = true;
2477 } else if (getLexer().is(AsmToken::Plus))
2478 Lex();
2479
Michael J. Spencer530ce852010-10-09 11:00:50 +00002480 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002481 getLexer().isNot(AsmToken::Real) &&
2482 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002483 return TokError("unexpected token in directive");
2484
2485 // Convert to an APFloat.
2486 APFloat Value(Semantics);
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002487 StringRef IDVal = getTok().getString();
2488 if (getLexer().is(AsmToken::Identifier)) {
2489 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2490 Value = APFloat::getInf(Semantics);
2491 else if (!IDVal.compare_lower("nan"))
2492 Value = APFloat::getNaN(Semantics, false, ~0);
2493 else
2494 return TokError("invalid floating point literal");
2495 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Jim Grosbach4b905842013-09-20 23:08:21 +00002496 APFloat::opInvalidOp)
Daniel Dunbar2af16532010-09-24 01:59:56 +00002497 return TokError("invalid floating point literal");
2498 if (IsNeg)
2499 Value.changeSign();
2500
2501 // Consume the numeric token.
2502 Lex();
2503
2504 // Emit the value as an integer.
2505 APInt AsInt = Value.bitcastToAPInt();
2506 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindola64e1af82013-07-02 15:49:13 +00002507 AsInt.getBitWidth() / 8);
Daniel Dunbar2af16532010-09-24 01:59:56 +00002508
2509 if (getLexer().is(AsmToken::EndOfStatement))
2510 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002511
Daniel Dunbar2af16532010-09-24 01:59:56 +00002512 if (getLexer().isNot(AsmToken::Comma))
2513 return TokError("unexpected token in directive");
2514 Lex();
2515 }
2516 }
2517
2518 Lex();
2519 return false;
2520}
2521
Jim Grosbach4b905842013-09-20 23:08:21 +00002522/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002523/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002524bool AsmParser::parseDirectiveZero() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002525 checkForValidSection();
Rafael Espindola922e3f42010-09-16 15:03:59 +00002526
2527 int64_t NumBytes;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002528 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002529 return true;
2530
Rafael Espindolab91bac62010-10-05 19:42:57 +00002531 int64_t Val = 0;
2532 if (getLexer().is(AsmToken::Comma)) {
2533 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002534 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002535 return true;
2536 }
2537
Rafael Espindola922e3f42010-09-16 15:03:59 +00002538 if (getLexer().isNot(AsmToken::EndOfStatement))
2539 return TokError("unexpected token in '.zero' directive");
2540
2541 Lex();
2542
Rafael Espindola64e1af82013-07-02 15:49:13 +00002543 getStreamer().EmitFill(NumBytes, Val);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002544
2545 return false;
2546}
2547
Jim Grosbach4b905842013-09-20 23:08:21 +00002548/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002549/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002550bool AsmParser::parseDirectiveFill() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002551 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002552
David Majnemer522d3db2014-02-01 07:19:38 +00002553 SMLoc RepeatLoc = getLexer().getLoc();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002554 int64_t NumValues;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002555 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002556 return true;
2557
David Majnemer522d3db2014-02-01 07:19:38 +00002558 if (NumValues < 0) {
2559 Warning(RepeatLoc,
2560 "'.fill' directive with negative repeat count has no effect");
2561 NumValues = 0;
2562 }
2563
Roman Divackye33098f2013-09-24 17:44:41 +00002564 int64_t FillSize = 1;
2565 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002566
David Majnemer522d3db2014-02-01 07:19:38 +00002567 SMLoc SizeLoc, ExprLoc;
Roman Divackye33098f2013-09-24 17:44:41 +00002568 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2569 if (getLexer().isNot(AsmToken::Comma))
2570 return TokError("unexpected token in '.fill' directive");
2571 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002572
David Majnemer522d3db2014-02-01 07:19:38 +00002573 SizeLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002574 if (parseAbsoluteExpression(FillSize))
2575 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002576
Roman Divackye33098f2013-09-24 17:44:41 +00002577 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2578 if (getLexer().isNot(AsmToken::Comma))
2579 return TokError("unexpected token in '.fill' directive");
2580 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002581
David Majnemer522d3db2014-02-01 07:19:38 +00002582 ExprLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002583 if (parseAbsoluteExpression(FillExpr))
2584 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002585
Roman Divackye33098f2013-09-24 17:44:41 +00002586 if (getLexer().isNot(AsmToken::EndOfStatement))
2587 return TokError("unexpected token in '.fill' directive");
2588
2589 Lex();
2590 }
2591 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002592
David Majnemer522d3db2014-02-01 07:19:38 +00002593 if (FillSize < 0) {
2594 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2595 NumValues = 0;
2596 }
2597 if (FillSize > 8) {
2598 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2599 FillSize = 8;
2600 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002601
David Majnemer522d3db2014-02-01 07:19:38 +00002602 if (!isUInt<32>(FillExpr) && FillSize > 4)
2603 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2604
Alexey Samsonov1b0713c2014-09-02 17:25:29 +00002605 if (NumValues > 0) {
2606 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2607 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2608 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2609 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2610 if (NonZeroFillSize < FillSize)
2611 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2612 }
David Majnemer522d3db2014-02-01 07:19:38 +00002613 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002614
2615 return false;
2616}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002617
Jim Grosbach4b905842013-09-20 23:08:21 +00002618/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002619/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002620bool AsmParser::parseDirectiveOrg() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002621 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002622
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002623 const MCExpr *Offset;
Jim Grosbachb5912772012-01-27 00:37:08 +00002624 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002625 if (parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002626 return true;
2627
2628 // Parse optional fill expression.
2629 int64_t FillExpr = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002630 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2631 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002632 return TokError("unexpected token in '.org' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002633 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00002634
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002635 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002636 return true;
2637
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002638 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002639 return TokError("unexpected token in '.org' directive");
2640 }
2641
Sean Callanan686ed8d2010-01-19 20:22:31 +00002642 Lex();
Daniel Dunbar75630b32009-06-30 02:10:03 +00002643
Jim Grosbachb5912772012-01-27 00:37:08 +00002644 // Only limited forms of relocatable expressions are accepted here, it
2645 // has to be relative to the current section. The streamer will return
2646 // 'true' if the expression wasn't evaluatable.
2647 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2648 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002649
2650 return false;
2651}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002652
Jim Grosbach4b905842013-09-20 23:08:21 +00002653/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002654/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002655bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002656 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002657
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002658 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002659 int64_t Alignment;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002660 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002661 return true;
2662
2663 SMLoc MaxBytesLoc;
2664 bool HasFillExpr = false;
2665 int64_t FillExpr = 0;
2666 int64_t MaxBytesToFill = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002667 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2668 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002669 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002670 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002671
2672 // The fill expression can be omitted while specifying a maximum number of
2673 // alignment bytes, e.g:
2674 // .align 3,,4
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002675 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002676 HasFillExpr = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002677 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002678 return true;
2679 }
2680
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002681 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2682 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002683 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002684 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002685
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002686 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002687 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002688 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002689
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002690 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002691 return TokError("unexpected token in directive");
2692 }
2693 }
2694
Sean Callanan686ed8d2010-01-19 20:22:31 +00002695 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002696
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002697 if (!HasFillExpr)
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002698 FillExpr = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002699
2700 // Compute alignment in bytes.
2701 if (IsPow2) {
2702 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002703 if (Alignment >= 32) {
2704 Error(AlignmentLoc, "invalid alignment value");
2705 Alignment = 31;
2706 }
2707
Benjamin Kramer63951ad2009-09-06 09:35:10 +00002708 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002709 } else {
2710 // Reject alignments that aren't a power of two, for gas compatibility.
2711 if (!isPowerOf2_64(Alignment))
2712 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002713 }
2714
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002715 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002716 if (MaxBytesLoc.isValid()) {
2717 if (MaxBytesToFill < 1) {
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002718 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00002719 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00002720 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002721 }
2722
2723 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00002724 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00002725 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002726 MaxBytesToFill = 0;
2727 }
2728 }
2729
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002730 // Check whether we should use optimal code alignment for this .align
2731 // directive.
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00002732 const MCSection *Section = getStreamer().getCurrentSection().first;
2733 assert(Section && "must have section to emit alignment");
2734 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002735 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2736 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002737 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002738 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00002739 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00002740 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2741 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002742 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002743
2744 return false;
2745}
2746
Jim Grosbach4b905842013-09-20 23:08:21 +00002747/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00002748/// ::= .file [number] filename
2749/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00002750bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00002751 // FIXME: I'm not sure what this is.
2752 int64_t FileNumber = -1;
2753 SMLoc FileNumberLoc = getLexer().getLoc();
2754 if (getLexer().is(AsmToken::Integer)) {
2755 FileNumber = getTok().getIntVal();
2756 Lex();
2757
2758 if (FileNumber < 1)
2759 return TokError("file number less than one");
2760 }
2761
2762 if (getLexer().isNot(AsmToken::String))
2763 return TokError("unexpected token in '.file' directive");
2764
2765 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002766 // Allow the strings to have escaped octal character sequence.
2767 std::string Path = getTok().getString();
2768 if (parseEscapedString(Path))
2769 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00002770 Lex();
2771
2772 StringRef Directory;
2773 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002774 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002775 if (getLexer().is(AsmToken::String)) {
2776 if (FileNumber == -1)
2777 return TokError("explicit path specified, but no file number");
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002778 if (parseEscapedString(FilenameData))
2779 return true;
2780 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002781 Directory = Path;
2782 Lex();
2783 } else {
2784 Filename = Path;
2785 }
2786
2787 if (getLexer().isNot(AsmToken::EndOfStatement))
2788 return TokError("unexpected token in '.file' directive");
2789
2790 if (FileNumber == -1)
2791 getStreamer().EmitFileDirective(Filename);
2792 else {
David Blaikiedc3f01e2015-03-09 01:57:13 +00002793 if (getContext().getGenDwarfForAssembly())
Jim Grosbach4b905842013-09-20 23:08:21 +00002794 Error(DirectiveLoc,
2795 "input can't have .file dwarf directives when -g is "
2796 "used to generate dwarf debug info for assembly code");
Eli Bendersky17233942013-01-15 22:59:42 +00002797
David Blaikiec714ef42014-03-17 01:52:11 +00002798 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2799 0)
Eli Bendersky17233942013-01-15 22:59:42 +00002800 Error(FileNumberLoc, "file number already allocated");
2801 }
2802
2803 return false;
2804}
2805
Jim Grosbach4b905842013-09-20 23:08:21 +00002806/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00002807/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00002808bool AsmParser::parseDirectiveLine() {
Eli Bendersky17233942013-01-15 22:59:42 +00002809 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2810 if (getLexer().isNot(AsmToken::Integer))
2811 return TokError("unexpected token in '.line' directive");
2812
2813 int64_t LineNumber = getTok().getIntVal();
Jim Grosbach4b905842013-09-20 23:08:21 +00002814 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00002815 Lex();
2816
2817 // FIXME: Do something with the .line.
2818 }
2819
2820 if (getLexer().isNot(AsmToken::EndOfStatement))
2821 return TokError("unexpected token in '.line' directive");
2822
2823 return false;
2824}
2825
Jim Grosbach4b905842013-09-20 23:08:21 +00002826/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00002827/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2828/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2829/// The first number is a file number, must have been previously assigned with
2830/// a .file directive, the second number is the line number and optionally the
2831/// third number is a column position (zero if not specified). The remaining
2832/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00002833bool AsmParser::parseDirectiveLoc() {
Eli Bendersky17233942013-01-15 22:59:42 +00002834 if (getLexer().isNot(AsmToken::Integer))
2835 return TokError("unexpected token in '.loc' directive");
2836 int64_t FileNumber = getTok().getIntVal();
2837 if (FileNumber < 1)
2838 return TokError("file number less than one in '.loc' directive");
2839 if (!getContext().isValidDwarfFileNumber(FileNumber))
2840 return TokError("unassigned file number in '.loc' directive");
2841 Lex();
2842
2843 int64_t LineNumber = 0;
2844 if (getLexer().is(AsmToken::Integer)) {
2845 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00002846 if (LineNumber < 0)
2847 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00002848 Lex();
2849 }
2850
2851 int64_t ColumnPos = 0;
2852 if (getLexer().is(AsmToken::Integer)) {
2853 ColumnPos = getTok().getIntVal();
2854 if (ColumnPos < 0)
2855 return TokError("column position less than zero in '.loc' directive");
2856 Lex();
2857 }
2858
2859 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2860 unsigned Isa = 0;
2861 int64_t Discriminator = 0;
2862 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2863 for (;;) {
2864 if (getLexer().is(AsmToken::EndOfStatement))
2865 break;
2866
2867 StringRef Name;
2868 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002869 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00002870 return TokError("unexpected token in '.loc' directive");
2871
2872 if (Name == "basic_block")
2873 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2874 else if (Name == "prologue_end")
2875 Flags |= DWARF2_FLAG_PROLOGUE_END;
2876 else if (Name == "epilogue_begin")
2877 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2878 else if (Name == "is_stmt") {
2879 Loc = getTok().getLoc();
2880 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002881 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00002882 return true;
2883 // The expression must be the constant 0 or 1.
2884 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2885 int Value = MCE->getValue();
2886 if (Value == 0)
2887 Flags &= ~DWARF2_FLAG_IS_STMT;
2888 else if (Value == 1)
2889 Flags |= DWARF2_FLAG_IS_STMT;
2890 else
2891 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00002892 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00002893 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2894 }
Craig Topperf15655b2013-04-22 04:22:40 +00002895 } else if (Name == "isa") {
Eli Bendersky17233942013-01-15 22:59:42 +00002896 Loc = getTok().getLoc();
2897 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002898 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00002899 return true;
2900 // The expression must be a constant greater or equal to 0.
2901 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2902 int Value = MCE->getValue();
2903 if (Value < 0)
2904 return Error(Loc, "isa number less than zero");
2905 Isa = Value;
Craig Topperf15655b2013-04-22 04:22:40 +00002906 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00002907 return Error(Loc, "isa number not a constant value");
2908 }
Craig Topperf15655b2013-04-22 04:22:40 +00002909 } else if (Name == "discriminator") {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002910 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky17233942013-01-15 22:59:42 +00002911 return true;
Craig Topperf15655b2013-04-22 04:22:40 +00002912 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00002913 return Error(Loc, "unknown sub-directive in '.loc' directive");
2914 }
2915
2916 if (getLexer().is(AsmToken::EndOfStatement))
2917 break;
2918 }
2919 }
2920
2921 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2922 Isa, Discriminator, StringRef());
2923
2924 return false;
2925}
2926
Jim Grosbach4b905842013-09-20 23:08:21 +00002927/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00002928/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00002929bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00002930 return TokError("unsupported directive '.stabs'");
2931}
2932
Jim Grosbach4b905842013-09-20 23:08:21 +00002933/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00002934/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00002935bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00002936 StringRef Name;
2937 bool EH = false;
2938 bool Debug = false;
2939
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002940 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00002941 return TokError("Expected an identifier");
2942
2943 if (Name == ".eh_frame")
2944 EH = true;
2945 else if (Name == ".debug_frame")
2946 Debug = true;
2947
2948 if (getLexer().is(AsmToken::Comma)) {
2949 Lex();
2950
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002951 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00002952 return TokError("Expected an identifier");
2953
2954 if (Name == ".eh_frame")
2955 EH = true;
2956 else if (Name == ".debug_frame")
2957 Debug = true;
2958 }
2959
2960 getStreamer().EmitCFISections(EH, Debug);
2961 return false;
2962}
2963
Jim Grosbach4b905842013-09-20 23:08:21 +00002964/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00002965/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00002966bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00002967 StringRef Simple;
2968 if (getLexer().isNot(AsmToken::EndOfStatement))
2969 if (parseIdentifier(Simple) || Simple != "simple")
2970 return TokError("unexpected token in .cfi_startproc directive");
2971
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00002972 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00002973 return false;
2974}
2975
Jim Grosbach4b905842013-09-20 23:08:21 +00002976/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00002977/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00002978bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00002979 getStreamer().EmitCFIEndProc();
2980 return false;
2981}
2982
Jim Grosbach4b905842013-09-20 23:08:21 +00002983/// \brief parse register name or number.
2984bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00002985 SMLoc DirectiveLoc) {
2986 unsigned RegNo;
2987
2988 if (getLexer().isNot(AsmToken::Integer)) {
2989 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2990 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00002991 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00002992 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002993 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00002994
2995 return false;
2996}
2997
Jim Grosbach4b905842013-09-20 23:08:21 +00002998/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00002999/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003000bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003001 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003002 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003003 return true;
3004
3005 if (getLexer().isNot(AsmToken::Comma))
3006 return TokError("unexpected token in directive");
3007 Lex();
3008
3009 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003010 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003011 return true;
3012
3013 getStreamer().EmitCFIDefCfa(Register, Offset);
3014 return false;
3015}
3016
Jim Grosbach4b905842013-09-20 23:08:21 +00003017/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003018/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003019bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003020 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003021 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003022 return true;
3023
3024 getStreamer().EmitCFIDefCfaOffset(Offset);
3025 return false;
3026}
3027
Jim Grosbach4b905842013-09-20 23:08:21 +00003028/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003029/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003030bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003031 int64_t Register1 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003032 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003033 return true;
3034
3035 if (getLexer().isNot(AsmToken::Comma))
3036 return TokError("unexpected token in directive");
3037 Lex();
3038
3039 int64_t Register2 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003040 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003041 return true;
3042
3043 getStreamer().EmitCFIRegister(Register1, Register2);
3044 return false;
3045}
3046
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003047/// parseDirectiveCFIWindowSave
3048/// ::= .cfi_window_save
3049bool AsmParser::parseDirectiveCFIWindowSave() {
3050 getStreamer().EmitCFIWindowSave();
3051 return false;
3052}
3053
Jim Grosbach4b905842013-09-20 23:08:21 +00003054/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003055/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003056bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003057 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003058 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003059 return true;
3060
3061 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3062 return false;
3063}
3064
Jim Grosbach4b905842013-09-20 23:08:21 +00003065/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003066/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003067bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003068 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003069 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003070 return true;
3071
3072 getStreamer().EmitCFIDefCfaRegister(Register);
3073 return false;
3074}
3075
Jim Grosbach4b905842013-09-20 23:08:21 +00003076/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003077/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003078bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003079 int64_t Register = 0;
3080 int64_t Offset = 0;
3081
Jim Grosbach4b905842013-09-20 23:08:21 +00003082 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003083 return true;
3084
3085 if (getLexer().isNot(AsmToken::Comma))
3086 return TokError("unexpected token in directive");
3087 Lex();
3088
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003089 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003090 return true;
3091
3092 getStreamer().EmitCFIOffset(Register, Offset);
3093 return false;
3094}
3095
Jim Grosbach4b905842013-09-20 23:08:21 +00003096/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003097/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003098bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003099 int64_t Register = 0;
3100
Jim Grosbach4b905842013-09-20 23:08:21 +00003101 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003102 return true;
3103
3104 if (getLexer().isNot(AsmToken::Comma))
3105 return TokError("unexpected token in directive");
3106 Lex();
3107
3108 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003109 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003110 return true;
3111
3112 getStreamer().EmitCFIRelOffset(Register, Offset);
3113 return false;
3114}
3115
3116static bool isValidEncoding(int64_t Encoding) {
3117 if (Encoding & ~0xff)
3118 return false;
3119
3120 if (Encoding == dwarf::DW_EH_PE_omit)
3121 return true;
3122
3123 const unsigned Format = Encoding & 0xf;
3124 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3125 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3126 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3127 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3128 return false;
3129
3130 const unsigned Application = Encoding & 0x70;
3131 if (Application != dwarf::DW_EH_PE_absptr &&
3132 Application != dwarf::DW_EH_PE_pcrel)
3133 return false;
3134
3135 return true;
3136}
3137
Jim Grosbach4b905842013-09-20 23:08:21 +00003138/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003139/// IsPersonality true for cfi_personality, false for cfi_lsda
3140/// ::= .cfi_personality encoding, [symbol_name]
3141/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003142bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003143 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003144 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003145 return true;
3146 if (Encoding == dwarf::DW_EH_PE_omit)
3147 return false;
3148
3149 if (!isValidEncoding(Encoding))
3150 return TokError("unsupported encoding.");
3151
3152 if (getLexer().isNot(AsmToken::Comma))
3153 return TokError("unexpected token in directive");
3154 Lex();
3155
3156 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003157 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003158 return TokError("expected identifier in directive");
3159
Jim Grosbach6f482002015-05-18 18:43:14 +00003160 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003161
3162 if (IsPersonality)
3163 getStreamer().EmitCFIPersonality(Sym, Encoding);
3164 else
3165 getStreamer().EmitCFILsda(Sym, Encoding);
3166 return false;
3167}
3168
Jim Grosbach4b905842013-09-20 23:08:21 +00003169/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003170/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003171bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003172 getStreamer().EmitCFIRememberState();
3173 return false;
3174}
3175
Jim Grosbach4b905842013-09-20 23:08:21 +00003176/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003177/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003178bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003179 getStreamer().EmitCFIRestoreState();
3180 return false;
3181}
3182
Jim Grosbach4b905842013-09-20 23:08:21 +00003183/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003184/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003185bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003186 int64_t Register = 0;
3187
Jim Grosbach4b905842013-09-20 23:08:21 +00003188 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003189 return true;
3190
3191 getStreamer().EmitCFISameValue(Register);
3192 return false;
3193}
3194
Jim Grosbach4b905842013-09-20 23:08:21 +00003195/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003196/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003197bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003198 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003199 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003200 return true;
3201
3202 getStreamer().EmitCFIRestore(Register);
3203 return false;
3204}
3205
Jim Grosbach4b905842013-09-20 23:08:21 +00003206/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003207/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003208bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003209 std::string Values;
3210 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003211 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003212 return true;
3213
3214 Values.push_back((uint8_t)CurrValue);
3215
3216 while (getLexer().is(AsmToken::Comma)) {
3217 Lex();
3218
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003219 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003220 return true;
3221
3222 Values.push_back((uint8_t)CurrValue);
3223 }
3224
3225 getStreamer().EmitCFIEscape(Values);
3226 return false;
3227}
3228
Jim Grosbach4b905842013-09-20 23:08:21 +00003229/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003230/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003231bool AsmParser::parseDirectiveCFISignalFrame() {
Eli Bendersky17233942013-01-15 22:59:42 +00003232 if (getLexer().isNot(AsmToken::EndOfStatement))
3233 return Error(getLexer().getLoc(),
3234 "unexpected token in '.cfi_signal_frame'");
3235
3236 getStreamer().EmitCFISignalFrame();
3237 return false;
3238}
3239
Jim Grosbach4b905842013-09-20 23:08:21 +00003240/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003241/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003242bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003243 int64_t Register = 0;
3244
Jim Grosbach4b905842013-09-20 23:08:21 +00003245 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003246 return true;
3247
3248 getStreamer().EmitCFIUndefined(Register);
3249 return false;
3250}
3251
Jim Grosbach4b905842013-09-20 23:08:21 +00003252/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003253/// ::= .macros_on
3254/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003255bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003256 if (getLexer().isNot(AsmToken::EndOfStatement))
3257 return Error(getLexer().getLoc(),
3258 "unexpected token in '" + Directive + "' directive");
3259
Jim Grosbach4b905842013-09-20 23:08:21 +00003260 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003261 return false;
3262}
3263
Jim Grosbach4b905842013-09-20 23:08:21 +00003264/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003265/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003266bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003267 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003268 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003269 return TokError("expected identifier in '.macro' directive");
3270
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003271 if (getLexer().is(AsmToken::Comma))
3272 Lex();
3273
Eli Bendersky17233942013-01-15 22:59:42 +00003274 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003275 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003276
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003277 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003278 return Error(Lexer.getLoc(),
3279 "Vararg parameter '" + Parameters.back().Name +
3280 "' should be last one in the list of parameters.");
3281
David Majnemer91fc4c22014-01-29 18:57:46 +00003282 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003283 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003284 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003285
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003286 if (Lexer.is(AsmToken::Colon)) {
3287 Lex(); // consume ':'
3288
3289 SMLoc QualLoc;
3290 StringRef Qualifier;
3291
3292 QualLoc = Lexer.getLoc();
3293 if (parseIdentifier(Qualifier))
3294 return Error(QualLoc, "missing parameter qualifier for "
3295 "'" + Parameter.Name + "' in macro '" + Name + "'");
3296
3297 if (Qualifier == "req")
3298 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003299 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003300 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003301 else
3302 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3303 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3304 }
3305
David Majnemer91fc4c22014-01-29 18:57:46 +00003306 if (getLexer().is(AsmToken::Equal)) {
3307 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003308
3309 SMLoc ParamLoc;
3310
3311 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003312 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003313 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003314
3315 if (Parameter.Required)
3316 Warning(ParamLoc, "pointless default value for required parameter "
3317 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003318 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003319
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003320 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003321
3322 if (getLexer().is(AsmToken::Comma))
3323 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003324 }
3325
3326 // Eat the end of statement.
3327 Lex();
3328
3329 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003330 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003331
3332 // Lex the macro definition.
3333 for (;;) {
3334 // Check whether we have reached the end of the file.
3335 if (getLexer().is(AsmToken::Eof))
3336 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3337
3338 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003339 if (getLexer().is(AsmToken::Identifier)) {
3340 if (getTok().getIdentifier() == ".endm" ||
3341 getTok().getIdentifier() == ".endmacro") {
3342 if (MacroDepth == 0) { // Outermost macro.
3343 EndToken = getTok();
3344 Lex();
3345 if (getLexer().isNot(AsmToken::EndOfStatement))
3346 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3347 "' directive");
3348 break;
3349 } else {
3350 // Otherwise we just found the end of an inner macro.
3351 --MacroDepth;
3352 }
3353 } else if (getTok().getIdentifier() == ".macro") {
3354 // We allow nested macros. Those aren't instantiated until the outermost
3355 // macro is expanded so just ignore them for now.
3356 ++MacroDepth;
3357 }
Eli Bendersky17233942013-01-15 22:59:42 +00003358 }
3359
3360 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003361 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003362 }
3363
Jim Grosbach4b905842013-09-20 23:08:21 +00003364 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003365 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3366 }
3367
3368 const char *BodyStart = StartToken.getLoc().getPointer();
3369 const char *BodyEnd = EndToken.getLoc().getPointer();
3370 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003371 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003372 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003373 return false;
3374}
3375
Jim Grosbach4b905842013-09-20 23:08:21 +00003376/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003377///
3378/// With the support added for named parameters there may be code out there that
3379/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003380/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003381/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003382/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003383/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3384/// warning that the positional parameter found in body which have no effect.
3385/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003386/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003387/// intended or change the macro to use the named parameters. It is possible
3388/// this warning will trigger when the none of the named parameters are used
3389/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003390void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003391 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003392 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003393 // If this macro is not defined with named parameters the warning we are
3394 // checking for here doesn't apply.
3395 unsigned NParameters = Parameters.size();
3396 if (NParameters == 0)
3397 return;
3398
3399 bool NamedParametersFound = false;
3400 bool PositionalParametersFound = false;
3401
3402 // Look at the body of the macro for use of both the named parameters and what
3403 // are likely to be positional parameters. This is what expandMacro() is
3404 // doing when it finds the parameters in the body.
3405 while (!Body.empty()) {
3406 // Scan for the next possible parameter.
3407 std::size_t End = Body.size(), Pos = 0;
3408 for (; Pos != End; ++Pos) {
3409 // Check for a substitution or escape.
3410 // This macro is defined with parameters, look for \foo, \bar, etc.
3411 if (Body[Pos] == '\\' && Pos + 1 != End)
3412 break;
3413
3414 // This macro should have parameters, but look for $0, $1, ..., $n too.
3415 if (Body[Pos] != '$' || Pos + 1 == End)
3416 continue;
3417 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00003418 if (Next == '$' || Next == 'n' ||
3419 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00003420 break;
3421 }
3422
3423 // Check if we reached the end.
3424 if (Pos == End)
3425 break;
3426
3427 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00003428 switch (Body[Pos + 1]) {
3429 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00003430 case '$':
3431 break;
3432
Jim Grosbach4b905842013-09-20 23:08:21 +00003433 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00003434 case 'n':
3435 PositionalParametersFound = true;
3436 break;
3437
Jim Grosbach4b905842013-09-20 23:08:21 +00003438 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00003439 default: {
3440 PositionalParametersFound = true;
3441 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00003442 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003443 }
3444 Pos += 2;
3445 } else {
3446 unsigned I = Pos + 1;
3447 while (isIdentifierChar(Body[I]) && I + 1 != End)
3448 ++I;
3449
Jim Grosbach4b905842013-09-20 23:08:21 +00003450 const char *Begin = Body.data() + Pos + 1;
3451 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00003452 unsigned Index = 0;
3453 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003454 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00003455 break;
3456
3457 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00003458 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3459 Pos += 3;
3460 else {
3461 Pos = I;
3462 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003463 } else {
3464 NamedParametersFound = true;
3465 Pos += 1 + Argument.size();
3466 }
3467 }
3468 // Update the scan point.
3469 Body = Body.substr(Pos);
3470 }
3471
3472 if (!NamedParametersFound && PositionalParametersFound)
3473 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3474 "used in macro body, possible positional parameter "
3475 "found in body which will have no effect");
3476}
3477
Nico Weber155dccd12014-07-24 17:08:39 +00003478/// parseDirectiveExitMacro
3479/// ::= .exitm
3480bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3481 if (getLexer().isNot(AsmToken::EndOfStatement))
3482 return TokError("unexpected token in '" + Directive + "' directive");
3483
3484 if (!isInsideMacroInstantiation())
3485 return TokError("unexpected '" + Directive + "' in file, "
3486 "no current macro definition");
3487
3488 // Exit all conditionals that are active in the current macro.
3489 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3490 TheCondState = TheCondStack.back();
3491 TheCondStack.pop_back();
3492 }
3493
3494 handleMacroExit();
3495 return false;
3496}
3497
Jim Grosbach4b905842013-09-20 23:08:21 +00003498/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003499/// ::= .endm
3500/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00003501bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003502 if (getLexer().isNot(AsmToken::EndOfStatement))
3503 return TokError("unexpected token in '" + Directive + "' directive");
3504
3505 // If we are inside a macro instantiation, terminate the current
3506 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00003507 if (isInsideMacroInstantiation()) {
3508 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00003509 return false;
3510 }
3511
3512 // Otherwise, this .endmacro is a stray entry in the file; well formed
3513 // .endmacro directives are handled during the macro definition parsing.
3514 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00003515 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00003516}
3517
Jim Grosbach4b905842013-09-20 23:08:21 +00003518/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003519/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00003520bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003521 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003522 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003523 return TokError("expected identifier in '.purgem' directive");
3524
3525 if (getLexer().isNot(AsmToken::EndOfStatement))
3526 return TokError("unexpected token in '.purgem' directive");
3527
Jim Grosbach4b905842013-09-20 23:08:21 +00003528 if (!lookupMacro(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003529 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3530
Jim Grosbach4b905842013-09-20 23:08:21 +00003531 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003532 return false;
3533}
Eli Benderskyf483ff92012-12-20 19:05:53 +00003534
Jim Grosbach4b905842013-09-20 23:08:21 +00003535/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00003536/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003537bool AsmParser::parseDirectiveBundleAlignMode() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003538 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003539
3540 // Expect a single argument: an expression that evaluates to a constant
3541 // in the inclusive range 0-30.
3542 SMLoc ExprLoc = getLexer().getLoc();
3543 int64_t AlignSizePow2;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003544 if (parseAbsoluteExpression(AlignSizePow2))
Eli Benderskyf483ff92012-12-20 19:05:53 +00003545 return true;
3546 else if (getLexer().isNot(AsmToken::EndOfStatement))
3547 return TokError("unexpected token after expression in"
3548 " '.bundle_align_mode' directive");
3549 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3550 return Error(ExprLoc,
3551 "invalid bundle alignment size (expected between 0 and 30)");
3552
3553 Lex();
3554
3555 // Because of AlignSizePow2's verified range we can safely truncate it to
3556 // unsigned.
3557 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3558 return false;
3559}
3560
Jim Grosbach4b905842013-09-20 23:08:21 +00003561/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00003562/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00003563bool AsmParser::parseDirectiveBundleLock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003564 checkForValidSection();
Eli Bendersky802b6282013-01-07 21:51:08 +00003565 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00003566
Eli Bendersky802b6282013-01-07 21:51:08 +00003567 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3568 StringRef Option;
3569 SMLoc Loc = getTok().getLoc();
3570 const char *kInvalidOptionError =
Jim Grosbach4b905842013-09-20 23:08:21 +00003571 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00003572
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003573 if (parseIdentifier(Option))
Eli Bendersky802b6282013-01-07 21:51:08 +00003574 return Error(Loc, kInvalidOptionError);
3575
3576 if (Option != "align_to_end")
3577 return Error(Loc, kInvalidOptionError);
3578 else if (getLexer().isNot(AsmToken::EndOfStatement))
3579 return Error(Loc,
3580 "unexpected token after '.bundle_lock' directive option");
3581 AlignToEnd = true;
3582 }
3583
Eli Benderskyf483ff92012-12-20 19:05:53 +00003584 Lex();
3585
Eli Bendersky802b6282013-01-07 21:51:08 +00003586 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00003587 return false;
3588}
3589
Jim Grosbach4b905842013-09-20 23:08:21 +00003590/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00003591/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00003592bool AsmParser::parseDirectiveBundleUnlock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003593 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003594
3595 if (getLexer().isNot(AsmToken::EndOfStatement))
3596 return TokError("unexpected token in '.bundle_unlock' directive");
3597 Lex();
3598
3599 getStreamer().EmitBundleUnlock();
3600 return false;
3601}
3602
Jim Grosbach4b905842013-09-20 23:08:21 +00003603/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00003604/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003605bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003606 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00003607
3608 int64_t NumBytes;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003609 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00003610 return true;
3611
3612 int64_t FillExpr = 0;
3613 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3614 if (getLexer().isNot(AsmToken::Comma))
3615 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3616 Lex();
3617
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003618 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky17233942013-01-15 22:59:42 +00003619 return true;
3620
3621 if (getLexer().isNot(AsmToken::EndOfStatement))
3622 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3623 }
3624
3625 Lex();
3626
3627 if (NumBytes <= 0)
Jim Grosbach4b905842013-09-20 23:08:21 +00003628 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3629 "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003630
3631 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Rafael Espindola64e1af82013-07-02 15:49:13 +00003632 getStreamer().EmitFill(NumBytes, FillExpr);
Eli Bendersky17233942013-01-15 22:59:42 +00003633
3634 return false;
3635}
3636
Jim Grosbach4b905842013-09-20 23:08:21 +00003637/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003638/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003639bool AsmParser::parseDirectiveLEB128(bool Signed) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003640 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00003641 const MCExpr *Value;
3642
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003643 for (;;) {
3644 if (parseExpression(Value))
3645 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003646
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003647 if (Signed)
3648 getStreamer().EmitSLEB128Value(Value);
3649 else
3650 getStreamer().EmitULEB128Value(Value);
Eli Bendersky17233942013-01-15 22:59:42 +00003651
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003652 if (getLexer().is(AsmToken::EndOfStatement))
3653 break;
3654
3655 if (getLexer().isNot(AsmToken::Comma))
3656 return TokError("unexpected token in directive");
3657 Lex();
3658 }
Eli Bendersky17233942013-01-15 22:59:42 +00003659
3660 return false;
3661}
3662
Jim Grosbach4b905842013-09-20 23:08:21 +00003663/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00003664/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003665bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003666 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbara5508c82009-06-30 00:33:19 +00003667 for (;;) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00003668 StringRef Name;
Jim Grosbachebdf32f2011-09-15 17:56:49 +00003669 SMLoc Loc = getTok().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00003670
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003671 if (parseIdentifier(Name))
Jim Grosbachebdf32f2011-09-15 17:56:49 +00003672 return Error(Loc, "expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003673
Jim Grosbach6f482002015-05-18 18:43:14 +00003674 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbara5508c82009-06-30 00:33:19 +00003675
Jim Grosbachebdf32f2011-09-15 17:56:49 +00003676 // Assembler local symbols don't make any sense here. Complain loudly.
3677 if (Sym->isTemporary())
3678 return Error(Loc, "non-local symbol required in directive");
3679
Saleem Abdulrasool4208b612013-08-09 01:52:03 +00003680 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3681 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbara5508c82009-06-30 00:33:19 +00003682
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003683 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara5508c82009-06-30 00:33:19 +00003684 break;
3685
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003686 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara5508c82009-06-30 00:33:19 +00003687 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00003688 Lex();
Daniel Dunbara5508c82009-06-30 00:33:19 +00003689 }
3690 }
3691
Sean Callanan686ed8d2010-01-19 20:22:31 +00003692 Lex();
Jan Wen Voungc7682872010-09-30 01:09:20 +00003693 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00003694}
Chris Lattnera1e11f52009-07-07 20:30:46 +00003695
Jim Grosbach4b905842013-09-20 23:08:21 +00003696/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00003697/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003698bool AsmParser::parseDirectiveComm(bool IsLocal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003699 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00003700
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003701 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00003702 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003703 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00003704 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003705
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00003706 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00003707 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00003708
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003709 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00003710 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00003711 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00003712
3713 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003714 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003715 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00003716 return true;
3717
3718 int64_t Pow2Alignment = 0;
3719 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003720 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00003721 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003722 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003723 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00003724 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003725
Benjamin Kramer68b9f052012-09-07 21:08:01 +00003726 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3727 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00003728 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3729
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00003730 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00003731 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3732 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00003733 if (!isPowerOf2_64(Pow2Alignment))
3734 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3735 Pow2Alignment = Log2_64(Pow2Alignment);
3736 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00003737 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00003738
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003739 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner28ad7542009-07-09 17:25:12 +00003740 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003741
Sean Callanan686ed8d2010-01-19 20:22:31 +00003742 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00003743
Chris Lattner28ad7542009-07-09 17:25:12 +00003744 // NOTE: a size of zero for a .comm should create a undefined symbol
3745 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00003746 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00003747 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00003748 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00003749
Eric Christopherbc818852010-05-14 01:38:54 +00003750 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00003751 // may internally end up wanting an alignment in bytes.
3752 // FIXME: Diagnose overflow.
3753 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00003754 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00003755 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00003756
Daniel Dunbar6860ac72009-08-22 07:22:36 +00003757 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00003758 return Error(IDLoc, "invalid symbol redefinition");
3759
Chris Lattner28ad7542009-07-09 17:25:12 +00003760 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00003761 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00003762 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00003763 return false;
3764 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00003765
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003766 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00003767 return false;
3768}
Chris Lattner07cadaf2009-07-10 22:20:30 +00003769
Jim Grosbach4b905842013-09-20 23:08:21 +00003770/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00003771/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003772bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00003773 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003774 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00003775
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003776 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003777 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby56523ce2009-07-13 23:15:14 +00003778 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00003779
Sean Callanan686ed8d2010-01-19 20:22:31 +00003780 Lex();
Kevin Enderby56523ce2009-07-13 23:15:14 +00003781
Daniel Dunbareb6bb322009-07-27 23:20:52 +00003782 if (Str.empty())
3783 Error(Loc, ".abort detected. Assembly stopping.");
3784 else
3785 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00003786 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00003787
3788 return false;
3789}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00003790
Jim Grosbach4b905842013-09-20 23:08:21 +00003791/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003792/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00003793bool AsmParser::parseDirectiveInclude() {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003794 if (getLexer().isNot(AsmToken::String))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003795 return TokError("expected string in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003796
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003797 // Allow the strings to have escaped octal character sequence.
3798 std::string Filename;
3799 if (parseEscapedString(Filename))
3800 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003801 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00003802 Lex();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003803
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003804 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003805 return TokError("unexpected token in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003806
Chris Lattner693fbb82009-07-16 06:14:39 +00003807 // Attempt to switch the lexer to the included file before consuming the end
3808 // of statement to avoid losing it when we switch.
Jim Grosbach4b905842013-09-20 23:08:21 +00003809 if (enterIncludeFile(Filename)) {
Daniel Dunbard8a18452010-07-18 18:31:45 +00003810 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner693fbb82009-07-16 06:14:39 +00003811 return true;
3812 }
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003813
3814 return false;
3815}
Kevin Enderby09ea5702009-07-15 15:30:11 +00003816
Jim Grosbach4b905842013-09-20 23:08:21 +00003817/// parseDirectiveIncbin
Kevin Enderby109f25c2011-12-14 21:47:48 +00003818/// ::= .incbin "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00003819bool AsmParser::parseDirectiveIncbin() {
Kevin Enderby109f25c2011-12-14 21:47:48 +00003820 if (getLexer().isNot(AsmToken::String))
3821 return TokError("expected string in '.incbin' directive");
3822
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003823 // Allow the strings to have escaped octal character sequence.
3824 std::string Filename;
3825 if (parseEscapedString(Filename))
3826 return true;
Kevin Enderby109f25c2011-12-14 21:47:48 +00003827 SMLoc IncbinLoc = getLexer().getLoc();
3828 Lex();
3829
3830 if (getLexer().isNot(AsmToken::EndOfStatement))
3831 return TokError("unexpected token in '.incbin' directive");
3832
Kevin Enderby109f25c2011-12-14 21:47:48 +00003833 // Attempt to process the included file.
Jim Grosbach4b905842013-09-20 23:08:21 +00003834 if (processIncbinFile(Filename)) {
Kevin Enderby109f25c2011-12-14 21:47:48 +00003835 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3836 return true;
3837 }
3838
3839 return false;
3840}
3841
Jim Grosbach4b905842013-09-20 23:08:21 +00003842/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00003843/// ::= .if{,eq,ge,gt,le,lt,ne} expression
3844bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003845 TheCondStack.push_back(TheCondState);
3846 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00003847 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003848 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00003849 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003850 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003851 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003852 return true;
3853
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003854 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003855 return TokError("unexpected token in '.if' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003856
Sean Callanan686ed8d2010-01-19 20:22:31 +00003857 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003858
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00003859 switch (DirKind) {
3860 default:
3861 llvm_unreachable("unsupported directive");
3862 case DK_IF:
3863 case DK_IFNE:
3864 break;
3865 case DK_IFEQ:
3866 ExprValue = ExprValue == 0;
3867 break;
3868 case DK_IFGE:
3869 ExprValue = ExprValue >= 0;
3870 break;
3871 case DK_IFGT:
3872 ExprValue = ExprValue > 0;
3873 break;
3874 case DK_IFLE:
3875 ExprValue = ExprValue <= 0;
3876 break;
3877 case DK_IFLT:
3878 ExprValue = ExprValue < 0;
3879 break;
3880 }
3881
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003882 TheCondState.CondMet = ExprValue;
3883 TheCondState.Ignore = !TheCondState.CondMet;
3884 }
3885
3886 return false;
3887}
3888
Jim Grosbach4b905842013-09-20 23:08:21 +00003889/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00003890/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00003891bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00003892 TheCondStack.push_back(TheCondState);
3893 TheCondState.TheCond = AsmCond::IfCond;
3894
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00003895 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003896 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00003897 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003898 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00003899
3900 if (getLexer().isNot(AsmToken::EndOfStatement))
3901 return TokError("unexpected token in '.ifb' directive");
3902
3903 Lex();
3904
3905 TheCondState.CondMet = ExpectBlank == Str.empty();
3906 TheCondState.Ignore = !TheCondState.CondMet;
3907 }
3908
3909 return false;
3910}
3911
Jim Grosbach4b905842013-09-20 23:08:21 +00003912/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003913/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00003914/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00003915bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003916 TheCondStack.push_back(TheCondState);
3917 TheCondState.TheCond = AsmCond::IfCond;
3918
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00003919 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003920 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003921 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00003922 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003923
3924 if (getLexer().isNot(AsmToken::Comma))
3925 return TokError("unexpected token in '.ifc' directive");
3926
3927 Lex();
3928
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003929 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003930
3931 if (getLexer().isNot(AsmToken::EndOfStatement))
3932 return TokError("unexpected token in '.ifc' directive");
3933
3934 Lex();
3935
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00003936 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003937 TheCondState.Ignore = !TheCondState.CondMet;
3938 }
3939
3940 return false;
3941}
3942
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003943/// parseDirectiveIfeqs
3944/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00003945bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003946 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00003947 if (ExpectEqual)
3948 TokError("expected string parameter for '.ifeqs' directive");
3949 else
3950 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003951 eatToEndOfStatement();
3952 return true;
3953 }
3954
3955 StringRef String1 = getTok().getStringContents();
3956 Lex();
3957
3958 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00003959 if (ExpectEqual)
3960 TokError("expected comma after first string for '.ifeqs' directive");
3961 else
3962 TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003963 eatToEndOfStatement();
3964 return true;
3965 }
3966
3967 Lex();
3968
3969 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00003970 if (ExpectEqual)
3971 TokError("expected string parameter for '.ifeqs' directive");
3972 else
3973 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003974 eatToEndOfStatement();
3975 return true;
3976 }
3977
3978 StringRef String2 = getTok().getStringContents();
3979 Lex();
3980
3981 TheCondStack.push_back(TheCondState);
3982 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00003983 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003984 TheCondState.Ignore = !TheCondState.CondMet;
3985
3986 return false;
3987}
3988
Jim Grosbach4b905842013-09-20 23:08:21 +00003989/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003990/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00003991bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00003992 StringRef Name;
3993 TheCondStack.push_back(TheCondState);
3994 TheCondState.TheCond = AsmCond::IfCond;
3995
3996 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003997 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00003998 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003999 if (parseIdentifier(Name))
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004000 return TokError("expected identifier after '.ifdef'");
4001
4002 Lex();
4003
Jim Grosbach6f482002015-05-18 18:43:14 +00004004 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004005
4006 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004007 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004008 else
Craig Topper353eda42014-04-24 06:44:33 +00004009 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004010 TheCondState.Ignore = !TheCondState.CondMet;
4011 }
4012
4013 return false;
4014}
4015
Jim Grosbach4b905842013-09-20 23:08:21 +00004016/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004017/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004018bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004019 if (TheCondState.TheCond != AsmCond::IfCond &&
4020 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004021 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4022 " an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004023 TheCondState.TheCond = AsmCond::ElseIfCond;
4024
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004025 bool LastIgnoreState = false;
4026 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004027 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004028 if (LastIgnoreState || TheCondState.CondMet) {
4029 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004030 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004031 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004032 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004033 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004034 return true;
4035
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004036 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004037 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004038
Sean Callanan686ed8d2010-01-19 20:22:31 +00004039 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004040 TheCondState.CondMet = ExprValue;
4041 TheCondState.Ignore = !TheCondState.CondMet;
4042 }
4043
4044 return false;
4045}
4046
Jim Grosbach4b905842013-09-20 23:08:21 +00004047/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004048/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004049bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004050 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004051 return TokError("unexpected token in '.else' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004052
Sean Callanan686ed8d2010-01-19 20:22:31 +00004053 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004054
4055 if (TheCondState.TheCond != AsmCond::IfCond &&
4056 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004057 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4058 ".elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004059 TheCondState.TheCond = AsmCond::ElseCond;
4060 bool LastIgnoreState = false;
4061 if (!TheCondStack.empty())
4062 LastIgnoreState = TheCondStack.back().Ignore;
4063 if (LastIgnoreState || TheCondState.CondMet)
4064 TheCondState.Ignore = true;
4065 else
4066 TheCondState.Ignore = false;
4067
4068 return false;
4069}
4070
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004071/// parseDirectiveEnd
4072/// ::= .end
4073bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4074 if (getLexer().isNot(AsmToken::EndOfStatement))
4075 return TokError("unexpected token in '.end' directive");
4076
4077 Lex();
4078
4079 while (Lexer.isNot(AsmToken::Eof))
4080 Lex();
4081
4082 return false;
4083}
4084
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004085/// parseDirectiveError
4086/// ::= .err
4087/// ::= .error [string]
4088bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4089 if (!TheCondStack.empty()) {
4090 if (TheCondStack.back().Ignore) {
4091 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004092 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004093 }
4094 }
4095
4096 if (!WithMessage)
4097 return Error(L, ".err encountered");
4098
4099 StringRef Message = ".error directive invoked in source file";
4100 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4101 if (Lexer.isNot(AsmToken::String)) {
4102 TokError(".error argument must be a string");
4103 eatToEndOfStatement();
4104 return true;
4105 }
4106
4107 Message = getTok().getStringContents();
4108 Lex();
4109 }
4110
4111 Error(L, Message);
4112 return true;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004113}
4114
Nico Weber404012b2014-07-24 16:26:06 +00004115/// parseDirectiveWarning
4116/// ::= .warning [string]
4117bool AsmParser::parseDirectiveWarning(SMLoc L) {
4118 if (!TheCondStack.empty()) {
4119 if (TheCondStack.back().Ignore) {
4120 eatToEndOfStatement();
4121 return false;
4122 }
4123 }
4124
4125 StringRef Message = ".warning directive invoked in source file";
4126 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4127 if (Lexer.isNot(AsmToken::String)) {
4128 TokError(".warning argument must be a string");
4129 eatToEndOfStatement();
4130 return true;
4131 }
4132
4133 Message = getTok().getStringContents();
4134 Lex();
4135 }
4136
4137 Warning(L, Message);
4138 return false;
4139}
4140
Jim Grosbach4b905842013-09-20 23:08:21 +00004141/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004142/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004143bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004144 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004145 return TokError("unexpected token in '.endif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004146
Sean Callanan686ed8d2010-01-19 20:22:31 +00004147 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004148
Jim Grosbach4b905842013-09-20 23:08:21 +00004149 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004150 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4151 ".else");
4152 if (!TheCondStack.empty()) {
4153 TheCondState = TheCondStack.back();
4154 TheCondStack.pop_back();
4155 }
4156
4157 return false;
4158}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004159
Eli Bendersky17233942013-01-15 22:59:42 +00004160void AsmParser::initializeDirectiveKindMap() {
4161 DirectiveKindMap[".set"] = DK_SET;
4162 DirectiveKindMap[".equ"] = DK_EQU;
4163 DirectiveKindMap[".equiv"] = DK_EQUIV;
4164 DirectiveKindMap[".ascii"] = DK_ASCII;
4165 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4166 DirectiveKindMap[".string"] = DK_STRING;
4167 DirectiveKindMap[".byte"] = DK_BYTE;
4168 DirectiveKindMap[".short"] = DK_SHORT;
4169 DirectiveKindMap[".value"] = DK_VALUE;
4170 DirectiveKindMap[".2byte"] = DK_2BYTE;
4171 DirectiveKindMap[".long"] = DK_LONG;
4172 DirectiveKindMap[".int"] = DK_INT;
4173 DirectiveKindMap[".4byte"] = DK_4BYTE;
4174 DirectiveKindMap[".quad"] = DK_QUAD;
4175 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004176 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004177 DirectiveKindMap[".single"] = DK_SINGLE;
4178 DirectiveKindMap[".float"] = DK_FLOAT;
4179 DirectiveKindMap[".double"] = DK_DOUBLE;
4180 DirectiveKindMap[".align"] = DK_ALIGN;
4181 DirectiveKindMap[".align32"] = DK_ALIGN32;
4182 DirectiveKindMap[".balign"] = DK_BALIGN;
4183 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4184 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4185 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4186 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4187 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4188 DirectiveKindMap[".org"] = DK_ORG;
4189 DirectiveKindMap[".fill"] = DK_FILL;
4190 DirectiveKindMap[".zero"] = DK_ZERO;
4191 DirectiveKindMap[".extern"] = DK_EXTERN;
4192 DirectiveKindMap[".globl"] = DK_GLOBL;
4193 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004194 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4195 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4196 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4197 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4198 DirectiveKindMap[".reference"] = DK_REFERENCE;
4199 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4200 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4201 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4202 DirectiveKindMap[".comm"] = DK_COMM;
4203 DirectiveKindMap[".common"] = DK_COMMON;
4204 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4205 DirectiveKindMap[".abort"] = DK_ABORT;
4206 DirectiveKindMap[".include"] = DK_INCLUDE;
4207 DirectiveKindMap[".incbin"] = DK_INCBIN;
4208 DirectiveKindMap[".code16"] = DK_CODE16;
4209 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4210 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004211 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004212 DirectiveKindMap[".irp"] = DK_IRP;
4213 DirectiveKindMap[".irpc"] = DK_IRPC;
4214 DirectiveKindMap[".endr"] = DK_ENDR;
4215 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4216 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4217 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4218 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004219 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4220 DirectiveKindMap[".ifge"] = DK_IFGE;
4221 DirectiveKindMap[".ifgt"] = DK_IFGT;
4222 DirectiveKindMap[".ifle"] = DK_IFLE;
4223 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004224 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004225 DirectiveKindMap[".ifb"] = DK_IFB;
4226 DirectiveKindMap[".ifnb"] = DK_IFNB;
4227 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004228 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004229 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004230 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004231 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4232 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4233 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4234 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4235 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004236 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004237 DirectiveKindMap[".endif"] = DK_ENDIF;
4238 DirectiveKindMap[".skip"] = DK_SKIP;
4239 DirectiveKindMap[".space"] = DK_SPACE;
4240 DirectiveKindMap[".file"] = DK_FILE;
4241 DirectiveKindMap[".line"] = DK_LINE;
4242 DirectiveKindMap[".loc"] = DK_LOC;
4243 DirectiveKindMap[".stabs"] = DK_STABS;
4244 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4245 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4246 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4247 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4248 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4249 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4250 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4251 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4252 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4253 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4254 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4255 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4256 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4257 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4258 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4259 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4260 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4261 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4262 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4263 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4264 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004265 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004266 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4267 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4268 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004269 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004270 DirectiveKindMap[".endm"] = DK_ENDM;
4271 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4272 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004273 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004274 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004275 DirectiveKindMap[".warning"] = DK_WARNING;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004276}
4277
Jim Grosbach4b905842013-09-20 23:08:21 +00004278MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004279 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004280
Rafael Espindola34b9c512012-06-03 23:57:14 +00004281 unsigned NestLevel = 0;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004282 for (;;) {
4283 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004284 if (getLexer().is(AsmToken::Eof)) {
4285 Error(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004286 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004287 }
4288
Rafael Espindola34b9c512012-06-03 23:57:14 +00004289 if (Lexer.is(AsmToken::Identifier) &&
4290 (getTok().getIdentifier() == ".rept")) {
4291 ++NestLevel;
4292 }
4293
4294 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004295 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004296 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004297 EndToken = getTok();
4298 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004299 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4300 TokError("unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004301 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004302 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004303 break;
4304 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004305 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004306 }
4307
Rafael Espindola34b9c512012-06-03 23:57:14 +00004308 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004309 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004310 }
4311
4312 const char *BodyStart = StartToken.getLoc().getPointer();
4313 const char *BodyEnd = EndToken.getLoc().getPointer();
4314 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4315
Rafael Espindola34b9c512012-06-03 23:57:14 +00004316 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004317 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00004318 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004319}
4320
Jim Grosbach4b905842013-09-20 23:08:21 +00004321void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00004322 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004323 OS << ".endr\n";
4324
Rafael Espindola3560ff22014-08-27 20:03:13 +00004325 std::unique_ptr<MemoryBuffer> Instantiation =
4326 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004327
Rafael Espindola34b9c512012-06-03 23:57:14 +00004328 // Create the macro instantiation object and add to the current macro
4329 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00004330 MacroInstantiation *MI = new MacroInstantiation(
4331 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004332 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004333
Rafael Espindola34b9c512012-06-03 23:57:14 +00004334 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00004335 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00004336 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004337 Lex();
4338}
4339
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004340/// parseDirectiveRept
4341/// ::= .rep | .rept count
4342bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004343 const MCExpr *CountExpr;
4344 SMLoc CountLoc = getTok().getLoc();
4345 if (parseExpression(CountExpr))
4346 return true;
4347
Rafael Espindola34b9c512012-06-03 23:57:14 +00004348 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00004349 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004350 eatToEndOfStatement();
4351 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4352 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004353
4354 if (Count < 0)
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004355 return Error(CountLoc, "Count is negative");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004356
4357 if (Lexer.isNot(AsmToken::EndOfStatement))
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004358 return TokError("unexpected token in '" + Dir + "' directive");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004359
4360 // Eat the end of statement.
4361 Lex();
4362
4363 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004364 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00004365 if (!M)
4366 return true;
4367
4368 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4369 // to hold the macro body with substitutions.
4370 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004371 raw_svector_ostream OS(Buf);
4372 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004373 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4374 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00004375 return true;
4376 }
Jim Grosbach4b905842013-09-20 23:08:21 +00004377 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004378
4379 return false;
4380}
4381
Jim Grosbach4b905842013-09-20 23:08:21 +00004382/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00004383/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004384bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004385 MCAsmMacroParameter Parameter;
Rafael Espindola768b41c2012-06-15 14:02:34 +00004386
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004387 if (parseIdentifier(Parameter.Name))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004388 return TokError("expected identifier in '.irp' directive");
4389
Rafael Espindola768b41c2012-06-15 14:02:34 +00004390 if (Lexer.isNot(AsmToken::Comma))
4391 return TokError("expected comma in '.irp' directive");
4392
4393 Lex();
4394
Eli Bendersky38274122013-01-14 23:22:36 +00004395 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004396 if (parseMacroArguments(nullptr, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004397 return true;
4398
4399 // Eat the end of statement.
4400 Lex();
4401
4402 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004403 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004404 if (!M)
4405 return true;
4406
4407 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4408 // to hold the macro body with substitutions.
4409 SmallString<256> Buf;
4410 raw_svector_ostream OS(Buf);
4411
Eli Bendersky38274122013-01-14 23:22:36 +00004412 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004413 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4414 // This is undocumented, but GAS seems to support it.
4415 if (expandMacro(OS, M->Body, Parameter, *i, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004416 return true;
4417 }
4418
Jim Grosbach4b905842013-09-20 23:08:21 +00004419 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004420
4421 return false;
4422}
4423
Jim Grosbach4b905842013-09-20 23:08:21 +00004424/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004425/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004426bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004427 MCAsmMacroParameter Parameter;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004428
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004429 if (parseIdentifier(Parameter.Name))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004430 return TokError("expected identifier in '.irpc' directive");
4431
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004432 if (Lexer.isNot(AsmToken::Comma))
4433 return TokError("expected comma in '.irpc' directive");
4434
4435 Lex();
4436
Eli Bendersky38274122013-01-14 23:22:36 +00004437 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004438 if (parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004439 return true;
4440
4441 if (A.size() != 1 || A.front().size() != 1)
4442 return TokError("unexpected token in '.irpc' directive");
4443
4444 // Eat the end of statement.
4445 Lex();
4446
4447 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004448 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004449 if (!M)
4450 return true;
4451
4452 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4453 // to hold the macro body with substitutions.
4454 SmallString<256> Buf;
4455 raw_svector_ostream OS(Buf);
4456
4457 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004458 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00004459 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004460 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004461
Toma Tabacu217116e2015-04-27 10:50:29 +00004462 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4463 // This is undocumented, but GAS seems to support it.
4464 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004465 return true;
4466 }
4467
Jim Grosbach4b905842013-09-20 23:08:21 +00004468 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004469
4470 return false;
4471}
4472
Jim Grosbach4b905842013-09-20 23:08:21 +00004473bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004474 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00004475 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004476
4477 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00004478 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004479 assert(getLexer().is(AsmToken::EndOfStatement));
4480
Jim Grosbach4b905842013-09-20 23:08:21 +00004481 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004482 return false;
4483}
Rafael Espindola12d73d12010-09-11 16:45:15 +00004484
Jim Grosbach4b905842013-09-20 23:08:21 +00004485bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00004486 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004487 const MCExpr *Value;
4488 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004489 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004490 return true;
4491 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4492 if (!MCE)
4493 return Error(ExprLoc, "unexpected expression in _emit");
4494 uint64_t IntValue = MCE->getValue();
4495 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4496 return Error(ExprLoc, "literal value out of range for directive");
4497
Chad Rosierc7f552c2013-02-12 21:33:51 +00004498 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4499 return false;
4500}
4501
Jim Grosbach4b905842013-09-20 23:08:21 +00004502bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00004503 const MCExpr *Value;
4504 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004505 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00004506 return true;
4507 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4508 if (!MCE)
4509 return Error(ExprLoc, "unexpected expression in align");
4510 uint64_t IntValue = MCE->getValue();
4511 if (!isPowerOf2_64(IntValue))
4512 return Error(ExprLoc, "literal value not a power of two greater then zero");
4513
Jim Grosbach4b905842013-09-20 23:08:21 +00004514 Info.AsmRewrites->push_back(
4515 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
Eli Friedman0f4871d2012-10-22 23:58:19 +00004516 return false;
4517}
4518
Chad Rosierf43fcf52013-02-13 21:27:17 +00004519// We are comparing pointers, but the pointers are relative to a single string.
4520// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00004521static int rewritesSort(const AsmRewrite *AsmRewriteA,
4522 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00004523 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4524 return -1;
4525 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4526 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004527
Chad Rosierfce4fab2013-04-08 17:43:47 +00004528 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4529 // rewrite to the same location. Make sure the SizeDirective rewrite is
4530 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4531 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00004532 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4533 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004534 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00004535
Jim Grosbach4b905842013-09-20 23:08:21 +00004536 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4537 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004538 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00004539 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00004540}
4541
Jim Grosbach4b905842013-09-20 23:08:21 +00004542bool AsmParser::parseMSInlineAsm(
4543 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4544 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4545 SmallVectorImpl<std::string> &Constraints,
4546 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4547 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00004548 SmallVector<void *, 4> InputDecls;
4549 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00004550 SmallVector<bool, 4> InputDeclsAddressOf;
4551 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00004552 SmallVector<std::string, 4> InputConstraints;
4553 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00004554 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00004555
Benjamin Kramer1a136112013-02-15 20:37:21 +00004556 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00004557
4558 // Prime the lexer.
4559 Lex();
4560
4561 // While we have input, parse each statement.
4562 unsigned InputIdx = 0;
4563 unsigned OutputIdx = 0;
4564 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004565 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00004566 if (parseStatement(Info, &SI))
Chad Rosierf1f6a722012-10-19 22:57:33 +00004567 return true;
Chad Rosier8bce6642012-10-18 15:49:34 +00004568
Chad Rosier149e8e02012-12-12 22:45:52 +00004569 if (Info.ParseError)
4570 return true;
4571
Benjamin Kramer1a136112013-02-15 20:37:21 +00004572 if (Info.Opcode == ~0U)
4573 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004574
Benjamin Kramer1a136112013-02-15 20:37:21 +00004575 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00004576
Benjamin Kramer1a136112013-02-15 20:37:21 +00004577 // Build the list of clobbers, outputs and inputs.
4578 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00004579 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004580
Benjamin Kramer1a136112013-02-15 20:37:21 +00004581 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00004582 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00004583 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004584
Benjamin Kramer1a136112013-02-15 20:37:21 +00004585 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00004586 if (Operand.isReg() && !Operand.needAddressOf() &&
4587 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00004588 unsigned NumDefs = Desc.getNumDefs();
4589 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00004590 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4591 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004592 continue;
4593 }
4594
4595 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00004596 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00004597 if (SymName.empty())
4598 continue;
4599
David Blaikie960ea3f2014-06-08 16:18:35 +00004600 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00004601 if (!OpDecl)
4602 continue;
4603
4604 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00004605 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004606 if (isOutput) {
4607 ++InputIdx;
4608 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00004609 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00004610 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Chad Rosiere81309b2013-04-09 17:53:49 +00004611 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
Benjamin Kramer1a136112013-02-15 20:37:21 +00004612 } else {
4613 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00004614 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4615 InputConstraints.push_back(Operand.getConstraint().str());
Chad Rosiere81309b2013-04-09 17:53:49 +00004616 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
Chad Rosier8bce6642012-10-18 15:49:34 +00004617 }
Chad Rosier8bce6642012-10-18 15:49:34 +00004618 }
Reid Kleckneree088972013-12-10 18:27:32 +00004619
4620 // Consider implicit defs to be clobbers. Think of cpuid and push.
David Majnemer8114c1a2014-06-23 02:17:16 +00004621 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4622 Desc.getNumImplicitDefs());
4623 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00004624 }
4625
4626 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00004627 NumOutputs = OutputDecls.size();
4628 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00004629
4630 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00004631 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4632 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4633 ClobberRegs.end());
4634 Clobbers.assign(ClobberRegs.size(), std::string());
4635 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4636 raw_string_ostream OS(Clobbers[I]);
4637 IP->printRegName(OS, ClobberRegs[I]);
4638 }
Chad Rosier8bce6642012-10-18 15:49:34 +00004639
4640 // Merge the various outputs and inputs. Output are expected first.
4641 if (NumOutputs || NumInputs) {
4642 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00004643 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00004644 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00004645 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00004646 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00004647 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004648 }
4649 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00004650 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00004651 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004652 }
4653 }
4654
4655 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00004656 std::string AsmStringIR;
4657 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00004658 StringRef ASMString =
4659 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4660 const char *AsmStart = ASMString.begin();
4661 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00004662 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00004663 for (const AsmRewrite &AR : AsmStrRewrites) {
4664 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00004665 if (Kind == AOK_Delete)
4666 continue;
4667
David Majnemer8114c1a2014-06-23 02:17:16 +00004668 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00004669 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00004670
Chad Rosier120eefd2013-03-19 17:32:17 +00004671 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00004672 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00004673 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00004674
Chad Rosier37e755c2012-10-23 17:43:43 +00004675 // Skip the original expression.
4676 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00004677 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00004678 continue;
4679 }
4680
Chad Rosierff10ed12013-04-12 16:26:42 +00004681 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00004682 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00004683 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004684 default:
4685 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00004686 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00004687 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00004688 break;
4689 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00004690 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00004691 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00004692 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00004693 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00004694 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00004695 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00004696 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00004697 break;
4698 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00004699 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00004700 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00004701 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00004702 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00004703 default: break;
4704 case 8: OS << "byte ptr "; break;
4705 case 16: OS << "word ptr "; break;
4706 case 32: OS << "dword ptr "; break;
4707 case 64: OS << "qword ptr "; break;
4708 case 80: OS << "xword ptr "; break;
4709 case 128: OS << "xmmword ptr "; break;
4710 case 256: OS << "ymmword ptr "; break;
4711 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00004712 break;
4713 case AOK_Emit:
4714 OS << ".byte";
4715 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00004716 case AOK_Align: {
David Majnemer8114c1a2014-06-23 02:17:16 +00004717 unsigned Val = AR.Val;
Chad Rosierc7f552c2013-02-12 21:33:51 +00004718 OS << ".align " << Val;
4719
4720 // Skip the original immediate.
Benjamin Kramer1a136112013-02-15 20:37:21 +00004721 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00004722 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4723 break;
4724 }
Chad Rosierf0e87202012-10-25 20:41:34 +00004725 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00004726 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00004727 OS.flush();
4728 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00004729 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00004730 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00004731 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00004732 }
Chad Rosier0f48c552012-10-19 20:57:14 +00004733
Chad Rosier8bce6642012-10-18 15:49:34 +00004734 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00004735 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00004736 }
4737
4738 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00004739 if (AsmStart != AsmEnd)
4740 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00004741
4742 AsmString = OS.str();
4743 return false;
4744}
4745
Pete Cooper80d21cb2015-06-22 19:35:57 +00004746namespace llvm {
4747namespace MCParserUtils {
4748
4749/// Returns whether the given symbol is used anywhere in the given expression,
4750/// or subexpressions.
4751static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
4752 switch (Value->getKind()) {
4753 case MCExpr::Binary: {
4754 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
4755 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
4756 isSymbolUsedInExpression(Sym, BE->getRHS());
4757 }
4758 case MCExpr::Target:
4759 case MCExpr::Constant:
4760 return false;
4761 case MCExpr::SymbolRef: {
4762 const MCSymbol &S =
4763 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
4764 if (S.isVariable())
4765 return isSymbolUsedInExpression(Sym, S.getVariableValue());
4766 return &S == Sym;
4767 }
4768 case MCExpr::Unary:
4769 return isSymbolUsedInExpression(
4770 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
4771 }
4772
4773 llvm_unreachable("Unknown expr kind!");
4774}
4775
4776bool parseAssignmentExpression(StringRef Name, bool allow_redef,
4777 MCAsmParser &Parser, MCSymbol *&Sym,
4778 const MCExpr *&Value) {
4779 MCAsmLexer &Lexer = Parser.getLexer();
4780
4781 // FIXME: Use better location, we should use proper tokens.
4782 SMLoc EqualLoc = Lexer.getLoc();
4783
4784 if (Parser.parseExpression(Value)) {
4785 Parser.TokError("missing expression");
4786 Parser.eatToEndOfStatement();
4787 return true;
4788 }
4789
4790 // Note: we don't count b as used in "a = b". This is to allow
4791 // a = b
4792 // b = c
4793
4794 if (Lexer.isNot(AsmToken::EndOfStatement))
4795 return Parser.TokError("unexpected token in assignment");
4796
4797 // Eat the end of statement marker.
4798 Parser.Lex();
4799
4800 // Validate that the LHS is allowed to be a variable (either it has not been
4801 // used as a symbol, or it is an absolute symbol).
4802 Sym = Parser.getContext().lookupSymbol(Name);
4803 if (Sym) {
4804 // Diagnose assignment to a label.
4805 //
4806 // FIXME: Diagnostics. Note the location of the definition as a label.
4807 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
4808 if (isSymbolUsedInExpression(Sym, Value))
4809 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
4810 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
4811 ; // Allow redefinitions of undefined symbols only used in directives.
4812 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
4813 ; // Allow redefinitions of variables that haven't yet been used.
4814 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
4815 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
4816 else if (!Sym->isVariable())
4817 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
4818 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
4819 return Parser.Error(EqualLoc,
4820 "invalid reassignment of non-absolute variable '" +
4821 Name + "'");
4822
4823 // Don't count these checks as uses.
4824 Sym->setUsed(false);
4825 } else if (Name == ".") {
4826 if (Parser.getStreamer().EmitValueToOffset(Value, 0)) {
4827 Parser.Error(EqualLoc, "expected absolute expression");
4828 Parser.eatToEndOfStatement();
4829 return true;
4830 }
4831 return false;
4832 } else
4833 Sym = Parser.getContext().getOrCreateSymbol(Name);
4834
4835 Sym->setRedefinable(allow_redef);
4836
4837 return false;
4838}
4839
4840} // namespace MCParserUtils
4841} // namespace llvm
4842
Daniel Dunbar01e36072010-07-17 02:26:10 +00004843/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00004844MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4845 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00004846 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00004847}