blob: 53ce02c08996587d30bf583f739856e1e18ee052 [file] [log] [blame]
Chris Lattner27aa7d22009-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 Dunbarb95a0792010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Daniel Dunbar7c0a3342009-08-26 22:49:51 +000015#include "llvm/ADT/SmallString.h"
Chad Rosierabde6752013-02-13 18:38:58 +000016#include "llvm/ADT/STLExtras.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000017#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000018#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000019#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000020#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000021#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000022#include "llvm/MC/MCExpr.h"
Chad Rosierb1f8c132012-10-18 15:49:34 +000023#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/MC/MCInstrInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000025#include "llvm/MC/MCParser/AsmCond.h"
26#include "llvm/MC/MCParser/AsmLexer.h"
27#include "llvm/MC/MCParser/MCAsmParser.h"
28#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000029#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000030#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000031#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000032#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000033#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000034#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000035#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000036#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000037#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000038#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000039#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000040#include <cctype>
Chad Rosierb1f8c132012-10-18 15:49:34 +000041#include <set>
42#include <string>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000043#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000044using namespace llvm;
45
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000046static cl::opt<bool>
47FatalAssemblerWarnings("fatal-assembler-warnings",
48 cl::desc("Consider warnings as error"));
49
Eric Christopher2318ba12012-12-18 00:30:54 +000050MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewycky0d7d11d2012-10-19 07:00:09 +000051
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000052namespace {
53
Eli Benderskyf9f40bd2013-01-16 18:56:50 +000054/// \brief Helper types for tracking macro definitions.
55typedef std::vector<AsmToken> MCAsmMacroArgument;
56typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
57typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
58typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
59
60struct MCAsmMacro {
61 StringRef Name;
62 StringRef Body;
63 MCAsmMacroParameters Parameters;
64
65public:
66 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
67 Name(N), Body(B), Parameters(P) {}
68
69 MCAsmMacro(const MCAsmMacro& Other)
70 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
71};
72
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000073/// \brief Helper class for storing information about an active macro
74/// instantiation.
75struct MacroInstantiation {
76 /// The macro being instantiated.
Eli Benderskyc0c67b02013-01-14 23:22:36 +000077 const MCAsmMacro *TheMacro;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000078
79 /// The macro instantiation with substitutions.
80 MemoryBuffer *Instantiation;
81
82 /// The location of the instantiation.
83 SMLoc InstantiationLoc;
84
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000085 /// The buffer where parsing should resume upon instantiation completion.
86 int ExitBuffer;
87
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000088 /// The location where parsing should resume upon instantiation completion.
89 SMLoc ExitLoc;
90
91public:
Eli Benderskyc0c67b02013-01-14 23:22:36 +000092 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000093 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000094};
95
Eli Friedman2128aae2012-10-22 23:58:19 +000096struct ParseStatementInfo {
Jim Grosbach4a200922013-09-20 23:08:21 +000097 /// \brief The parsed operands from the last parsed statement.
Eli Friedman2128aae2012-10-22 23:58:19 +000098 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
99
Jim Grosbach4a200922013-09-20 23:08:21 +0000100 /// \brief The opcode from the last parsed instruction.
Eli Friedman2128aae2012-10-22 23:58:19 +0000101 unsigned Opcode;
102
Jim Grosbach4a200922013-09-20 23:08:21 +0000103 /// \brief Was there an error parsing the inline assembly?
Chad Rosier57498012012-12-12 22:45:52 +0000104 bool ParseError;
105
Eli Friedman2128aae2012-10-22 23:58:19 +0000106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107
Chad Rosier57498012012-12-12 22:45:52 +0000108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier57498012012-12-12 22:45:52 +0000110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000111
112 ~ParseStatementInfo() {
113 // Free any parsed operands.
114 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
115 delete ParsedOperands[i];
116 ParsedOperands.clear();
117 }
118};
119
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000120/// \brief The concrete assembly parser instance.
121class AsmParser : public MCAsmParser {
Craig Topper85aadc02012-09-15 16:23:52 +0000122 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
123 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000124private:
125 AsmLexer Lexer;
126 MCContext &Ctx;
127 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000128 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000129 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000130 SourceMgr::DiagHandlerTy SavedDiagHandler;
131 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000132 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000133
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
136 int CurBuffer;
137
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
140
Jim Grosbach4a200922013-09-20 23:08:21 +0000141 /// \brief maps directive names to handler methods in parser
Eli Bendersky6ee13082013-01-15 22:59:42 +0000142 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000143 /// addDirectiveHandler.
Eli Bendersky6ee13082013-01-15 22:59:42 +0000144 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000145
Jim Grosbach4a200922013-09-20 23:08:21 +0000146 /// \brief Map of currently defined macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000147 StringMap<MCAsmMacro*> MacroMap;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000148
Jim Grosbach4a200922013-09-20 23:08:21 +0000149 /// \brief Stack of active macro instantiations.
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000150 std::vector<MacroInstantiation*> ActiveMacros;
151
Jim Grosbach4a200922013-09-20 23:08:21 +0000152 /// \brief List of bodies of anonymous macros.
Benjamin Kramera2b0c332013-08-04 09:06:29 +0000153 std::deque<MCAsmMacro> MacroLikeBodies;
154
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000155 /// Boolean tracking whether macro substitution is enabled.
Eli Bendersky733c3362013-01-14 18:08:41 +0000156 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000157
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000158 /// Flag tracking whether any errors have been encountered.
159 unsigned HadError : 1;
160
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000161 /// The values from the last parsed cpp hash file line comment if any.
162 StringRef CppHashFilename;
163 int64_t CppHashLineNumber;
164 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000165 int CppHashBuf;
Kevin Enderbya8959492013-06-21 20:51:39 +0000166 /// When generating dwarf for assembly source files we need to calculate the
167 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic7b0a7962013-08-20 13:33:18 +0000168 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderbya8959492013-06-21 20:51:39 +0000169 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
170 SMLoc LastQueryIDLoc;
171 int LastQueryBuffer;
172 unsigned LastQueryLine;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000173
Devang Patel0db58bf2012-01-31 18:14:05 +0000174 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
175 unsigned AssemblerDialect;
176
Jim Grosbach4a200922013-09-20 23:08:21 +0000177 /// \brief is Darwin compatibility enabled?
Preston Gurd7b6f2032012-09-19 20:36:12 +0000178 bool IsDarwin;
179
Jim Grosbach4a200922013-09-20 23:08:21 +0000180 /// \brief Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000181 bool ParsingInlineAsm;
182
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000183public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000184 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000185 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000186 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000187
188 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
189
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000190 virtual void addDirectiveHandler(StringRef Directive,
Eli Bendersky171192f2013-01-16 00:50:52 +0000191 ExtensionDirectiveHandler Handler) {
192 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000193 }
194
195public:
196 /// @name MCAsmParser Interface
197 /// {
198
199 virtual SourceMgr &getSourceManager() { return SrcMgr; }
200 virtual MCAsmLexer &getLexer() { return Lexer; }
201 virtual MCContext &getContext() { return Ctx; }
202 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000203 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000204 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000205 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000206 else
207 return AssemblerDialect;
208 }
209 virtual void setAssemblerDialect(unsigned i) {
210 AssemblerDialect = i;
211 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000212
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000213 virtual bool Warning(SMLoc L, const Twine &Msg,
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000214 ArrayRef<SMRange> Ranges = None);
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000215 virtual bool Error(SMLoc L, const Twine &Msg,
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000216 ArrayRef<SMRange> Ranges = None);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000217
Craig Topper345d16d2012-08-29 05:48:09 +0000218 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000219
Chad Rosier84125ca2012-10-13 00:26:04 +0000220 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000221 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000222
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000223 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000224 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000225 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000226 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000227 SmallVectorImpl<std::string> &Clobbers,
228 const MCInstrInfo *MII,
229 const MCInstPrinter *IP,
230 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000231
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000232 bool parseExpression(const MCExpr *&Res);
233 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
Chad Rosierba69b362013-04-10 17:35:30 +0000234 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000235 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
236 virtual bool parseAbsoluteExpression(int64_t &Res);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000237
Jim Grosbach4a200922013-09-20 23:08:21 +0000238 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Benderskybf706b32013-01-12 00:05:00 +0000239 /// and set \p Res to the identifier contents.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000240 virtual bool parseIdentifier(StringRef &Res);
241 virtual void eatToEndOfStatement();
Eli Benderskybf706b32013-01-12 00:05:00 +0000242
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000243 virtual void checkForValidSection();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000244 /// }
245
246private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000247
Jim Grosbach4a200922013-09-20 23:08:21 +0000248 bool parseStatement(ParseStatementInfo &Info);
249 void eatToEndOfLine();
250 bool parseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000251
Jim Grosbach4a200922013-09-20 23:08:21 +0000252 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Kevin Enderby221514e2013-01-22 21:44:53 +0000253 MCAsmMacroParameters Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +0000254 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000255 const MCAsmMacroParameters &Parameters,
256 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000257 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000258
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000259 /// \brief Are macros enabled in the parser?
Jim Grosbach4a200922013-09-20 23:08:21 +0000260 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000261
262 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4a200922013-09-20 23:08:21 +0000263 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000264
265 /// \brief Lookup a previously defined macro.
266 /// \param Name Macro name.
267 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4a200922013-09-20 23:08:21 +0000268 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000269
270 /// \brief Define a new macro with the given name and information.
Jim Grosbach4a200922013-09-20 23:08:21 +0000271 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000272
273 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4a200922013-09-20 23:08:21 +0000274 void undefineMacro(StringRef Name);
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000275
276 /// \brief Are we inside a macro instantiation?
Jim Grosbach4a200922013-09-20 23:08:21 +0000277 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000278
Vladimir Medic7b0a7962013-08-20 13:33:18 +0000279 /// \brief Handle entry to macro instantiation.
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000280 ///
281 /// \param M The macro.
282 /// \param NameLoc Instantiation location.
Jim Grosbach4a200922013-09-20 23:08:21 +0000283 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000284
285 /// \brief Handle exit from macro instantiation.
Jim Grosbach4a200922013-09-20 23:08:21 +0000286 void handleMacroExit();
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000287
288 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
289 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
290 /// correct delimiter by the method.
Jim Grosbach4a200922013-09-20 23:08:21 +0000291 bool parseMacroArgument(MCAsmMacroArgument &MA,
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000292 AsmToken::TokenKind &ArgumentDelimiter);
293
294 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4a200922013-09-20 23:08:21 +0000295 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000296
Jim Grosbach4a200922013-09-20 23:08:21 +0000297 void printMacroInstantiations();
298 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000299 ArrayRef<SMRange> Ranges = None) const {
Chris Lattner462b43c2011-10-16 05:47:55 +0000300 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000301 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000302 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000303
Jim Grosbach4a200922013-09-20 23:08:21 +0000304 /// \brief Enter the specified file. This returns true on failure.
305 bool enterIncludeFile(const std::string &Filename);
306
307 /// \brief Process the specified file for the .incbin directive.
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000308 /// This returns true on failure.
Jim Grosbach4a200922013-09-20 23:08:21 +0000309 bool processIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000310
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000311 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000312 /// current token is not set; clients should ensure Lex() is called
313 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000314 ///
315 /// \param InBuffer If not -1, should be the known buffer id that contains the
316 /// location.
Jim Grosbach4a200922013-09-20 23:08:21 +0000317 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000318
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000319 /// \brief Parse up to the end of statement and a return the contents from the
320 /// current token until the end of the statement; the current token on exit
321 /// will be either the EndOfStatement or EOF.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000322 virtual StringRef parseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000323
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000324 /// \brief Parse until the end of a statement or a comma is encountered,
325 /// return the contents from the current token up to the end or comma.
Jim Grosbach4a200922013-09-20 23:08:21 +0000326 StringRef parseStringToComma();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000327
Jim Grosbach4a200922013-09-20 23:08:21 +0000328 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000329 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000330
Jim Grosbach4a200922013-09-20 23:08:21 +0000331 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
332 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
333 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000334
Jim Grosbach4a200922013-09-20 23:08:21 +0000335 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola787c3372010-10-28 20:02:27 +0000336
Eli Bendersky6ee13082013-01-15 22:59:42 +0000337 // Generic (target and platform independent) directive parsing.
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000338 enum DirectiveKind {
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000339 DK_NO_DIRECTIVE, // Placeholder
340 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
341 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
342 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky9b1bb052013-01-11 22:55:28 +0000343 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000344 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby4f066b62013-08-28 17:50:59 +0000345 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000346 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
347 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
348 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
349 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
350 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000351 DK_ELSEIF, DK_ELSE, DK_ENDIF,
352 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
353 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
354 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
355 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
356 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
357 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju83ba58e2013-09-26 14:49:40 +0000358 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000359 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
360 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000361 };
362
Jim Grosbach4a200922013-09-20 23:08:21 +0000363 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky6ee13082013-01-15 22:59:42 +0000364 /// directives parsed by this class.
365 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000366
367 // ".ascii", ".asciz", ".string"
Jim Grosbach4a200922013-09-20 23:08:21 +0000368 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
369 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
370 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
371 bool parseDirectiveFill(); // ".fill"
372 bool parseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000373 // ".set", ".equ", ".equiv"
Jim Grosbach4a200922013-09-20 23:08:21 +0000374 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
375 bool parseDirectiveOrg(); // ".org"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000376 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4a200922013-09-20 23:08:21 +0000377 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000378
Eli Bendersky6ee13082013-01-15 22:59:42 +0000379 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4a200922013-09-20 23:08:21 +0000380 bool parseDirectiveFile(SMLoc DirectiveLoc);
381 bool parseDirectiveLine();
382 bool parseDirectiveLoc();
383 bool parseDirectiveStabs();
Eli Bendersky6ee13082013-01-15 22:59:42 +0000384
385 // .cfi directives
Jim Grosbach4a200922013-09-20 23:08:21 +0000386 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju83ba58e2013-09-26 14:49:40 +0000387 bool parseDirectiveCFIWindowSave();
Jim Grosbach4a200922013-09-20 23:08:21 +0000388 bool parseDirectiveCFISections();
389 bool parseDirectiveCFIStartProc();
390 bool parseDirectiveCFIEndProc();
391 bool parseDirectiveCFIDefCfaOffset();
392 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
393 bool parseDirectiveCFIAdjustCfaOffset();
394 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
395 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
397 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
398 bool parseDirectiveCFIRememberState();
399 bool parseDirectiveCFIRestoreState();
400 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
401 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIEscape();
403 bool parseDirectiveCFISignalFrame();
404 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky6ee13082013-01-15 22:59:42 +0000405
406 // macro directives
Jim Grosbach4a200922013-09-20 23:08:21 +0000407 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
408 bool parseDirectiveEndMacro(StringRef Directive);
409 bool parseDirectiveMacro(SMLoc DirectiveLoc);
410 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky6ee13082013-01-15 22:59:42 +0000411
Eli Bendersky4766ef42012-12-20 19:05:53 +0000412 // ".bundle_align_mode"
Jim Grosbach4a200922013-09-20 23:08:21 +0000413 bool parseDirectiveBundleAlignMode();
Eli Bendersky4766ef42012-12-20 19:05:53 +0000414 // ".bundle_lock"
Jim Grosbach4a200922013-09-20 23:08:21 +0000415 bool parseDirectiveBundleLock();
Eli Bendersky4766ef42012-12-20 19:05:53 +0000416 // ".bundle_unlock"
Jim Grosbach4a200922013-09-20 23:08:21 +0000417 bool parseDirectiveBundleUnlock();
Eli Bendersky4766ef42012-12-20 19:05:53 +0000418
Eli Bendersky6ee13082013-01-15 22:59:42 +0000419 // ".space", ".skip"
Jim Grosbach4a200922013-09-20 23:08:21 +0000420 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky6ee13082013-01-15 22:59:42 +0000421
422 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4a200922013-09-20 23:08:21 +0000423 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky6ee13082013-01-15 22:59:42 +0000424
Jim Grosbach4a200922013-09-20 23:08:21 +0000425 /// \brief Parse a directive like ".globl" which
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000426 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4a200922013-09-20 23:08:21 +0000427 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000428
Jim Grosbach4a200922013-09-20 23:08:21 +0000429 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000430
Jim Grosbach4a200922013-09-20 23:08:21 +0000431 bool parseDirectiveAbort(); // ".abort"
432 bool parseDirectiveInclude(); // ".include"
433 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000434
Jim Grosbach4a200922013-09-20 23:08:21 +0000435 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000436 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4a200922013-09-20 23:08:21 +0000437 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000438 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4a200922013-09-20 23:08:21 +0000439 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000440 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4a200922013-09-20 23:08:21 +0000441 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
442 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
443 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
444 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000445 virtual bool parseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000446
Jim Grosbach4a200922013-09-20 23:08:21 +0000447 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbarcceba832010-09-17 02:47:07 +0000448 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000449
Rafael Espindola761cb062012-06-03 23:57:14 +0000450 // Macro-like directives
Jim Grosbach4a200922013-09-20 23:08:21 +0000451 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
452 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000453 raw_svector_ostream &OS);
Jim Grosbach4a200922013-09-20 23:08:21 +0000454 bool parseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
455 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
456 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
457 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000458
Chad Rosier469b1442013-02-12 21:33:51 +0000459 // "_emit" or "__emit"
Jim Grosbach4a200922013-09-20 23:08:21 +0000460 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosier469b1442013-02-12 21:33:51 +0000461 size_t Len);
462
463 // "align"
Jim Grosbach4a200922013-09-20 23:08:21 +0000464 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000465
Eli Bendersky6ee13082013-01-15 22:59:42 +0000466 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000467};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000468}
469
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000470namespace llvm {
471
472extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000473extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000474extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000475
476}
477
Chris Lattneraaec2052010-01-19 19:46:13 +0000478enum { DEFAULT_ADDRSPACE = 0 };
479
Jim Grosbach4a200922013-09-20 23:08:21 +0000480AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
481 const MCAsmInfo &_MAI)
482 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
483 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
484 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
485 ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000486 // Save the old handler.
487 SavedDiagHandler = SrcMgr.getDiagHandler();
488 SavedDiagContext = SrcMgr.getDiagContext();
489 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000490 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000491 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000492
Daniel Dunbare4749702010-07-12 18:12:02 +0000493 // Initialize the platform / file format parser.
494 //
495 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
496 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000497 if (_MAI.hasMicrosoftFastStdCallMangling()) {
498 PlatformParser = createCOFFAsmParser();
499 PlatformParser->Initialize(*this);
500 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000501 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000502 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000503 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000504 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000505 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000506 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000507 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000508
Eli Bendersky6ee13082013-01-15 22:59:42 +0000509 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000510}
511
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000512AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000513 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
514
515 // Destroy any macros.
Jim Grosbach4a200922013-09-20 23:08:21 +0000516 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
517 ie = MacroMap.end();
518 it != ie; ++it)
Daniel Dunbar56491302010-07-29 01:51:55 +0000519 delete it->getValue();
520
Daniel Dunbare4749702010-07-12 18:12:02 +0000521 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000522}
523
Jim Grosbach4a200922013-09-20 23:08:21 +0000524void AsmParser::printMacroInstantiations() {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000525 // Print the active macro instantiation stack.
Jim Grosbach4a200922013-09-20 23:08:21 +0000526 for (std::vector<MacroInstantiation *>::const_reverse_iterator
527 it = ActiveMacros.rbegin(),
528 ie = ActiveMacros.rend();
529 it != ie; ++it)
530 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000531 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000532}
533
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000534bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000535 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000536 return Error(L, Msg, Ranges);
Jim Grosbach4a200922013-09-20 23:08:21 +0000537 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
538 printMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000539 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000540}
541
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000542bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000543 HadError = true;
Jim Grosbach4a200922013-09-20 23:08:21 +0000544 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
545 printMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000546 return true;
547}
548
Jim Grosbach4a200922013-09-20 23:08:21 +0000549bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000550 std::string IncludedFile;
551 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000552 if (NewBuf == -1)
553 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000554
Sean Callananfd0b0282010-01-21 00:19:58 +0000555 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000556
Sean Callananfd0b0282010-01-21 00:19:58 +0000557 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000558
Sean Callananfd0b0282010-01-21 00:19:58 +0000559 return false;
560}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000561
Sylvestre Ledruda2ed452013-05-14 23:36:24 +0000562/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000563/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000564/// returns true on failure.
Jim Grosbach4a200922013-09-20 23:08:21 +0000565bool AsmParser::processIncbinFile(const std::string &Filename) {
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000566 std::string IncludedFile;
567 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
568 if (NewBuf == -1)
569 return true;
570
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000571 // Pick up the bytes from the file and emit them.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +0000572 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000573 return false;
574}
575
Jim Grosbach4a200922013-09-20 23:08:21 +0000576void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000577 if (InBuffer != -1) {
578 CurBuffer = InBuffer;
579 } else {
580 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
581 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000582 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
583}
584
Sean Callananfd0b0282010-01-21 00:19:58 +0000585const AsmToken &AsmParser::Lex() {
586 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000587
Sean Callananfd0b0282010-01-21 00:19:58 +0000588 if (tok->is(AsmToken::Eof)) {
589 // If this is the end of an included file, pop the parent file off the
590 // include stack.
591 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
592 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4a200922013-09-20 23:08:21 +0000593 jumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000594 tok = &Lexer.Lex();
595 }
596 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000597
Sean Callananfd0b0282010-01-21 00:19:58 +0000598 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000599 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000600
Sean Callananfd0b0282010-01-21 00:19:58 +0000601 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000602}
603
Chris Lattner79180e22010-04-05 23:15:42 +0000604bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000605 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000606 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000607 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000608
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000609 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000610 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000611
612 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000613 AsmCond StartingCondState = TheCondState;
614
Kevin Enderby613b7572011-11-01 22:27:22 +0000615 // If we are generating dwarf for assembly source files save the initial text
616 // section and generate a .file directive.
617 if (getContext().getGenDwarfForAssembly()) {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000618 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
Kevin Enderby94c2e852011-12-09 18:09:40 +0000619 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
620 getStreamer().EmitLabel(SectionStartSym);
621 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000622 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000623 StringRef(),
624 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000625 }
626
Chris Lattnerb717fb02009-07-02 21:53:43 +0000627 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000628 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000629 ParseStatementInfo Info;
Jim Grosbach4a200922013-09-20 23:08:21 +0000630 if (!parseStatement(Info))
631 continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000632
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000633 // We had an error, validate that one was emitted and recover by skipping to
634 // the next line.
635 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000636 eatToEndOfStatement();
Chris Lattnerb717fb02009-07-02 21:53:43 +0000637 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000638
639 if (TheCondState.TheCond != StartingCondState.TheCond ||
640 TheCondState.Ignore != StartingCondState.Ignore)
641 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000642
643 // Check to see there are no empty DwarfFile slots.
Manman Ren9e999ad2013-03-12 20:17:00 +0000644 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Jim Grosbach4a200922013-09-20 23:08:21 +0000645 getContext().getMCDwarfFiles();
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000646 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000647 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000648 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000649 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000650
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000651 // Check to see that all assembler local symbols were actually defined.
652 // Targets that don't do subsections via symbols may not want this, though,
653 // so conservatively exclude them. Only do this if we're finalizing, though,
654 // as otherwise we won't necessarilly have seen everything yet.
655 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
656 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
657 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
Jim Grosbach4a200922013-09-20 23:08:21 +0000658 e = Symbols.end();
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000659 i != e; ++i) {
660 MCSymbol *Sym = i->getValue();
661 // Variable symbols may not be marked as defined, so check those
662 // explicitly. If we know it's a variable, we have a definition for
663 // the purposes of this check.
664 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
665 // FIXME: We would really like to refer back to where the symbol was
666 // first referenced for a source location. We need to add something
667 // to track that. Currently, we just point to the end of the file.
Jim Grosbach4a200922013-09-20 23:08:21 +0000668 printMessage(
669 getLexer().getLoc(), SourceMgr::DK_Error,
670 "assembler local symbol '" + Sym->getName() + "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000671 }
672 }
673
Chris Lattner79180e22010-04-05 23:15:42 +0000674 // Finalize the output stream if there are no errors and if the client wants
675 // us to.
Jack Carter8e48edc2013-10-04 21:26:15 +0000676 if (!HadError && !NoFinalize) {
677 getTargetParser().emitEndOfAsmFile(Out);
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000678 Out.Finish();
Jack Carter8e48edc2013-10-04 21:26:15 +0000679 }
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000680
Chris Lattnerb717fb02009-07-02 21:53:43 +0000681 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000682}
683
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000684void AsmParser::checkForValidSection() {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000685 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000686 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000687 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000688 }
689}
690
Jim Grosbach4a200922013-09-20 23:08:21 +0000691/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000692void AsmParser::eatToEndOfStatement() {
Jim Grosbach4a200922013-09-20 23:08:21 +0000693 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000694 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000695
Chris Lattner2cf5f142009-06-22 01:29:09 +0000696 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000697 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000698 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000699}
700
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000701StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000702 const char *Start = getTok().getLoc().getPointer();
703
Jim Grosbach4a200922013-09-20 23:08:21 +0000704 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000705 Lex();
706
707 const char *End = getTok().getLoc().getPointer();
708 return StringRef(Start, End - Start);
709}
Chris Lattnerc4193832009-06-22 05:51:26 +0000710
Jim Grosbach4a200922013-09-20 23:08:21 +0000711StringRef AsmParser::parseStringToComma() {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000712 const char *Start = getTok().getLoc().getPointer();
713
714 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4a200922013-09-20 23:08:21 +0000715 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000716 Lex();
717
718 const char *End = getTok().getLoc().getPointer();
719 return StringRef(Start, End - Start);
720}
721
Jim Grosbach4a200922013-09-20 23:08:21 +0000722/// \brief Parse a paren expression and return it.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000723/// NOTE: This assumes the leading '(' has already been consumed.
724///
725/// parenexpr ::= expr)
726///
Jim Grosbach4a200922013-09-20 23:08:21 +0000727bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
728 if (parseExpression(Res))
729 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000730 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000731 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000732 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000733 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000734 return false;
735}
Chris Lattnerc4193832009-06-22 05:51:26 +0000736
Jim Grosbach4a200922013-09-20 23:08:21 +0000737/// \brief Parse a bracket expression and return it.
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000738/// NOTE: This assumes the leading '[' has already been consumed.
739///
740/// bracketexpr ::= expr]
741///
Jim Grosbach4a200922013-09-20 23:08:21 +0000742bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
743 if (parseExpression(Res))
744 return true;
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000745 if (Lexer.isNot(AsmToken::RBrac))
746 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000747 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000748 Lex();
749 return false;
750}
751
Jim Grosbach4a200922013-09-20 23:08:21 +0000752/// \brief Parse a primary expression and return it.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000753/// primaryexpr ::= (parenexpr
754/// primaryexpr ::= symbol
755/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000756/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000757/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4a200922013-09-20 23:08:21 +0000758bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000759 SMLoc FirstTokenLoc = getLexer().getLoc();
760 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
761 switch (FirstTokenKind) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000762 default:
763 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000764 // If we have an error assume that we've already handled it.
765 case AsmToken::Error:
766 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000767 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000768 Lex(); // Eat the operator.
Jim Grosbach4a200922013-09-20 23:08:21 +0000769 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000770 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000771 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000772 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000773 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000774 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000775 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000776 StringRef Identifier;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000777 if (parseIdentifier(Identifier)) {
David Majnemer3f22cc12013-09-25 10:47:21 +0000778 if (FirstTokenKind == AsmToken::Dollar) {
779 if (Lexer.getMAI().getDollarIsPC()) {
780 // This is a '$' reference, which references the current PC. Emit a
781 // temporary label to the streamer and refer to it.
782 MCSymbol *Sym = Ctx.CreateTempSymbol();
783 Out.EmitLabel(Sym);
Jack Carter8e48edc2013-10-04 21:26:15 +0000784 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
785 getContext());
David Majnemer3f22cc12013-09-25 10:47:21 +0000786 EndLoc = FirstTokenLoc;
787 return false;
788 } else
789 return Error(FirstTokenLoc, "invalid token in expression");
790 return true;
791 }
Kevin Enderby5de048e2013-01-22 21:09:20 +0000792 }
Daniel Dunbare17edff2010-08-24 19:13:42 +0000793
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000794 EndLoc = SMLoc::getFromPointer(Identifier.end());
795
Daniel Dunbarfffff912009-10-16 01:34:54 +0000796 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000797 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000798 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000799
800 // Lookup the symbol variant if used.
801 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000802 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000803 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000804 if (Variant == MCSymbolRefExpr::VK_Invalid) {
805 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000806 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000807 }
808 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000809
Daniel Dunbarfffff912009-10-16 01:34:54 +0000810 // If this is an absolute variable reference, substitute it now to preserve
811 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000812 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000813 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000814 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000815
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000816 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000817 return false;
818 }
819
820 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000821 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000822 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000823 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000824 case AsmToken::Integer: {
825 SMLoc Loc = getTok().getLoc();
826 int64_t IntVal = getTok().getIntVal();
827 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000828 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000829 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000830 // Look for 'b' or 'f' following an Integer as a directional label
831 if (Lexer.getKind() == AsmToken::Identifier) {
832 StringRef IDVal = getTok().getString();
Ulrich Weigand151ad372013-06-20 16:24:17 +0000833 // Lookup the symbol variant if used.
834 std::pair<StringRef, StringRef> Split = IDVal.split('@');
835 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
836 if (Split.first.size() != IDVal.size()) {
837 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
838 if (Variant == MCSymbolRefExpr::VK_Invalid) {
839 Variant = MCSymbolRefExpr::VK_None;
840 return TokError("invalid variant '" + Split.second + "'");
841 }
Vladimir Medic7b0a7962013-08-20 13:33:18 +0000842 IDVal = Split.first;
Ulrich Weigand151ad372013-06-20 16:24:17 +0000843 }
Jim Grosbach4a200922013-09-20 23:08:21 +0000844 if (IDVal == "f" || IDVal == "b") {
845 MCSymbol *Sym =
846 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
Ulrich Weigand151ad372013-06-20 16:24:17 +0000847 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000848 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000849 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000850 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000851 Lex(); // Eat identifier.
852 }
853 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000854 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000855 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000856 case AsmToken::Real: {
857 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000858 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000859 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000860 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000861 Lex(); // Eat token.
862 return false;
863 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000864 case AsmToken::Dot: {
865 // This is a '.' reference, which references the current PC. Emit a
866 // temporary label to the streamer and refer to it.
867 MCSymbol *Sym = Ctx.CreateTempSymbol();
868 Out.EmitLabel(Sym);
869 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000870 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000871 Lex(); // Eat identifier.
872 return false;
873 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000874 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000875 Lex(); // Eat the '('.
Jim Grosbach4a200922013-09-20 23:08:21 +0000876 return parseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000877 case AsmToken::LBrac:
878 if (!PlatformParser->HasBracketExpressions())
879 return TokError("brackets expression not supported on this target");
880 Lex(); // Eat the '['.
Jim Grosbach4a200922013-09-20 23:08:21 +0000881 return parseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000882 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000883 Lex(); // Eat the operator.
Jim Grosbach4a200922013-09-20 23:08:21 +0000884 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000885 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000886 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000887 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000888 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000889 Lex(); // Eat the operator.
Jim Grosbach4a200922013-09-20 23:08:21 +0000890 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000891 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000892 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000893 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000894 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000895 Lex(); // Eat the operator.
Jim Grosbach4a200922013-09-20 23:08:21 +0000896 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000897 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000898 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000899 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000900 }
901}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000902
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000903bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000904 SMLoc EndLoc;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000905 return parseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000906}
907
Daniel Dunbarcceba832010-09-17 02:47:07 +0000908const MCExpr *
Jim Grosbach4a200922013-09-20 23:08:21 +0000909AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbarcceba832010-09-17 02:47:07 +0000910 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenberger66b71392013-08-27 20:23:19 +0000911 // Ask the target implementation about this expression first.
912 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
913 if (NewE)
914 return NewE;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000915 // Recurse over the given expression, rebuilding it to apply the given variant
916 // if there is exactly one symbol.
917 switch (E->getKind()) {
918 case MCExpr::Target:
919 case MCExpr::Constant:
920 return 0;
921
922 case MCExpr::SymbolRef: {
923 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
924
925 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4a200922013-09-20 23:08:21 +0000926 TokError("invalid variant on expression '" + getTok().getIdentifier() +
927 "' (already modified)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000928 return E;
929 }
930
931 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
932 }
933
934 case MCExpr::Unary: {
935 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4a200922013-09-20 23:08:21 +0000936 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000937 if (!Sub)
938 return 0;
939 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
940 }
941
942 case MCExpr::Binary: {
943 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4a200922013-09-20 23:08:21 +0000944 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
945 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000946
947 if (!LHS && !RHS)
948 return 0;
949
Jim Grosbach4a200922013-09-20 23:08:21 +0000950 if (!LHS)
951 LHS = BE->getLHS();
952 if (!RHS)
953 RHS = BE->getRHS();
Daniel Dunbarcceba832010-09-17 02:47:07 +0000954
955 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
956 }
957 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000958
Craig Topper85814382012-02-07 05:05:23 +0000959 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000960}
961
Jim Grosbach4a200922013-09-20 23:08:21 +0000962/// \brief Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000963///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000964/// expr ::= expr &&,|| expr -> lowest.
965/// expr ::= expr |,^,&,! expr
966/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
967/// expr ::= expr <<,>> expr
968/// expr ::= expr +,- expr
969/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000970/// expr ::= primaryexpr
971///
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000972bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000973 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000974 Res = 0;
Jim Grosbach4a200922013-09-20 23:08:21 +0000975 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000976 return true;
977
Daniel Dunbarcceba832010-09-17 02:47:07 +0000978 // As a special case, we support 'a op b @ modifier' by rewriting the
979 // expression to include the modifier. This is inefficient, but in general we
980 // expect users to use 'a@modifier op b'.
981 if (Lexer.getKind() == AsmToken::At) {
982 Lex();
983
984 if (Lexer.isNot(AsmToken::Identifier))
985 return TokError("unexpected symbol modifier following '@'");
986
987 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4a200922013-09-20 23:08:21 +0000988 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbarcceba832010-09-17 02:47:07 +0000989 if (Variant == MCSymbolRefExpr::VK_Invalid)
990 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
991
Jim Grosbach4a200922013-09-20 23:08:21 +0000992 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000993 if (!ModifiedRes) {
994 return TokError("invalid modifier '" + getTok().getIdentifier() +
995 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000996 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000997
Daniel Dunbarcceba832010-09-17 02:47:07 +0000998 Res = ModifiedRes;
999 Lex();
1000 }
1001
Daniel Dunbare9a60eb2010-02-13 01:28:07 +00001002 // Try to constant fold it up front, if possible.
1003 int64_t Value;
1004 if (Res->EvaluateAsAbsolute(Value))
1005 Res = MCConstantExpr::Create(Value, getContext());
1006
1007 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +00001008}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001009
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001010bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +00001011 Res = 0;
Jim Grosbach4a200922013-09-20 23:08:21 +00001012 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +00001013}
1014
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001015bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001016 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001017
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00001018 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001019 if (parseExpression(Expr))
Daniel Dunbar475839e2009-06-29 20:37:27 +00001020 return true;
1021
Daniel Dunbare00b0112009-10-16 01:57:52 +00001022 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00001023 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +00001024
1025 return false;
1026}
1027
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001028static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001029 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001030 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001031 default:
Jim Grosbach4a200922013-09-20 23:08:21 +00001032 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +00001033
Jim Grosbach4a200922013-09-20 23:08:21 +00001034 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +00001035 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001036 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001037 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001038 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001039 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001040 return 1;
1041
Jim Grosbach4a200922013-09-20 23:08:21 +00001042 // Low Precedence: |, &, ^
1043 //
1044 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001045 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001046 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001047 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001048 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001049 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001050 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001051 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001052 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001053 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001054
Jim Grosbach4a200922013-09-20 23:08:21 +00001055 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001056 case AsmToken::EqualEqual:
1057 Kind = MCBinaryExpr::EQ;
1058 return 3;
1059 case AsmToken::ExclaimEqual:
1060 case AsmToken::LessGreater:
1061 Kind = MCBinaryExpr::NE;
1062 return 3;
1063 case AsmToken::Less:
1064 Kind = MCBinaryExpr::LT;
1065 return 3;
1066 case AsmToken::LessEqual:
1067 Kind = MCBinaryExpr::LTE;
1068 return 3;
1069 case AsmToken::Greater:
1070 Kind = MCBinaryExpr::GT;
1071 return 3;
1072 case AsmToken::GreaterEqual:
1073 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001074 return 3;
1075
Jim Grosbach4a200922013-09-20 23:08:21 +00001076 // Intermediate Precedence: <<, >>
Jim Grosbachfbe16812011-08-20 16:24:13 +00001077 case AsmToken::LessLess:
1078 Kind = MCBinaryExpr::Shl;
1079 return 4;
1080 case AsmToken::GreaterGreater:
1081 Kind = MCBinaryExpr::Shr;
1082 return 4;
1083
Jim Grosbach4a200922013-09-20 23:08:21 +00001084 // High Intermediate Precedence: +, -
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001085 case AsmToken::Plus:
1086 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001087 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001088 case AsmToken::Minus:
1089 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001090 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001091
Jim Grosbach4a200922013-09-20 23:08:21 +00001092 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001093 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001094 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001095 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001096 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001097 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001098 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001099 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001100 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001101 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001102 }
1103}
1104
Jim Grosbach4a200922013-09-20 23:08:21 +00001105/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001106/// Res contains the LHS of the expression on input.
Jim Grosbach4a200922013-09-20 23:08:21 +00001107bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattnerb4307b32010-01-15 19:28:38 +00001108 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001109 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001110 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001111 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001112
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001113 // If the next token is lower precedence than we are allowed to eat, return
1114 // successfully with what we ate already.
1115 if (TokPrec < Precedence)
1116 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001117
Sean Callanan79ed1a82010-01-19 20:22:31 +00001118 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001119
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001120 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001121 const MCExpr *RHS;
Jim Grosbach4a200922013-09-20 23:08:21 +00001122 if (parsePrimaryExpr(RHS, EndLoc))
1123 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001124
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001125 // If BinOp binds less tightly with RHS than the operator after RHS, let
1126 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001127 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001128 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4a200922013-09-20 23:08:21 +00001129 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1130 return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001131
Daniel Dunbar475839e2009-06-29 20:37:27 +00001132 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001133 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001134 }
1135}
1136
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001137/// ParseStatement:
1138/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001139/// ::= Label* Directive ...Operands... EndOfStatement
1140/// ::= Label* Identifier OperandList* EndOfStatement
Jim Grosbach4a200922013-09-20 23:08:21 +00001141bool AsmParser::parseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001142 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001143 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001144 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001145 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001146 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001147
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001148 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001149 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001150 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001151 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001152 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001153 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001154 if (Lexer.is(AsmToken::Hash))
Jim Grosbach4a200922013-09-20 23:08:21 +00001155 return parseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001156
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001157 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001158 if (Lexer.is(AsmToken::Integer)) {
1159 LocalLabelVal = getTok().getIntVal();
1160 if (LocalLabelVal < 0) {
1161 if (!TheCondState.Ignore)
1162 return TokError("unexpected token at start of statement");
1163 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001164 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001165 IDVal = getTok().getString();
1166 Lex(); // Consume the integer token to be used as an identifier token.
1167 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001168 if (!TheCondState.Ignore)
1169 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001170 }
1171 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001172 } else if (Lexer.is(AsmToken::Dot)) {
1173 // Treat '.' as a valid identifier in this context.
1174 Lex();
1175 IDVal = ".";
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001176 } else if (parseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001177 if (!TheCondState.Ignore)
1178 return TokError("unexpected token at start of statement");
1179 IDVal = "";
1180 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001181
Chris Lattner7834fac2010-04-17 18:14:27 +00001182 // Handle conditional assembly here before checking for skipping. We
1183 // have to do this so that .endif isn't skipped in a ".if 0" block for
1184 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001185 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4a200922013-09-20 23:08:21 +00001186 DirectiveKindMap.find(IDVal);
1187 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1188 ? DK_NO_DIRECTIVE
1189 : DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001190 switch (DirKind) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001191 default:
1192 break;
1193 case DK_IF:
1194 return parseDirectiveIf(IDLoc);
1195 case DK_IFB:
1196 return parseDirectiveIfb(IDLoc, true);
1197 case DK_IFNB:
1198 return parseDirectiveIfb(IDLoc, false);
1199 case DK_IFC:
1200 return parseDirectiveIfc(IDLoc, true);
1201 case DK_IFNC:
1202 return parseDirectiveIfc(IDLoc, false);
1203 case DK_IFDEF:
1204 return parseDirectiveIfdef(IDLoc, true);
1205 case DK_IFNDEF:
1206 case DK_IFNOTDEF:
1207 return parseDirectiveIfdef(IDLoc, false);
1208 case DK_ELSEIF:
1209 return parseDirectiveElseIf(IDLoc);
1210 case DK_ELSE:
1211 return parseDirectiveElse(IDLoc);
1212 case DK_ENDIF:
1213 return parseDirectiveEndIf(IDLoc);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001214 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001215
Eli Benderskyed5df012013-01-16 19:32:36 +00001216 // Ignore the statement if in the middle of inactive conditional
1217 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001218 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001219 eatToEndOfStatement();
Chris Lattner7834fac2010-04-17 18:14:27 +00001220 return false;
1221 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001222
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001223 // FIXME: Recurse on local labels?
1224
1225 // See what kind of statement we have.
1226 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001227 case AsmToken::Colon: {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001228 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001229
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001230 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001231 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001232
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001233 // Diagnose attempt to use '.' as a label.
1234 if (IDVal == ".")
1235 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1236
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001237 // Diagnose attempt to use a variable as a label.
1238 //
1239 // FIXME: Diagnostics. Note the location of the definition as a label.
1240 // FIXME: This doesn't diagnose assignment to a symbol which has been
1241 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001242 MCSymbol *Sym;
1243 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001244 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001245 else
1246 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001247 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001248 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001249
Daniel Dunbar959fd882009-08-26 22:13:22 +00001250 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001251 if (!ParsingInlineAsm)
1252 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001253
Kevin Enderby94c2e852011-12-09 18:09:40 +00001254 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001255 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001256 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001257 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1258 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001259
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001260 // Consume any end of statement token, if present, to avoid spurious
1261 // AddBlankLine calls().
1262 if (Lexer.is(AsmToken::EndOfStatement)) {
1263 Lex();
1264 if (Lexer.is(AsmToken::Eof))
1265 return false;
1266 }
1267
Eli Friedman2128aae2012-10-22 23:58:19 +00001268 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001269 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001270
Daniel Dunbar3f872332009-07-28 16:08:33 +00001271 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001272 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001273 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001274
Jim Grosbach4a200922013-09-20 23:08:21 +00001275 return parseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001276
1277 default: // Normal instruction or directive.
1278 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001279 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001280
1281 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4a200922013-09-20 23:08:21 +00001282 if (areMacrosEnabled())
1283 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1284 return handleMacroEntry(M, IDLoc);
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001285 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001286
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001287 // Otherwise, we have a normal instruction or directive.
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001288
Eli Bendersky6ee13082013-01-15 22:59:42 +00001289 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001290 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001291 // There are several entities interested in parsing directives:
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001292 //
Eli Bendersky6ee13082013-01-15 22:59:42 +00001293 // 1. The target-specific assembly parser. Some directives are target
1294 // specific or may potentially behave differently on certain targets.
1295 // 2. Asm parser extensions. For example, platform-specific parsers
1296 // (like the ELF parser) register themselves as extensions.
1297 // 3. The generic directive parser implemented by this class. These are
1298 // all the directives that behave in a target and platform independent
1299 // manner, or at least have a default behavior that's shared between
1300 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001301
Eli Bendersky6ee13082013-01-15 22:59:42 +00001302 // First query the target-specific parser. It will return 'true' if it
1303 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001304 if (!getTargetParser().ParseDirective(ID))
1305 return false;
1306
Eli Bendersky6ee13082013-01-15 22:59:42 +00001307 // Next, check the extention directive map to see if any extension has
1308 // registered itself to parse this directive.
Jim Grosbach4a200922013-09-20 23:08:21 +00001309 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1310 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky6ee13082013-01-15 22:59:42 +00001311 if (Handler.first)
1312 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1313
1314 // Finally, if no one else is interested in this directive, it must be
1315 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001316 switch (DirKind) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001317 default:
1318 break;
1319 case DK_SET:
1320 case DK_EQU:
1321 return parseDirectiveSet(IDVal, true);
1322 case DK_EQUIV:
1323 return parseDirectiveSet(IDVal, false);
1324 case DK_ASCII:
1325 return parseDirectiveAscii(IDVal, false);
1326 case DK_ASCIZ:
1327 case DK_STRING:
1328 return parseDirectiveAscii(IDVal, true);
1329 case DK_BYTE:
1330 return parseDirectiveValue(1);
1331 case DK_SHORT:
1332 case DK_VALUE:
1333 case DK_2BYTE:
1334 return parseDirectiveValue(2);
1335 case DK_LONG:
1336 case DK_INT:
1337 case DK_4BYTE:
1338 return parseDirectiveValue(4);
1339 case DK_QUAD:
1340 case DK_8BYTE:
1341 return parseDirectiveValue(8);
1342 case DK_SINGLE:
1343 case DK_FLOAT:
1344 return parseDirectiveRealValue(APFloat::IEEEsingle);
1345 case DK_DOUBLE:
1346 return parseDirectiveRealValue(APFloat::IEEEdouble);
1347 case DK_ALIGN: {
1348 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1349 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1350 }
1351 case DK_ALIGN32: {
1352 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1353 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1354 }
1355 case DK_BALIGN:
1356 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1357 case DK_BALIGNW:
1358 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1359 case DK_BALIGNL:
1360 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1361 case DK_P2ALIGN:
1362 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1363 case DK_P2ALIGNW:
1364 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1365 case DK_P2ALIGNL:
1366 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1367 case DK_ORG:
1368 return parseDirectiveOrg();
1369 case DK_FILL:
1370 return parseDirectiveFill();
1371 case DK_ZERO:
1372 return parseDirectiveZero();
1373 case DK_EXTERN:
1374 eatToEndOfStatement(); // .extern is the default, ignore it.
1375 return false;
1376 case DK_GLOBL:
1377 case DK_GLOBAL:
1378 return parseDirectiveSymbolAttribute(MCSA_Global);
1379 case DK_LAZY_REFERENCE:
1380 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1381 case DK_NO_DEAD_STRIP:
1382 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1383 case DK_SYMBOL_RESOLVER:
1384 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1385 case DK_PRIVATE_EXTERN:
1386 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1387 case DK_REFERENCE:
1388 return parseDirectiveSymbolAttribute(MCSA_Reference);
1389 case DK_WEAK_DEFINITION:
1390 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1391 case DK_WEAK_REFERENCE:
1392 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1393 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1394 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1395 case DK_COMM:
1396 case DK_COMMON:
1397 return parseDirectiveComm(/*IsLocal=*/false);
1398 case DK_LCOMM:
1399 return parseDirectiveComm(/*IsLocal=*/true);
1400 case DK_ABORT:
1401 return parseDirectiveAbort();
1402 case DK_INCLUDE:
1403 return parseDirectiveInclude();
1404 case DK_INCBIN:
1405 return parseDirectiveIncbin();
1406 case DK_CODE16:
1407 case DK_CODE16GCC:
1408 return TokError(Twine(IDVal) + " not supported yet");
1409 case DK_REPT:
1410 return parseDirectiveRept(IDLoc);
1411 case DK_IRP:
1412 return parseDirectiveIrp(IDLoc);
1413 case DK_IRPC:
1414 return parseDirectiveIrpc(IDLoc);
1415 case DK_ENDR:
1416 return parseDirectiveEndr(IDLoc);
1417 case DK_BUNDLE_ALIGN_MODE:
1418 return parseDirectiveBundleAlignMode();
1419 case DK_BUNDLE_LOCK:
1420 return parseDirectiveBundleLock();
1421 case DK_BUNDLE_UNLOCK:
1422 return parseDirectiveBundleUnlock();
1423 case DK_SLEB128:
1424 return parseDirectiveLEB128(true);
1425 case DK_ULEB128:
1426 return parseDirectiveLEB128(false);
1427 case DK_SPACE:
1428 case DK_SKIP:
1429 return parseDirectiveSpace(IDVal);
1430 case DK_FILE:
1431 return parseDirectiveFile(IDLoc);
1432 case DK_LINE:
1433 return parseDirectiveLine();
1434 case DK_LOC:
1435 return parseDirectiveLoc();
1436 case DK_STABS:
1437 return parseDirectiveStabs();
1438 case DK_CFI_SECTIONS:
1439 return parseDirectiveCFISections();
1440 case DK_CFI_STARTPROC:
1441 return parseDirectiveCFIStartProc();
1442 case DK_CFI_ENDPROC:
1443 return parseDirectiveCFIEndProc();
1444 case DK_CFI_DEF_CFA:
1445 return parseDirectiveCFIDefCfa(IDLoc);
1446 case DK_CFI_DEF_CFA_OFFSET:
1447 return parseDirectiveCFIDefCfaOffset();
1448 case DK_CFI_ADJUST_CFA_OFFSET:
1449 return parseDirectiveCFIAdjustCfaOffset();
1450 case DK_CFI_DEF_CFA_REGISTER:
1451 return parseDirectiveCFIDefCfaRegister(IDLoc);
1452 case DK_CFI_OFFSET:
1453 return parseDirectiveCFIOffset(IDLoc);
1454 case DK_CFI_REL_OFFSET:
1455 return parseDirectiveCFIRelOffset(IDLoc);
1456 case DK_CFI_PERSONALITY:
1457 return parseDirectiveCFIPersonalityOrLsda(true);
1458 case DK_CFI_LSDA:
1459 return parseDirectiveCFIPersonalityOrLsda(false);
1460 case DK_CFI_REMEMBER_STATE:
1461 return parseDirectiveCFIRememberState();
1462 case DK_CFI_RESTORE_STATE:
1463 return parseDirectiveCFIRestoreState();
1464 case DK_CFI_SAME_VALUE:
1465 return parseDirectiveCFISameValue(IDLoc);
1466 case DK_CFI_RESTORE:
1467 return parseDirectiveCFIRestore(IDLoc);
1468 case DK_CFI_ESCAPE:
1469 return parseDirectiveCFIEscape();
1470 case DK_CFI_SIGNAL_FRAME:
1471 return parseDirectiveCFISignalFrame();
1472 case DK_CFI_UNDEFINED:
1473 return parseDirectiveCFIUndefined(IDLoc);
1474 case DK_CFI_REGISTER:
1475 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju83ba58e2013-09-26 14:49:40 +00001476 case DK_CFI_WINDOW_SAVE:
1477 return parseDirectiveCFIWindowSave();
Jim Grosbach4a200922013-09-20 23:08:21 +00001478 case DK_MACROS_ON:
1479 case DK_MACROS_OFF:
1480 return parseDirectiveMacrosOnOff(IDVal);
1481 case DK_MACRO:
1482 return parseDirectiveMacro(IDLoc);
1483 case DK_ENDM:
1484 case DK_ENDMACRO:
1485 return parseDirectiveEndMacro(IDVal);
1486 case DK_PURGEM:
1487 return parseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001488 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001489
Jim Grosbach686c0182012-05-01 18:38:27 +00001490 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001491 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001492
Chad Rosier469b1442013-02-12 21:33:51 +00001493 // __asm _emit or __asm __emit
1494 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1495 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4a200922013-09-20 23:08:21 +00001496 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosier469b1442013-02-12 21:33:51 +00001497
1498 // __asm align
1499 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4a200922013-09-20 23:08:21 +00001500 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman2128aae2012-10-22 23:58:19 +00001501
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001502 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001503
Chris Lattnera7f13542010-05-19 23:34:33 +00001504 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001505 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001506 ParseInstructionInfo IInfo(Info.AsmRewrites);
Jim Grosbach4a200922013-09-20 23:08:21 +00001507 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001508 Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001509 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001510
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001511 // Dump the parsed representation, if requested.
1512 if (getShowParsedOperands()) {
1513 SmallString<256> Str;
1514 raw_svector_ostream OS(Str);
1515 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001516 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001517 if (i != 0)
1518 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001519 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001520 }
1521 OS << "]";
1522
Jim Grosbach4a200922013-09-20 23:08:21 +00001523 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001524 }
1525
Kevin Enderby613b7572011-11-01 22:27:22 +00001526 // If we are generating dwarf for assembly source files and the current
1527 // section is the initial text section then generate a .loc directive for
1528 // the instruction.
1529 if (!HadError && getContext().getGenDwarfForAssembly() &&
Peter Collingbournedf39be62013-04-17 21:18:16 +00001530 getContext().getGenDwarfSection() ==
Jim Grosbach4a200922013-09-20 23:08:21 +00001531 getStreamer().getCurrentSection().first) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001532
Eli Benderskyed5df012013-01-16 19:32:36 +00001533 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001534
Eli Benderskyed5df012013-01-16 19:32:36 +00001535 // If we previously parsed a cpp hash file line comment then make sure the
1536 // current Dwarf File is for the CppHashFilename if not then emit the
1537 // Dwarf File table for it and adjust the line number for the .loc.
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001538 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Jim Grosbach4a200922013-09-20 23:08:21 +00001539 getContext().getMCDwarfFiles();
Eli Benderskyed5df012013-01-16 19:32:36 +00001540 if (CppHashFilename.size() != 0) {
1541 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001542 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001543 getStreamer().EmitDwarfFileDirective(
Jim Grosbach4a200922013-09-20 23:08:21 +00001544 getContext().nextGenDwarfFileNumber(), StringRef(),
1545 CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001546
Jim Grosbach4a200922013-09-20 23:08:21 +00001547 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1548 // cache with the different Loc from the call above we save the last
1549 // info we queried here with SrcMgr.FindLineNumber().
1550 unsigned CppHashLocLineNo;
1551 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1552 CppHashLocLineNo = LastQueryLine;
1553 else {
1554 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1555 LastQueryLine = CppHashLocLineNo;
1556 LastQueryIDLoc = CppHashLoc;
1557 LastQueryBuffer = CppHashBuf;
1558 }
1559 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001560 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001561
Jim Grosbach4a200922013-09-20 23:08:21 +00001562 getStreamer().EmitDwarfLocDirective(
1563 getContext().getGenDwarfFileNumber(), Line, 0,
1564 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1565 StringRef());
Kevin Enderby613b7572011-11-01 22:27:22 +00001566 }
1567
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001568 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001569 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001570 unsigned ErrorInfo;
Jim Grosbach4a200922013-09-20 23:08:21 +00001571 HadError = getTargetParser().MatchAndEmitInstruction(
1572 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1573 ParsingInlineAsm);
Chad Rosier84125ca2012-10-13 00:26:04 +00001574 }
Chris Lattner98986712010-01-14 22:21:20 +00001575
Chris Lattnercbf8a982010-09-11 16:18:25 +00001576 // Don't skip the rest of the line, the instruction parser is responsible for
1577 // that.
1578 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001579}
Chris Lattner9a023f72009-06-24 04:43:34 +00001580
Jim Grosbach4a200922013-09-20 23:08:21 +00001581/// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001582/// since they may not be able to be tokenized to get to the end of line token.
Jim Grosbach4a200922013-09-20 23:08:21 +00001583void AsmParser::eatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001584 if (!Lexer.is(AsmToken::EndOfStatement))
1585 Lexer.LexUntilEndOfLine();
Jim Grosbach4a200922013-09-20 23:08:21 +00001586 // Eat EOL.
1587 Lex();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001588}
1589
Jim Grosbach4a200922013-09-20 23:08:21 +00001590/// parseCppHashLineFilenameComment as this:
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001591/// ::= # number "filename"
1592/// or just as a full line comment if it doesn't have a number and a string.
Jim Grosbach4a200922013-09-20 23:08:21 +00001593bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001594 Lex(); // Eat the hash token.
1595
1596 if (getLexer().isNot(AsmToken::Integer)) {
1597 // Consume the line since in cases it is not a well-formed line directive,
1598 // as if were simply a full line comment.
Jim Grosbach4a200922013-09-20 23:08:21 +00001599 eatToEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001600 return false;
1601 }
1602
1603 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001604 Lex();
1605
1606 if (getLexer().isNot(AsmToken::String)) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001607 eatToEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001608 return false;
1609 }
1610
1611 StringRef Filename = getTok().getString();
1612 // Get rid of the enclosing quotes.
Jim Grosbach4a200922013-09-20 23:08:21 +00001613 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001614
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001615 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1616 CppHashLoc = L;
1617 CppHashFilename = Filename;
1618 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001619 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001620
1621 // Ignore any trailing characters, they're just comment.
Jim Grosbach4a200922013-09-20 23:08:21 +00001622 eatToEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001623 return false;
1624}
1625
Jim Grosbach4a200922013-09-20 23:08:21 +00001626/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001627/// for the Filename and LineNo if any in the diagnostic.
1628void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001629 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001630 raw_ostream &OS = errs();
1631
1632 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1633 const SMLoc &DiagLoc = Diag.getLoc();
1634 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1635 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1636
Jim Grosbach4a200922013-09-20 23:08:21 +00001637 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001638 // before printing the message.
1639 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001640 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001641 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1642 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001643 }
1644
Eric Christopher2318ba12012-12-18 00:30:54 +00001645 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001646 // manager changed or buffer changed (like in a nested include) then just
1647 // print the normal diagnostic using its Filename and LineNo.
Jim Grosbach4a200922013-09-20 23:08:21 +00001648 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001649 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001650 if (Parser->SavedDiagHandler)
1651 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1652 else
1653 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001654 return;
1655 }
1656
Eric Christopher2318ba12012-12-18 00:30:54 +00001657 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001658 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1659 // the diagnostic.
Jakub Staszakb06ea252013-09-16 22:03:38 +00001660 const std::string &Filename = Parser->CppHashFilename;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001661
1662 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1663 int CppHashLocLineNo =
1664 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
Jim Grosbach4a200922013-09-20 23:08:21 +00001665 int LineNo =
1666 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001667
Jim Grosbach4a200922013-09-20 23:08:21 +00001668 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1669 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001670 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001671
Benjamin Kramer04a04262011-10-16 10:48:29 +00001672 if (Parser->SavedDiagHandler)
1673 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1674 else
1675 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001676}
1677
Rafael Espindola799aacf2012-08-21 18:29:30 +00001678// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1679// difference being that that function accepts '@' as part of identifiers and
1680// we can't do that. AsmLexer.cpp should probably be changed to handle
1681// '@' as a special case when needed.
1682static bool isIdentifierChar(char c) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001683 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1684 c == '.';
Rafael Espindola799aacf2012-08-21 18:29:30 +00001685}
1686
Rafael Espindola761cb062012-06-03 23:57:14 +00001687bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001688 const MCAsmMacroParameters &Parameters,
Jim Grosbach4a200922013-09-20 23:08:21 +00001689 const MCAsmMacroArguments &A, const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001690 unsigned NParameters = Parameters.size();
1691 if (NParameters != 0 && NParameters != A.size())
1692 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001693
Preston Gurd7b6f2032012-09-19 20:36:12 +00001694 // A macro without parameters is handled differently on Darwin:
1695 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001696 while (!Body.empty()) {
1697 // Scan for the next substitution.
1698 std::size_t End = Body.size(), Pos = 0;
1699 for (; Pos != End; ++Pos) {
1700 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001701 if (!NParameters) {
1702 // This macro has no parameters, look for $0, $1, etc.
1703 if (Body[Pos] != '$' || Pos + 1 == End)
1704 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001705
Rafael Espindola65366442011-06-05 02:43:45 +00001706 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001707 if (Next == '$' || Next == 'n' ||
1708 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola65366442011-06-05 02:43:45 +00001709 break;
1710 } else {
1711 // This macro has parameters, look for \foo, \bar, etc.
1712 if (Body[Pos] == '\\' && Pos + 1 != End)
1713 break;
1714 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001715 }
1716
1717 // Add the prefix.
1718 OS << Body.slice(0, Pos);
1719
1720 // Check if we reached the end.
1721 if (Pos == End)
1722 break;
1723
Rafael Espindola65366442011-06-05 02:43:45 +00001724 if (!NParameters) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001725 switch (Body[Pos + 1]) {
1726 // $$ => $
Rafael Espindola65366442011-06-05 02:43:45 +00001727 case '$':
1728 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001729 break;
1730
Jim Grosbach4a200922013-09-20 23:08:21 +00001731 // $n => number of arguments
Rafael Espindola65366442011-06-05 02:43:45 +00001732 case 'n':
1733 OS << A.size();
1734 break;
1735
Jim Grosbach4a200922013-09-20 23:08:21 +00001736 // $[0-9] => argument
Rafael Espindola65366442011-06-05 02:43:45 +00001737 default: {
1738 // Missing arguments are ignored.
Jim Grosbach4a200922013-09-20 23:08:21 +00001739 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola65366442011-06-05 02:43:45 +00001740 if (Index >= A.size())
1741 break;
1742
1743 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001744 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Jim Grosbach4a200922013-09-20 23:08:21 +00001745 ie = A[Index].end();
1746 it != ie; ++it)
Rafael Espindola65366442011-06-05 02:43:45 +00001747 OS << it->getString();
1748 break;
1749 }
1750 }
1751 Pos += 2;
1752 } else {
1753 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001754 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001755 ++I;
1756
Jim Grosbach4a200922013-09-20 23:08:21 +00001757 const char *Begin = Body.data() + Pos + 1;
1758 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola65366442011-06-05 02:43:45 +00001759 unsigned Index = 0;
1760 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001761 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001762 break;
1763
Preston Gurd7b6f2032012-09-19 20:36:12 +00001764 if (Index == NParameters) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001765 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1766 Pos += 3;
1767 else {
1768 OS << '\\' << Argument;
1769 Pos = I;
1770 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001771 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001772 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Jim Grosbach4a200922013-09-20 23:08:21 +00001773 ie = A[Index].end();
1774 it != ie; ++it)
Preston Gurd7b6f2032012-09-19 20:36:12 +00001775 if (it->getKind() == AsmToken::String)
1776 OS << it->getStringContents();
1777 else
1778 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001779
Preston Gurd7b6f2032012-09-19 20:36:12 +00001780 Pos += 1 + Argument.size();
1781 }
Rafael Espindola65366442011-06-05 02:43:45 +00001782 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001783 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001784 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001785 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001786
Rafael Espindola65366442011-06-05 02:43:45 +00001787 return false;
1788}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001789
Jim Grosbach4a200922013-09-20 23:08:21 +00001790MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1791 SMLoc EL, MemoryBuffer *I)
1792 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1793 ExitLoc(EL) {}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001794
Jim Grosbach4a200922013-09-20 23:08:21 +00001795static bool isOperator(AsmToken::TokenKind kind) {
1796 switch (kind) {
1797 default:
1798 return false;
1799 case AsmToken::Plus:
1800 case AsmToken::Minus:
1801 case AsmToken::Tilde:
1802 case AsmToken::Slash:
1803 case AsmToken::Star:
1804 case AsmToken::Dot:
1805 case AsmToken::Equal:
1806 case AsmToken::EqualEqual:
1807 case AsmToken::Pipe:
1808 case AsmToken::PipePipe:
1809 case AsmToken::Caret:
1810 case AsmToken::Amp:
1811 case AsmToken::AmpAmp:
1812 case AsmToken::Exclaim:
1813 case AsmToken::ExclaimEqual:
1814 case AsmToken::Percent:
1815 case AsmToken::Less:
1816 case AsmToken::LessEqual:
1817 case AsmToken::LessLess:
1818 case AsmToken::LessGreater:
1819 case AsmToken::Greater:
1820 case AsmToken::GreaterEqual:
1821 case AsmToken::GreaterGreater:
1822 return true;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001823 }
1824}
1825
Jim Grosbach4a200922013-09-20 23:08:21 +00001826bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001827 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001828 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001829 unsigned AddTokens = 0;
1830
1831 // gas accepts arguments separated by whitespace, except on Darwin
1832 if (!IsDarwin)
1833 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001834
1835 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001836 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1837 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001838 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001839 }
1840
1841 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1842 // Spaces and commas cannot be mixed to delimit parameters
1843 if (ArgumentDelimiter == AsmToken::Eof)
1844 ArgumentDelimiter = AsmToken::Comma;
1845 else if (ArgumentDelimiter != AsmToken::Comma) {
1846 Lexer.setSkipSpace(true);
1847 return TokError("expected ' ' for macro argument separator");
1848 }
1849 break;
1850 }
1851
1852 if (Lexer.is(AsmToken::Space)) {
1853 Lex(); // Eat spaces
1854
1855 // Spaces can delimit parameters, but could also be part an expression.
1856 // If the token after a space is an operator, add the token and the next
1857 // one into this argument
1858 if (ArgumentDelimiter == AsmToken::Space ||
1859 ArgumentDelimiter == AsmToken::Eof) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001860 if (isOperator(Lexer.getKind())) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001861 // Check to see whether the token is used as an operator,
1862 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001863 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001864 if (*NextChar == ' ')
1865 AddTokens = 2;
1866 }
1867
1868 if (!AddTokens && ParenLevel == 0) {
1869 if (ArgumentDelimiter == AsmToken::Eof &&
Jim Grosbach4a200922013-09-20 23:08:21 +00001870 !isOperator(Lexer.getKind()))
Preston Gurd7b6f2032012-09-19 20:36:12 +00001871 ArgumentDelimiter = AsmToken::Space;
1872 break;
1873 }
1874 }
1875 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001876
Jim Grosbach4a200922013-09-20 23:08:21 +00001877 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001878 // to be able to fill in the remaining default parameter values
1879 if (Lexer.is(AsmToken::EndOfStatement))
1880 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001881
1882 // Adjust the current parentheses level.
1883 if (Lexer.is(AsmToken::LParen))
1884 ++ParenLevel;
1885 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1886 --ParenLevel;
1887
1888 // Append the token to the current argument list.
1889 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001890 if (AddTokens)
1891 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001892 Lex();
1893 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001894
1895 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001896 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001897 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001898 return false;
1899}
1900
1901// Parse the macro instantiation arguments.
Jim Grosbach4a200922013-09-20 23:08:21 +00001902bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001903 MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001904 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001905 // Argument delimiter is initially unknown. It will be set by
Jim Grosbach4a200922013-09-20 23:08:21 +00001906 // parseMacroArgument()
Preston Gurd7b6f2032012-09-19 20:36:12 +00001907 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001908
1909 // Parse two kinds of macro invocations:
1910 // - macros defined without any parameters accept an arbitrary number of them
1911 // - macros defined with parameters accept at most that many of them
1912 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1913 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001914 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001915
Jim Grosbach4a200922013-09-20 23:08:21 +00001916 if (parseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001917 return true;
1918
Preston Gurd6c9176a2012-09-19 20:29:04 +00001919 if (!MA.empty() || !NParameters)
1920 A.push_back(MA);
1921 else if (NParameters) {
1922 if (!M->Parameters[Parameter].second.empty())
1923 A.push_back(M->Parameters[Parameter].second);
1924 }
Jim Grosbach97146442012-07-30 22:44:17 +00001925
Preston Gurd6c9176a2012-09-19 20:29:04 +00001926 // At the end of the statement, fill in remaining arguments that have
1927 // default values. If there aren't any, then the next argument is
1928 // required but missing
1929 if (Lexer.is(AsmToken::EndOfStatement)) {
1930 if (NParameters && Parameter < NParameters - 1) {
1931 if (M->Parameters[Parameter + 1].second.empty())
1932 return TokError("macro argument '" +
1933 Twine(M->Parameters[Parameter + 1].first) +
1934 "' is missing");
1935 else
1936 continue;
1937 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001938 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001939 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001940
1941 if (Lexer.is(AsmToken::Comma))
1942 Lex();
1943 }
1944 return TokError("Too many arguments");
1945}
1946
Jim Grosbach4a200922013-09-20 23:08:21 +00001947const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
1948 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001949 return (I == MacroMap.end()) ? NULL : I->getValue();
1950}
1951
Jim Grosbach4a200922013-09-20 23:08:21 +00001952void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001953 MacroMap[Name] = new MCAsmMacro(Macro);
1954}
1955
Jim Grosbach4a200922013-09-20 23:08:21 +00001956void AsmParser::undefineMacro(StringRef Name) {
1957 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001958 if (I != MacroMap.end()) {
1959 delete I->getValue();
1960 MacroMap.erase(I);
1961 }
1962}
1963
Jim Grosbach4a200922013-09-20 23:08:21 +00001964bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001965 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1966 // this, although we should protect against infinite loops.
1967 if (ActiveMacros.size() == 20)
1968 return TokError("macros cannot be nested more than 20 levels deep");
1969
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001970 MCAsmMacroArguments A;
Jim Grosbach4a200922013-09-20 23:08:21 +00001971 if (parseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001972 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001973
Jim Grosbach97146442012-07-30 22:44:17 +00001974 // Remove any trailing empty arguments. Do this after-the-fact as we have
1975 // to keep empty arguments in the middle of the list or positionality
1976 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001977 while (!A.empty() && A.back().empty())
1978 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001979
Rafael Espindola65366442011-06-05 02:43:45 +00001980 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1981 // to hold the macro body with substitutions.
1982 SmallString<256> Buf;
1983 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001984 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001985
Rafael Espindola8a403d32012-08-08 14:51:03 +00001986 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001987 return true;
1988
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001989 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001990 // instantiation.
1991 OS << ".endmacro\n";
1992
Rafael Espindola65366442011-06-05 02:43:45 +00001993 MemoryBuffer *Instantiation =
Jim Grosbach4a200922013-09-20 23:08:21 +00001994 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001995
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001996 // Create the macro instantiation object and add to the current macro
1997 // instantiation stack.
Jim Grosbach4a200922013-09-20 23:08:21 +00001998 MacroInstantiation *MI = new MacroInstantiation(
1999 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00002000 ActiveMacros.push_back(MI);
2001
2002 // Jump to the macro instantiation and prime the lexer.
2003 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2004 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2005 Lex();
2006
2007 return false;
2008}
2009
Jim Grosbach4a200922013-09-20 23:08:21 +00002010void AsmParser::handleMacroExit() {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00002011 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4a200922013-09-20 23:08:21 +00002012 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00002013 Lex();
2014
2015 // Pop the instantiation entry.
2016 delete ActiveMacros.back();
2017 ActiveMacros.pop_back();
2018}
2019
Jim Grosbach4a200922013-09-20 23:08:21 +00002020static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002021 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00002022 case MCExpr::Binary: {
Jim Grosbach4a200922013-09-20 23:08:21 +00002023 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2024 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002025 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00002026 case MCExpr::Target:
2027 case MCExpr::Constant:
2028 return false;
2029 case MCExpr::SymbolRef: {
Jim Grosbach4a200922013-09-20 23:08:21 +00002030 const MCSymbol &S =
2031 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00002032 if (S.isVariable())
Jim Grosbach4a200922013-09-20 23:08:21 +00002033 return isUsedIn(Sym, S.getVariableValue());
Rafael Espindola8b01c822012-01-28 06:22:14 +00002034 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00002035 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002036 case MCExpr::Unary:
Jim Grosbach4a200922013-09-20 23:08:21 +00002037 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002038 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00002039
2040 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002041}
2042
Jim Grosbach4a200922013-09-20 23:08:21 +00002043bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002044 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002045 // FIXME: Use better location, we should use proper tokens.
2046 SMLoc EqualLoc = Lexer.getLoc();
2047
Daniel Dunbar821e3332009-08-31 08:09:28 +00002048 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002049 if (parseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002050 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002051
Rafael Espindolae71cc862012-01-28 05:57:00 +00002052 // Note: we don't count b as used in "a = b". This is to allow
2053 // a = b
2054 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002055
Daniel Dunbar3f872332009-07-28 16:08:33 +00002056 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002057 return TokError("unexpected token in assignment");
2058
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002059 // Error on assignment to '.'.
2060 if (Name == ".") {
2061 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2062 "(use '.space' or '.org').)"));
2063 }
2064
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002065 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002066 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002067
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002068 // Validate that the LHS is allowed to be a variable (either it has not been
2069 // used as a symbol, or it is an absolute symbol).
2070 MCSymbol *Sym = getContext().LookupSymbol(Name);
2071 if (Sym) {
2072 // Diagnose assignment to a label.
2073 //
2074 // FIXME: Diagnostics. Note the location of the definition as a label.
2075 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Jim Grosbach4a200922013-09-20 23:08:21 +00002076 if (isUsedIn(Sym, Value))
Rafael Espindolae71cc862012-01-28 05:57:00 +00002077 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2078 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002079 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002080 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2081 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002082 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002083 return Error(EqualLoc, "redefinition of '" + Name + "'");
2084 else if (!Sym->isVariable())
2085 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002086 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002087 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
Jim Grosbach4a200922013-09-20 23:08:21 +00002088 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002089
2090 // Don't count these checks as uses.
2091 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002092 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002093 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002094
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002095 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002096
2097 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002098 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002099 if (NoDeadStrip)
2100 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2101
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002102 return false;
2103}
2104
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002105/// parseIdentifier:
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002106/// ::= identifier
2107/// ::= string
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002108bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002109 // The assembler has relaxed rules for accepting identifiers, in particular we
2110 // allow things like '.globl $foo', which would normally be separate
2111 // tokens. At this level, we have already lexed so we cannot (currently)
2112 // handle this as a context dependent token, instead we detect adjacent tokens
2113 // and return the combined identifier.
2114 if (Lexer.is(AsmToken::Dollar)) {
2115 SMLoc DollarLoc = getLexer().getLoc();
2116
2117 // Consume the dollar sign, and check for a following identifier.
2118 Lex();
2119 if (Lexer.isNot(AsmToken::Identifier))
2120 return true;
2121
2122 // We have a '$' followed by an identifier, make sure they are adjacent.
2123 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2124 return true;
2125
2126 // Construct the joined identifier and consume the token.
Jim Grosbach4a200922013-09-20 23:08:21 +00002127 Res =
2128 StringRef(DollarLoc.getPointer(), getTok().getIdentifier().size() + 1);
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002129 Lex();
2130 return false;
2131 }
2132
Jim Grosbach4a200922013-09-20 23:08:21 +00002133 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002134 return true;
2135
Sean Callanan18b83232010-01-19 21:44:56 +00002136 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002137
Sean Callanan79ed1a82010-01-19 20:22:31 +00002138 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002139
2140 return false;
2141}
2142
Jim Grosbach4a200922013-09-20 23:08:21 +00002143/// parseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002144/// ::= .equ identifier ',' expression
2145/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002146/// ::= .set identifier ',' expression
Jim Grosbach4a200922013-09-20 23:08:21 +00002147bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002148 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002149
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002150 if (parseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002151 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002152
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002153 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002154 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002155 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002156
Jim Grosbach4a200922013-09-20 23:08:21 +00002157 return parseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002158}
2159
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002160bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002161 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002162
2163 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002164 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002165 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2166 if (Str[i] != '\\') {
2167 Data += Str[i];
2168 continue;
2169 }
2170
2171 // Recognize escaped characters. Note that this escape semantics currently
2172 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2173 ++i;
2174 if (i == e)
2175 return TokError("unexpected backslash at end of string");
2176
2177 // Recognize octal sequences.
Jim Grosbach4a200922013-09-20 23:08:21 +00002178 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002179 // Consume up to three octal characters.
2180 unsigned Value = Str[i] - '0';
2181
Jim Grosbach4a200922013-09-20 23:08:21 +00002182 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002183 ++i;
2184 Value = Value * 8 + (Str[i] - '0');
2185
Jim Grosbach4a200922013-09-20 23:08:21 +00002186 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002187 ++i;
2188 Value = Value * 8 + (Str[i] - '0');
2189 }
2190 }
2191
2192 if (Value > 255)
2193 return TokError("invalid octal escape sequence (out of range)");
2194
Jim Grosbach4a200922013-09-20 23:08:21 +00002195 Data += (unsigned char)Value;
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002196 continue;
2197 }
2198
2199 // Otherwise recognize individual escapes.
2200 switch (Str[i]) {
2201 default:
2202 // Just reject invalid escape sequences for now.
2203 return TokError("invalid escape sequence (unrecognized character)");
2204
2205 case 'b': Data += '\b'; break;
2206 case 'f': Data += '\f'; break;
2207 case 'n': Data += '\n'; break;
2208 case 'r': Data += '\r'; break;
2209 case 't': Data += '\t'; break;
2210 case '"': Data += '"'; break;
2211 case '\\': Data += '\\'; break;
2212 }
2213 }
2214
2215 return false;
2216}
2217
Jim Grosbach4a200922013-09-20 23:08:21 +00002218/// parseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002219/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4a200922013-09-20 23:08:21 +00002220bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002221 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002222 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002223
Daniel Dunbara0d14262009-06-24 23:30:00 +00002224 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002225 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002226 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002227
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002228 std::string Data;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002229 if (parseEscapedString(Data))
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002230 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002231
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002232 getStreamer().EmitBytes(Data);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002233 if (ZeroTerminated)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002234 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002235
Sean Callanan79ed1a82010-01-19 20:22:31 +00002236 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002237
2238 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002239 break;
2240
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002241 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002242 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002243 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002244 }
2245 }
2246
Sean Callanan79ed1a82010-01-19 20:22:31 +00002247 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002248 return false;
2249}
2250
Jim Grosbach4a200922013-09-20 23:08:21 +00002251/// parseDirectiveValue
Daniel Dunbara0d14262009-06-24 23:30:00 +00002252/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Jim Grosbach4a200922013-09-20 23:08:21 +00002253bool AsmParser::parseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002254 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002255 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002256
Daniel Dunbara0d14262009-06-24 23:30:00 +00002257 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002258 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002259 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002260 if (parseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002261 return true;
2262
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002263 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002264 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2265 assert(Size <= 8 && "Invalid size");
2266 uint64_t IntValue = MCE->getValue();
2267 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2268 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002269 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach254cf032011-06-29 16:05:14 +00002270 } else
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002271 getStreamer().EmitValue(Value, Size);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002272
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002273 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002274 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002275
Daniel Dunbara0d14262009-06-24 23:30:00 +00002276 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002277 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002278 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002279 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002280 }
2281 }
2282
Sean Callanan79ed1a82010-01-19 20:22:31 +00002283 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002284 return false;
2285}
2286
Jim Grosbach4a200922013-09-20 23:08:21 +00002287/// parseDirectiveRealValue
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002288/// ::= (.single | .double) [ expression (, expression)* ]
Jim Grosbach4a200922013-09-20 23:08:21 +00002289bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002290 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002291 checkForValidSection();
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002292
2293 for (;;) {
2294 // We don't truly support arithmetic on floating point expressions, so we
2295 // have to manually parse unary prefixes.
2296 bool IsNeg = false;
2297 if (getLexer().is(AsmToken::Minus)) {
2298 Lex();
2299 IsNeg = true;
2300 } else if (getLexer().is(AsmToken::Plus))
2301 Lex();
2302
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002303 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002304 getLexer().isNot(AsmToken::Real) &&
2305 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002306 return TokError("unexpected token in directive");
2307
2308 // Convert to an APFloat.
2309 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002310 StringRef IDVal = getTok().getString();
2311 if (getLexer().is(AsmToken::Identifier)) {
2312 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2313 Value = APFloat::getInf(Semantics);
2314 else if (!IDVal.compare_lower("nan"))
2315 Value = APFloat::getNaN(Semantics, false, ~0);
2316 else
2317 return TokError("invalid floating point literal");
2318 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Jim Grosbach4a200922013-09-20 23:08:21 +00002319 APFloat::opInvalidOp)
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002320 return TokError("invalid floating point literal");
2321 if (IsNeg)
2322 Value.changeSign();
2323
2324 // Consume the numeric token.
2325 Lex();
2326
2327 // Emit the value as an integer.
2328 APInt AsInt = Value.bitcastToAPInt();
2329 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002330 AsInt.getBitWidth() / 8);
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002331
2332 if (getLexer().is(AsmToken::EndOfStatement))
2333 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002334
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002335 if (getLexer().isNot(AsmToken::Comma))
2336 return TokError("unexpected token in directive");
2337 Lex();
2338 }
2339 }
2340
2341 Lex();
2342 return false;
2343}
2344
Jim Grosbach4a200922013-09-20 23:08:21 +00002345/// parseDirectiveZero
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002346/// ::= .zero expression
Jim Grosbach4a200922013-09-20 23:08:21 +00002347bool AsmParser::parseDirectiveZero() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002348 checkForValidSection();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002349
2350 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002351 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002352 return true;
2353
Rafael Espindolae452b172010-10-05 19:42:57 +00002354 int64_t Val = 0;
2355 if (getLexer().is(AsmToken::Comma)) {
2356 Lex();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002357 if (parseAbsoluteExpression(Val))
Rafael Espindolae452b172010-10-05 19:42:57 +00002358 return true;
2359 }
2360
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002361 if (getLexer().isNot(AsmToken::EndOfStatement))
2362 return TokError("unexpected token in '.zero' directive");
2363
2364 Lex();
2365
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002366 getStreamer().EmitFill(NumBytes, Val);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002367
2368 return false;
2369}
2370
Jim Grosbach4a200922013-09-20 23:08:21 +00002371/// parseDirectiveFill
Roman Divacky9c607102013-09-24 17:44:41 +00002372/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4a200922013-09-20 23:08:21 +00002373bool AsmParser::parseDirectiveFill() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002374 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002375
Daniel Dunbara0d14262009-06-24 23:30:00 +00002376 int64_t NumValues;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002377 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002378 return true;
2379
Roman Divacky9c607102013-09-24 17:44:41 +00002380 int64_t FillSize = 1;
2381 int64_t FillExpr = 0;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002382
Roman Divacky9c607102013-09-24 17:44:41 +00002383 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2384 if (getLexer().isNot(AsmToken::Comma))
2385 return TokError("unexpected token in '.fill' directive");
2386 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002387
Roman Divacky9c607102013-09-24 17:44:41 +00002388 if (parseAbsoluteExpression(FillSize))
2389 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002390
Roman Divacky9c607102013-09-24 17:44:41 +00002391 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2392 if (getLexer().isNot(AsmToken::Comma))
2393 return TokError("unexpected token in '.fill' directive");
2394 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002395
Roman Divacky9c607102013-09-24 17:44:41 +00002396 if (parseAbsoluteExpression(FillExpr))
2397 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002398
Roman Divacky9c607102013-09-24 17:44:41 +00002399 if (getLexer().isNot(AsmToken::EndOfStatement))
2400 return TokError("unexpected token in '.fill' directive");
2401
2402 Lex();
2403 }
2404 }
Daniel Dunbara0d14262009-06-24 23:30:00 +00002405
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002406 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2407 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002408
2409 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002410 getStreamer().EmitIntValue(FillExpr, FillSize);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002411
2412 return false;
2413}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002414
Jim Grosbach4a200922013-09-20 23:08:21 +00002415/// parseDirectiveOrg
Daniel Dunbarc238b582009-06-25 22:44:51 +00002416/// ::= .org expression [ , expression ]
Jim Grosbach4a200922013-09-20 23:08:21 +00002417bool AsmParser::parseDirectiveOrg() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002418 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002419
Daniel Dunbar821e3332009-08-31 08:09:28 +00002420 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002421 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002422 if (parseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002423 return true;
2424
2425 // Parse optional fill expression.
2426 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002427 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2428 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002429 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002430 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002431
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002432 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002433 return true;
2434
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002435 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002436 return TokError("unexpected token in '.org' directive");
2437 }
2438
Sean Callanan79ed1a82010-01-19 20:22:31 +00002439 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002440
Jim Grosbachebd4c052012-01-27 00:37:08 +00002441 // Only limited forms of relocatable expressions are accepted here, it
2442 // has to be relative to the current section. The streamer will return
2443 // 'true' if the expression wasn't evaluatable.
2444 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2445 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002446
2447 return false;
2448}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002449
Jim Grosbach4a200922013-09-20 23:08:21 +00002450/// parseDirectiveAlign
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002451/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4a200922013-09-20 23:08:21 +00002452bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002453 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002454
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002455 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002456 int64_t Alignment;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002457 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002458 return true;
2459
2460 SMLoc MaxBytesLoc;
2461 bool HasFillExpr = false;
2462 int64_t FillExpr = 0;
2463 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002464 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2465 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002466 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002467 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002468
2469 // The fill expression can be omitted while specifying a maximum number of
2470 // alignment bytes, e.g:
2471 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002472 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002473 HasFillExpr = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002474 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002475 return true;
2476 }
2477
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002478 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2479 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002480 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002481 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002482
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002483 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002484 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002485 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002486
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002487 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002488 return TokError("unexpected token in directive");
2489 }
2490 }
2491
Sean Callanan79ed1a82010-01-19 20:22:31 +00002492 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002493
Daniel Dunbar648ac512010-05-17 21:54:30 +00002494 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002495 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002496
2497 // Compute alignment in bytes.
2498 if (IsPow2) {
2499 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002500 if (Alignment >= 32) {
2501 Error(AlignmentLoc, "invalid alignment value");
2502 Alignment = 31;
2503 }
2504
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002505 Alignment = 1ULL << Alignment;
Benjamin Kramer8a89cf22013-02-16 15:00:16 +00002506 } else {
2507 // Reject alignments that aren't a power of two, for gas compatibility.
2508 if (!isPowerOf2_64(Alignment))
2509 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002510 }
2511
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002512 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002513 if (MaxBytesLoc.isValid()) {
2514 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002515 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
Jim Grosbach4a200922013-09-20 23:08:21 +00002516 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002517 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002518 }
2519
2520 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002521 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4a200922013-09-20 23:08:21 +00002522 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002523 MaxBytesToFill = 0;
2524 }
2525 }
2526
Daniel Dunbar648ac512010-05-17 21:54:30 +00002527 // Check whether we should use optimal code alignment for this .align
2528 // directive.
Peter Collingbournedf39be62013-04-17 21:18:16 +00002529 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002530 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2531 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002532 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002533 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002534 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002535 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2536 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002537 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002538
2539 return false;
2540}
2541
Jim Grosbach4a200922013-09-20 23:08:21 +00002542/// parseDirectiveFile
Eli Bendersky6ee13082013-01-15 22:59:42 +00002543/// ::= .file [number] filename
2544/// ::= .file number directory filename
Jim Grosbach4a200922013-09-20 23:08:21 +00002545bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002546 // FIXME: I'm not sure what this is.
2547 int64_t FileNumber = -1;
2548 SMLoc FileNumberLoc = getLexer().getLoc();
2549 if (getLexer().is(AsmToken::Integer)) {
2550 FileNumber = getTok().getIntVal();
2551 Lex();
2552
2553 if (FileNumber < 1)
2554 return TokError("file number less than one");
2555 }
2556
2557 if (getLexer().isNot(AsmToken::String))
2558 return TokError("unexpected token in '.file' directive");
2559
2560 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gaoed119822013-09-05 19:14:26 +00002561 // Allow the strings to have escaped octal character sequence.
2562 std::string Path = getTok().getString();
2563 if (parseEscapedString(Path))
2564 return true;
Eli Bendersky6ee13082013-01-15 22:59:42 +00002565 Lex();
2566
2567 StringRef Directory;
2568 StringRef Filename;
Yunzhong Gaoed119822013-09-05 19:14:26 +00002569 std::string FilenameData;
Eli Bendersky6ee13082013-01-15 22:59:42 +00002570 if (getLexer().is(AsmToken::String)) {
2571 if (FileNumber == -1)
2572 return TokError("explicit path specified, but no file number");
Yunzhong Gaoed119822013-09-05 19:14:26 +00002573 if (parseEscapedString(FilenameData))
2574 return true;
2575 Filename = FilenameData;
Eli Bendersky6ee13082013-01-15 22:59:42 +00002576 Directory = Path;
2577 Lex();
2578 } else {
2579 Filename = Path;
2580 }
2581
2582 if (getLexer().isNot(AsmToken::EndOfStatement))
2583 return TokError("unexpected token in '.file' directive");
2584
2585 if (FileNumber == -1)
2586 getStreamer().EmitFileDirective(Filename);
2587 else {
2588 if (getContext().getGenDwarfForAssembly() == true)
Jim Grosbach4a200922013-09-20 23:08:21 +00002589 Error(DirectiveLoc,
2590 "input can't have .file dwarf directives when -g is "
2591 "used to generate dwarf debug info for assembly code");
Eli Bendersky6ee13082013-01-15 22:59:42 +00002592
2593 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2594 Error(FileNumberLoc, "file number already allocated");
2595 }
2596
2597 return false;
2598}
2599
Jim Grosbach4a200922013-09-20 23:08:21 +00002600/// parseDirectiveLine
Eli Bendersky6ee13082013-01-15 22:59:42 +00002601/// ::= .line [number]
Jim Grosbach4a200922013-09-20 23:08:21 +00002602bool AsmParser::parseDirectiveLine() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002603 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2604 if (getLexer().isNot(AsmToken::Integer))
2605 return TokError("unexpected token in '.line' directive");
2606
2607 int64_t LineNumber = getTok().getIntVal();
Jim Grosbach4a200922013-09-20 23:08:21 +00002608 (void)LineNumber;
Eli Bendersky6ee13082013-01-15 22:59:42 +00002609 Lex();
2610
2611 // FIXME: Do something with the .line.
2612 }
2613
2614 if (getLexer().isNot(AsmToken::EndOfStatement))
2615 return TokError("unexpected token in '.line' directive");
2616
2617 return false;
2618}
2619
Jim Grosbach4a200922013-09-20 23:08:21 +00002620/// parseDirectiveLoc
Eli Bendersky6ee13082013-01-15 22:59:42 +00002621/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2622/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2623/// The first number is a file number, must have been previously assigned with
2624/// a .file directive, the second number is the line number and optionally the
2625/// third number is a column position (zero if not specified). The remaining
2626/// optional items are .loc sub-directives.
Jim Grosbach4a200922013-09-20 23:08:21 +00002627bool AsmParser::parseDirectiveLoc() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002628 if (getLexer().isNot(AsmToken::Integer))
2629 return TokError("unexpected token in '.loc' directive");
2630 int64_t FileNumber = getTok().getIntVal();
2631 if (FileNumber < 1)
2632 return TokError("file number less than one in '.loc' directive");
2633 if (!getContext().isValidDwarfFileNumber(FileNumber))
2634 return TokError("unassigned file number in '.loc' directive");
2635 Lex();
2636
2637 int64_t LineNumber = 0;
2638 if (getLexer().is(AsmToken::Integer)) {
2639 LineNumber = getTok().getIntVal();
Adrian Prantldeac1372013-09-26 23:37:11 +00002640 if (LineNumber < 0)
2641 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky6ee13082013-01-15 22:59:42 +00002642 Lex();
2643 }
2644
2645 int64_t ColumnPos = 0;
2646 if (getLexer().is(AsmToken::Integer)) {
2647 ColumnPos = getTok().getIntVal();
2648 if (ColumnPos < 0)
2649 return TokError("column position less than zero in '.loc' directive");
2650 Lex();
2651 }
2652
2653 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2654 unsigned Isa = 0;
2655 int64_t Discriminator = 0;
2656 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2657 for (;;) {
2658 if (getLexer().is(AsmToken::EndOfStatement))
2659 break;
2660
2661 StringRef Name;
2662 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002663 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002664 return TokError("unexpected token in '.loc' directive");
2665
2666 if (Name == "basic_block")
2667 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2668 else if (Name == "prologue_end")
2669 Flags |= DWARF2_FLAG_PROLOGUE_END;
2670 else if (Name == "epilogue_begin")
2671 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2672 else if (Name == "is_stmt") {
2673 Loc = getTok().getLoc();
2674 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002675 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002676 return true;
2677 // The expression must be the constant 0 or 1.
2678 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2679 int Value = MCE->getValue();
2680 if (Value == 0)
2681 Flags &= ~DWARF2_FLAG_IS_STMT;
2682 else if (Value == 1)
2683 Flags |= DWARF2_FLAG_IS_STMT;
2684 else
2685 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperefa703d2013-04-22 04:22:40 +00002686 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002687 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2688 }
Craig Topperefa703d2013-04-22 04:22:40 +00002689 } else if (Name == "isa") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002690 Loc = getTok().getLoc();
2691 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002692 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002693 return true;
2694 // The expression must be a constant greater or equal to 0.
2695 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2696 int Value = MCE->getValue();
2697 if (Value < 0)
2698 return Error(Loc, "isa number less than zero");
2699 Isa = Value;
Craig Topperefa703d2013-04-22 04:22:40 +00002700 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002701 return Error(Loc, "isa number not a constant value");
2702 }
Craig Topperefa703d2013-04-22 04:22:40 +00002703 } else if (Name == "discriminator") {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002704 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002705 return true;
Craig Topperefa703d2013-04-22 04:22:40 +00002706 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002707 return Error(Loc, "unknown sub-directive in '.loc' directive");
2708 }
2709
2710 if (getLexer().is(AsmToken::EndOfStatement))
2711 break;
2712 }
2713 }
2714
2715 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2716 Isa, Discriminator, StringRef());
2717
2718 return false;
2719}
2720
Jim Grosbach4a200922013-09-20 23:08:21 +00002721/// parseDirectiveStabs
Eli Bendersky6ee13082013-01-15 22:59:42 +00002722/// ::= .stabs string, number, number, number
Jim Grosbach4a200922013-09-20 23:08:21 +00002723bool AsmParser::parseDirectiveStabs() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002724 return TokError("unsupported directive '.stabs'");
2725}
2726
Jim Grosbach4a200922013-09-20 23:08:21 +00002727/// parseDirectiveCFISections
Eli Bendersky6ee13082013-01-15 22:59:42 +00002728/// ::= .cfi_sections section [, section]
Jim Grosbach4a200922013-09-20 23:08:21 +00002729bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002730 StringRef Name;
2731 bool EH = false;
2732 bool Debug = false;
2733
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002734 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002735 return TokError("Expected an identifier");
2736
2737 if (Name == ".eh_frame")
2738 EH = true;
2739 else if (Name == ".debug_frame")
2740 Debug = true;
2741
2742 if (getLexer().is(AsmToken::Comma)) {
2743 Lex();
2744
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002745 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002746 return TokError("Expected an identifier");
2747
2748 if (Name == ".eh_frame")
2749 EH = true;
2750 else if (Name == ".debug_frame")
2751 Debug = true;
2752 }
2753
2754 getStreamer().EmitCFISections(EH, Debug);
2755 return false;
2756}
2757
Jim Grosbach4a200922013-09-20 23:08:21 +00002758/// parseDirectiveCFIStartProc
Eli Bendersky6ee13082013-01-15 22:59:42 +00002759/// ::= .cfi_startproc
Jim Grosbach4a200922013-09-20 23:08:21 +00002760bool AsmParser::parseDirectiveCFIStartProc() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002761 getStreamer().EmitCFIStartProc();
2762 return false;
2763}
2764
Jim Grosbach4a200922013-09-20 23:08:21 +00002765/// parseDirectiveCFIEndProc
Eli Bendersky6ee13082013-01-15 22:59:42 +00002766/// ::= .cfi_endproc
Jim Grosbach4a200922013-09-20 23:08:21 +00002767bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002768 getStreamer().EmitCFIEndProc();
2769 return false;
2770}
2771
Jim Grosbach4a200922013-09-20 23:08:21 +00002772/// \brief parse register name or number.
2773bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky6ee13082013-01-15 22:59:42 +00002774 SMLoc DirectiveLoc) {
2775 unsigned RegNo;
2776
2777 if (getLexer().isNot(AsmToken::Integer)) {
2778 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2779 return true;
Bill Wendling99cb6222013-06-18 07:20:20 +00002780 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002781 } else
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002782 return parseAbsoluteExpression(Register);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002783
2784 return false;
2785}
2786
Jim Grosbach4a200922013-09-20 23:08:21 +00002787/// parseDirectiveCFIDefCfa
Eli Bendersky6ee13082013-01-15 22:59:42 +00002788/// ::= .cfi_def_cfa register, offset
Jim Grosbach4a200922013-09-20 23:08:21 +00002789bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002790 int64_t Register = 0;
Jim Grosbach4a200922013-09-20 23:08:21 +00002791 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002792 return true;
2793
2794 if (getLexer().isNot(AsmToken::Comma))
2795 return TokError("unexpected token in directive");
2796 Lex();
2797
2798 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002799 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002800 return true;
2801
2802 getStreamer().EmitCFIDefCfa(Register, Offset);
2803 return false;
2804}
2805
Jim Grosbach4a200922013-09-20 23:08:21 +00002806/// parseDirectiveCFIDefCfaOffset
Eli Bendersky6ee13082013-01-15 22:59:42 +00002807/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4a200922013-09-20 23:08:21 +00002808bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002809 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002810 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002811 return true;
2812
2813 getStreamer().EmitCFIDefCfaOffset(Offset);
2814 return false;
2815}
2816
Jim Grosbach4a200922013-09-20 23:08:21 +00002817/// parseDirectiveCFIRegister
Eli Bendersky6ee13082013-01-15 22:59:42 +00002818/// ::= .cfi_register register, register
Jim Grosbach4a200922013-09-20 23:08:21 +00002819bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002820 int64_t Register1 = 0;
Jim Grosbach4a200922013-09-20 23:08:21 +00002821 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002822 return true;
2823
2824 if (getLexer().isNot(AsmToken::Comma))
2825 return TokError("unexpected token in directive");
2826 Lex();
2827
2828 int64_t Register2 = 0;
Jim Grosbach4a200922013-09-20 23:08:21 +00002829 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002830 return true;
2831
2832 getStreamer().EmitCFIRegister(Register1, Register2);
2833 return false;
2834}
2835
Venkatraman Govindaraju83ba58e2013-09-26 14:49:40 +00002836/// parseDirectiveCFIWindowSave
2837/// ::= .cfi_window_save
2838bool AsmParser::parseDirectiveCFIWindowSave() {
2839 getStreamer().EmitCFIWindowSave();
2840 return false;
2841}
2842
Jim Grosbach4a200922013-09-20 23:08:21 +00002843/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky6ee13082013-01-15 22:59:42 +00002844/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4a200922013-09-20 23:08:21 +00002845bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002846 int64_t Adjustment = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002847 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002848 return true;
2849
2850 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2851 return false;
2852}
2853
Jim Grosbach4a200922013-09-20 23:08:21 +00002854/// parseDirectiveCFIDefCfaRegister
Eli Bendersky6ee13082013-01-15 22:59:42 +00002855/// ::= .cfi_def_cfa_register register
Jim Grosbach4a200922013-09-20 23:08:21 +00002856bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002857 int64_t Register = 0;
Jim Grosbach4a200922013-09-20 23:08:21 +00002858 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002859 return true;
2860
2861 getStreamer().EmitCFIDefCfaRegister(Register);
2862 return false;
2863}
2864
Jim Grosbach4a200922013-09-20 23:08:21 +00002865/// parseDirectiveCFIOffset
Eli Bendersky6ee13082013-01-15 22:59:42 +00002866/// ::= .cfi_offset register, offset
Jim Grosbach4a200922013-09-20 23:08:21 +00002867bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002868 int64_t Register = 0;
2869 int64_t Offset = 0;
2870
Jim Grosbach4a200922013-09-20 23:08:21 +00002871 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002872 return true;
2873
2874 if (getLexer().isNot(AsmToken::Comma))
2875 return TokError("unexpected token in directive");
2876 Lex();
2877
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002878 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002879 return true;
2880
2881 getStreamer().EmitCFIOffset(Register, Offset);
2882 return false;
2883}
2884
Jim Grosbach4a200922013-09-20 23:08:21 +00002885/// parseDirectiveCFIRelOffset
Eli Bendersky6ee13082013-01-15 22:59:42 +00002886/// ::= .cfi_rel_offset register, offset
Jim Grosbach4a200922013-09-20 23:08:21 +00002887bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002888 int64_t Register = 0;
2889
Jim Grosbach4a200922013-09-20 23:08:21 +00002890 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002891 return true;
2892
2893 if (getLexer().isNot(AsmToken::Comma))
2894 return TokError("unexpected token in directive");
2895 Lex();
2896
2897 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002898 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002899 return true;
2900
2901 getStreamer().EmitCFIRelOffset(Register, Offset);
2902 return false;
2903}
2904
2905static bool isValidEncoding(int64_t Encoding) {
2906 if (Encoding & ~0xff)
2907 return false;
2908
2909 if (Encoding == dwarf::DW_EH_PE_omit)
2910 return true;
2911
2912 const unsigned Format = Encoding & 0xf;
2913 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2914 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2915 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2916 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2917 return false;
2918
2919 const unsigned Application = Encoding & 0x70;
2920 if (Application != dwarf::DW_EH_PE_absptr &&
2921 Application != dwarf::DW_EH_PE_pcrel)
2922 return false;
2923
2924 return true;
2925}
2926
Jim Grosbach4a200922013-09-20 23:08:21 +00002927/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky6ee13082013-01-15 22:59:42 +00002928/// IsPersonality true for cfi_personality, false for cfi_lsda
2929/// ::= .cfi_personality encoding, [symbol_name]
2930/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4a200922013-09-20 23:08:21 +00002931bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002932 int64_t Encoding = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002933 if (parseAbsoluteExpression(Encoding))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002934 return true;
2935 if (Encoding == dwarf::DW_EH_PE_omit)
2936 return false;
2937
2938 if (!isValidEncoding(Encoding))
2939 return TokError("unsupported encoding.");
2940
2941 if (getLexer().isNot(AsmToken::Comma))
2942 return TokError("unexpected token in directive");
2943 Lex();
2944
2945 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002946 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002947 return TokError("expected identifier in directive");
2948
2949 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2950
2951 if (IsPersonality)
2952 getStreamer().EmitCFIPersonality(Sym, Encoding);
2953 else
2954 getStreamer().EmitCFILsda(Sym, Encoding);
2955 return false;
2956}
2957
Jim Grosbach4a200922013-09-20 23:08:21 +00002958/// parseDirectiveCFIRememberState
Eli Bendersky6ee13082013-01-15 22:59:42 +00002959/// ::= .cfi_remember_state
Jim Grosbach4a200922013-09-20 23:08:21 +00002960bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002961 getStreamer().EmitCFIRememberState();
2962 return false;
2963}
2964
Jim Grosbach4a200922013-09-20 23:08:21 +00002965/// parseDirectiveCFIRestoreState
Eli Bendersky6ee13082013-01-15 22:59:42 +00002966/// ::= .cfi_remember_state
Jim Grosbach4a200922013-09-20 23:08:21 +00002967bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002968 getStreamer().EmitCFIRestoreState();
2969 return false;
2970}
2971
Jim Grosbach4a200922013-09-20 23:08:21 +00002972/// parseDirectiveCFISameValue
Eli Bendersky6ee13082013-01-15 22:59:42 +00002973/// ::= .cfi_same_value register
Jim Grosbach4a200922013-09-20 23:08:21 +00002974bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002975 int64_t Register = 0;
2976
Jim Grosbach4a200922013-09-20 23:08:21 +00002977 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002978 return true;
2979
2980 getStreamer().EmitCFISameValue(Register);
2981 return false;
2982}
2983
Jim Grosbach4a200922013-09-20 23:08:21 +00002984/// parseDirectiveCFIRestore
Eli Bendersky6ee13082013-01-15 22:59:42 +00002985/// ::= .cfi_restore register
Jim Grosbach4a200922013-09-20 23:08:21 +00002986bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002987 int64_t Register = 0;
Jim Grosbach4a200922013-09-20 23:08:21 +00002988 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002989 return true;
2990
2991 getStreamer().EmitCFIRestore(Register);
2992 return false;
2993}
2994
Jim Grosbach4a200922013-09-20 23:08:21 +00002995/// parseDirectiveCFIEscape
Eli Bendersky6ee13082013-01-15 22:59:42 +00002996/// ::= .cfi_escape expression[,...]
Jim Grosbach4a200922013-09-20 23:08:21 +00002997bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002998 std::string Values;
2999 int64_t CurrValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003000 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003001 return true;
3002
3003 Values.push_back((uint8_t)CurrValue);
3004
3005 while (getLexer().is(AsmToken::Comma)) {
3006 Lex();
3007
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003008 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003009 return true;
3010
3011 Values.push_back((uint8_t)CurrValue);
3012 }
3013
3014 getStreamer().EmitCFIEscape(Values);
3015 return false;
3016}
3017
Jim Grosbach4a200922013-09-20 23:08:21 +00003018/// parseDirectiveCFISignalFrame
Eli Bendersky6ee13082013-01-15 22:59:42 +00003019/// ::= .cfi_signal_frame
Jim Grosbach4a200922013-09-20 23:08:21 +00003020bool AsmParser::parseDirectiveCFISignalFrame() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00003021 if (getLexer().isNot(AsmToken::EndOfStatement))
3022 return Error(getLexer().getLoc(),
3023 "unexpected token in '.cfi_signal_frame'");
3024
3025 getStreamer().EmitCFISignalFrame();
3026 return false;
3027}
3028
Jim Grosbach4a200922013-09-20 23:08:21 +00003029/// parseDirectiveCFIUndefined
Eli Bendersky6ee13082013-01-15 22:59:42 +00003030/// ::= .cfi_undefined register
Jim Grosbach4a200922013-09-20 23:08:21 +00003031bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00003032 int64_t Register = 0;
3033
Jim Grosbach4a200922013-09-20 23:08:21 +00003034 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003035 return true;
3036
3037 getStreamer().EmitCFIUndefined(Register);
3038 return false;
3039}
3040
Jim Grosbach4a200922013-09-20 23:08:21 +00003041/// parseDirectiveMacrosOnOff
Eli Bendersky6ee13082013-01-15 22:59:42 +00003042/// ::= .macros_on
3043/// ::= .macros_off
Jim Grosbach4a200922013-09-20 23:08:21 +00003044bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00003045 if (getLexer().isNot(AsmToken::EndOfStatement))
3046 return Error(getLexer().getLoc(),
3047 "unexpected token in '" + Directive + "' directive");
3048
Jim Grosbach4a200922013-09-20 23:08:21 +00003049 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky6ee13082013-01-15 22:59:42 +00003050 return false;
3051}
3052
Jim Grosbach4a200922013-09-20 23:08:21 +00003053/// parseDirectiveMacro
Eli Bendersky6ee13082013-01-15 22:59:42 +00003054/// ::= .macro name [parameters]
Jim Grosbach4a200922013-09-20 23:08:21 +00003055bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00003056 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003057 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003058 return TokError("expected identifier in '.macro' directive");
3059
3060 MCAsmMacroParameters Parameters;
3061 // Argument delimiter is initially unknown. It will be set by
Jim Grosbach4a200922013-09-20 23:08:21 +00003062 // parseMacroArgument()
Eli Bendersky6ee13082013-01-15 22:59:42 +00003063 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3064 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3065 for (;;) {
3066 MCAsmMacroParameter Parameter;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003067 if (parseIdentifier(Parameter.first))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003068 return TokError("expected identifier in '.macro' directive");
3069
3070 if (getLexer().is(AsmToken::Equal)) {
3071 Lex();
Jim Grosbach4a200922013-09-20 23:08:21 +00003072 if (parseMacroArgument(Parameter.second, ArgumentDelimiter))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003073 return true;
3074 }
3075
3076 Parameters.push_back(Parameter);
3077
3078 if (getLexer().is(AsmToken::Comma))
3079 Lex();
3080 else if (getLexer().is(AsmToken::EndOfStatement))
3081 break;
3082 }
3083 }
3084
3085 // Eat the end of statement.
3086 Lex();
3087
3088 AsmToken EndToken, StartToken = getTok();
3089
3090 // Lex the macro definition.
3091 for (;;) {
3092 // Check whether we have reached the end of the file.
3093 if (getLexer().is(AsmToken::Eof))
3094 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3095
3096 // Otherwise, check whether we have reach the .endmacro.
3097 if (getLexer().is(AsmToken::Identifier) &&
3098 (getTok().getIdentifier() == ".endm" ||
3099 getTok().getIdentifier() == ".endmacro")) {
3100 EndToken = getTok();
3101 Lex();
3102 if (getLexer().isNot(AsmToken::EndOfStatement))
3103 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3104 "' directive");
3105 break;
3106 }
3107
3108 // Otherwise, scan til the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003109 eatToEndOfStatement();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003110 }
3111
Jim Grosbach4a200922013-09-20 23:08:21 +00003112 if (lookupMacro(Name)) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00003113 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3114 }
3115
3116 const char *BodyStart = StartToken.getLoc().getPointer();
3117 const char *BodyEnd = EndToken.getLoc().getPointer();
3118 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4a200922013-09-20 23:08:21 +00003119 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3120 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
Eli Bendersky6ee13082013-01-15 22:59:42 +00003121 return false;
3122}
3123
Jim Grosbach4a200922013-09-20 23:08:21 +00003124/// checkForBadMacro
Kevin Enderby221514e2013-01-22 21:44:53 +00003125///
3126/// With the support added for named parameters there may be code out there that
3127/// is transitioning from positional parameters. In versions of gas that did
3128/// not support named parameters they would be ignored on the macro defintion.
3129/// But to support both styles of parameters this is not possible so if a macro
3130/// defintion has named parameters but does not use them and has what appears
3131/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3132/// warning that the positional parameter found in body which have no effect.
3133/// Hoping the developer will either remove the named parameters from the macro
3134/// definiton so the positional parameters get used if that was what was
3135/// intended or change the macro to use the named parameters. It is possible
3136/// this warning will trigger when the none of the named parameters are used
3137/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4a200922013-09-20 23:08:21 +00003138void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby221514e2013-01-22 21:44:53 +00003139 StringRef Body,
3140 MCAsmMacroParameters Parameters) {
3141 // If this macro is not defined with named parameters the warning we are
3142 // checking for here doesn't apply.
3143 unsigned NParameters = Parameters.size();
3144 if (NParameters == 0)
3145 return;
3146
3147 bool NamedParametersFound = false;
3148 bool PositionalParametersFound = false;
3149
3150 // Look at the body of the macro for use of both the named parameters and what
3151 // are likely to be positional parameters. This is what expandMacro() is
3152 // doing when it finds the parameters in the body.
3153 while (!Body.empty()) {
3154 // Scan for the next possible parameter.
3155 std::size_t End = Body.size(), Pos = 0;
3156 for (; Pos != End; ++Pos) {
3157 // Check for a substitution or escape.
3158 // This macro is defined with parameters, look for \foo, \bar, etc.
3159 if (Body[Pos] == '\\' && Pos + 1 != End)
3160 break;
3161
3162 // This macro should have parameters, but look for $0, $1, ..., $n too.
3163 if (Body[Pos] != '$' || Pos + 1 == End)
3164 continue;
3165 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00003166 if (Next == '$' || Next == 'n' ||
3167 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby221514e2013-01-22 21:44:53 +00003168 break;
3169 }
3170
3171 // Check if we reached the end.
3172 if (Pos == End)
3173 break;
3174
3175 if (Body[Pos] == '$') {
Jim Grosbach4a200922013-09-20 23:08:21 +00003176 switch (Body[Pos + 1]) {
3177 // $$ => $
Kevin Enderby221514e2013-01-22 21:44:53 +00003178 case '$':
3179 break;
3180
Jim Grosbach4a200922013-09-20 23:08:21 +00003181 // $n => number of arguments
Kevin Enderby221514e2013-01-22 21:44:53 +00003182 case 'n':
3183 PositionalParametersFound = true;
3184 break;
3185
Jim Grosbach4a200922013-09-20 23:08:21 +00003186 // $[0-9] => argument
Kevin Enderby221514e2013-01-22 21:44:53 +00003187 default: {
3188 PositionalParametersFound = true;
3189 break;
Jim Grosbach4a200922013-09-20 23:08:21 +00003190 }
Kevin Enderby221514e2013-01-22 21:44:53 +00003191 }
3192 Pos += 2;
3193 } else {
3194 unsigned I = Pos + 1;
3195 while (isIdentifierChar(Body[I]) && I + 1 != End)
3196 ++I;
3197
Jim Grosbach4a200922013-09-20 23:08:21 +00003198 const char *Begin = Body.data() + Pos + 1;
3199 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby221514e2013-01-22 21:44:53 +00003200 unsigned Index = 0;
3201 for (; Index < NParameters; ++Index)
3202 if (Parameters[Index].first == Argument)
3203 break;
3204
3205 if (Index == NParameters) {
Jim Grosbach4a200922013-09-20 23:08:21 +00003206 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3207 Pos += 3;
3208 else {
3209 Pos = I;
3210 }
Kevin Enderby221514e2013-01-22 21:44:53 +00003211 } else {
3212 NamedParametersFound = true;
3213 Pos += 1 + Argument.size();
3214 }
3215 }
3216 // Update the scan point.
3217 Body = Body.substr(Pos);
3218 }
3219
3220 if (!NamedParametersFound && PositionalParametersFound)
3221 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3222 "used in macro body, possible positional parameter "
3223 "found in body which will have no effect");
3224}
3225
Jim Grosbach4a200922013-09-20 23:08:21 +00003226/// parseDirectiveEndMacro
Eli Bendersky6ee13082013-01-15 22:59:42 +00003227/// ::= .endm
3228/// ::= .endmacro
Jim Grosbach4a200922013-09-20 23:08:21 +00003229bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00003230 if (getLexer().isNot(AsmToken::EndOfStatement))
3231 return TokError("unexpected token in '" + Directive + "' directive");
3232
3233 // If we are inside a macro instantiation, terminate the current
3234 // instantiation.
Jim Grosbach4a200922013-09-20 23:08:21 +00003235 if (isInsideMacroInstantiation()) {
3236 handleMacroExit();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003237 return false;
3238 }
3239
3240 // Otherwise, this .endmacro is a stray entry in the file; well formed
3241 // .endmacro directives are handled during the macro definition parsing.
3242 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4a200922013-09-20 23:08:21 +00003243 "no current macro definition");
Eli Bendersky6ee13082013-01-15 22:59:42 +00003244}
3245
Jim Grosbach4a200922013-09-20 23:08:21 +00003246/// parseDirectivePurgeMacro
Eli Bendersky6ee13082013-01-15 22:59:42 +00003247/// ::= .purgem
Jim Grosbach4a200922013-09-20 23:08:21 +00003248bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00003249 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003250 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003251 return TokError("expected identifier in '.purgem' directive");
3252
3253 if (getLexer().isNot(AsmToken::EndOfStatement))
3254 return TokError("unexpected token in '.purgem' directive");
3255
Jim Grosbach4a200922013-09-20 23:08:21 +00003256 if (!lookupMacro(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003257 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3258
Jim Grosbach4a200922013-09-20 23:08:21 +00003259 undefineMacro(Name);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003260 return false;
3261}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003262
Jim Grosbach4a200922013-09-20 23:08:21 +00003263/// parseDirectiveBundleAlignMode
Eli Bendersky4766ef42012-12-20 19:05:53 +00003264/// ::= {.bundle_align_mode} expression
Jim Grosbach4a200922013-09-20 23:08:21 +00003265bool AsmParser::parseDirectiveBundleAlignMode() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003266 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003267
3268 // Expect a single argument: an expression that evaluates to a constant
3269 // in the inclusive range 0-30.
3270 SMLoc ExprLoc = getLexer().getLoc();
3271 int64_t AlignSizePow2;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003272 if (parseAbsoluteExpression(AlignSizePow2))
Eli Bendersky4766ef42012-12-20 19:05:53 +00003273 return true;
3274 else if (getLexer().isNot(AsmToken::EndOfStatement))
3275 return TokError("unexpected token after expression in"
3276 " '.bundle_align_mode' directive");
3277 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3278 return Error(ExprLoc,
3279 "invalid bundle alignment size (expected between 0 and 30)");
3280
3281 Lex();
3282
3283 // Because of AlignSizePow2's verified range we can safely truncate it to
3284 // unsigned.
3285 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3286 return false;
3287}
3288
Jim Grosbach4a200922013-09-20 23:08:21 +00003289/// parseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003290/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4a200922013-09-20 23:08:21 +00003291bool AsmParser::parseDirectiveBundleLock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003292 checkForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003293 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003294
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003295 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3296 StringRef Option;
3297 SMLoc Loc = getTok().getLoc();
3298 const char *kInvalidOptionError =
Jim Grosbach4a200922013-09-20 23:08:21 +00003299 "invalid option for '.bundle_lock' directive";
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003300
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003301 if (parseIdentifier(Option))
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003302 return Error(Loc, kInvalidOptionError);
3303
3304 if (Option != "align_to_end")
3305 return Error(Loc, kInvalidOptionError);
3306 else if (getLexer().isNot(AsmToken::EndOfStatement))
3307 return Error(Loc,
3308 "unexpected token after '.bundle_lock' directive option");
3309 AlignToEnd = true;
3310 }
3311
Eli Bendersky4766ef42012-12-20 19:05:53 +00003312 Lex();
3313
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003314 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003315 return false;
3316}
3317
Jim Grosbach4a200922013-09-20 23:08:21 +00003318/// parseDirectiveBundleLock
Eli Bendersky4766ef42012-12-20 19:05:53 +00003319/// ::= {.bundle_lock}
Jim Grosbach4a200922013-09-20 23:08:21 +00003320bool AsmParser::parseDirectiveBundleUnlock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003321 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003322
3323 if (getLexer().isNot(AsmToken::EndOfStatement))
3324 return TokError("unexpected token in '.bundle_unlock' directive");
3325 Lex();
3326
3327 getStreamer().EmitBundleUnlock();
3328 return false;
3329}
3330
Jim Grosbach4a200922013-09-20 23:08:21 +00003331/// parseDirectiveSpace
Eli Bendersky6ee13082013-01-15 22:59:42 +00003332/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4a200922013-09-20 23:08:21 +00003333bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003334 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003335
3336 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003337 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003338 return true;
3339
3340 int64_t FillExpr = 0;
3341 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3342 if (getLexer().isNot(AsmToken::Comma))
3343 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3344 Lex();
3345
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003346 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003347 return true;
3348
3349 if (getLexer().isNot(AsmToken::EndOfStatement))
3350 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3351 }
3352
3353 Lex();
3354
3355 if (NumBytes <= 0)
Jim Grosbach4a200922013-09-20 23:08:21 +00003356 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3357 "' directive");
Eli Bendersky6ee13082013-01-15 22:59:42 +00003358
3359 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00003360 getStreamer().EmitFill(NumBytes, FillExpr);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003361
3362 return false;
3363}
3364
Jim Grosbach4a200922013-09-20 23:08:21 +00003365/// parseDirectiveLEB128
Eli Bendersky6ee13082013-01-15 22:59:42 +00003366/// ::= (.sleb128 | .uleb128) expression
Jim Grosbach4a200922013-09-20 23:08:21 +00003367bool AsmParser::parseDirectiveLEB128(bool Signed) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003368 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003369 const MCExpr *Value;
3370
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003371 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003372 return true;
3373
3374 if (getLexer().isNot(AsmToken::EndOfStatement))
3375 return TokError("unexpected token in directive");
3376
3377 if (Signed)
3378 getStreamer().EmitSLEB128Value(Value);
3379 else
3380 getStreamer().EmitULEB128Value(Value);
3381
3382 return false;
3383}
3384
Jim Grosbach4a200922013-09-20 23:08:21 +00003385/// parseDirectiveSymbolAttribute
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003386/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4a200922013-09-20 23:08:21 +00003387bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003388 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003389 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003390 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003391 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003392
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003393 if (parseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003394 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003395
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003396 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003397
Jim Grosbach10ec6502011-09-15 17:56:49 +00003398 // Assembler local symbols don't make any sense here. Complain loudly.
3399 if (Sym->isTemporary())
3400 return Error(Loc, "non-local symbol required in directive");
3401
Saleem Abdulrasool1c9cd022013-08-09 01:52:03 +00003402 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3403 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003404
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003405 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003406 break;
3407
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003408 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003409 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003410 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003411 }
3412 }
3413
Sean Callanan79ed1a82010-01-19 20:22:31 +00003414 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003415 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003416}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003417
Jim Grosbach4a200922013-09-20 23:08:21 +00003418/// parseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003419/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4a200922013-09-20 23:08:21 +00003420bool AsmParser::parseDirectiveComm(bool IsLocal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003421 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003422
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003423 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003424 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003425 if (parseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003426 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003427
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003428 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003429 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003430
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003431 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003432 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003433 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003434
3435 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003436 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003437 if (parseAbsoluteExpression(Size))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003438 return true;
3439
3440 int64_t Pow2Alignment = 0;
3441 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003442 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003443 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003444 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003445 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003446 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003447
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003448 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3449 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003450 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3451
Chris Lattner258281d2010-01-19 06:22:22 +00003452 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003453 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3454 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003455 if (!isPowerOf2_64(Pow2Alignment))
3456 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3457 Pow2Alignment = Log2_64(Pow2Alignment);
3458 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003459 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003460
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003461 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003462 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003463
Sean Callanan79ed1a82010-01-19 20:22:31 +00003464 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003465
Chris Lattner1fc3d752009-07-09 17:25:12 +00003466 // NOTE: a size of zero for a .comm should create a undefined symbol
3467 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003468 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003469 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4a200922013-09-20 23:08:21 +00003470 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003471
Eric Christopherc260a3e2010-05-14 01:38:54 +00003472 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003473 // may internally end up wanting an alignment in bytes.
3474 // FIXME: Diagnose overflow.
3475 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003476 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4a200922013-09-20 23:08:21 +00003477 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003478
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003479 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003480 return Error(IDLoc, "invalid symbol redefinition");
3481
Chris Lattner1fc3d752009-07-09 17:25:12 +00003482 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003483 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003484 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003485 return false;
3486 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003487
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003488 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003489 return false;
3490}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003491
Jim Grosbach4a200922013-09-20 23:08:21 +00003492/// parseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003493/// ::= .abort [... message ...]
Jim Grosbach4a200922013-09-20 23:08:21 +00003494bool AsmParser::parseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003495 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003496 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003497
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003498 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003499 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003500 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003501
Sean Callanan79ed1a82010-01-19 20:22:31 +00003502 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003503
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003504 if (Str.empty())
3505 Error(Loc, ".abort detected. Assembly stopping.");
3506 else
3507 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003508 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003509
3510 return false;
3511}
Kevin Enderby71148242009-07-14 21:35:03 +00003512
Jim Grosbach4a200922013-09-20 23:08:21 +00003513/// parseDirectiveInclude
Kevin Enderby1f049b22009-07-14 23:21:55 +00003514/// ::= .include "filename"
Jim Grosbach4a200922013-09-20 23:08:21 +00003515bool AsmParser::parseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003516 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003517 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003518
Yunzhong Gaoed119822013-09-05 19:14:26 +00003519 // Allow the strings to have escaped octal character sequence.
3520 std::string Filename;
3521 if (parseEscapedString(Filename))
3522 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003523 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003524 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003525
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003526 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003527 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003528
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003529 // Attempt to switch the lexer to the included file before consuming the end
3530 // of statement to avoid losing it when we switch.
Jim Grosbach4a200922013-09-20 23:08:21 +00003531 if (enterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003532 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003533 return true;
3534 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003535
3536 return false;
3537}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003538
Jim Grosbach4a200922013-09-20 23:08:21 +00003539/// parseDirectiveIncbin
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003540/// ::= .incbin "filename"
Jim Grosbach4a200922013-09-20 23:08:21 +00003541bool AsmParser::parseDirectiveIncbin() {
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003542 if (getLexer().isNot(AsmToken::String))
3543 return TokError("expected string in '.incbin' directive");
3544
Yunzhong Gaoed119822013-09-05 19:14:26 +00003545 // Allow the strings to have escaped octal character sequence.
3546 std::string Filename;
3547 if (parseEscapedString(Filename))
3548 return true;
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003549 SMLoc IncbinLoc = getLexer().getLoc();
3550 Lex();
3551
3552 if (getLexer().isNot(AsmToken::EndOfStatement))
3553 return TokError("unexpected token in '.incbin' directive");
3554
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003555 // Attempt to process the included file.
Jim Grosbach4a200922013-09-20 23:08:21 +00003556 if (processIncbinFile(Filename)) {
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003557 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3558 return true;
3559 }
3560
3561 return false;
3562}
3563
Jim Grosbach4a200922013-09-20 23:08:21 +00003564/// parseDirectiveIf
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003565/// ::= .if expression
Jim Grosbach4a200922013-09-20 23:08:21 +00003566bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003567 TheCondStack.push_back(TheCondState);
3568 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003569 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003570 eatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003571 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003572 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003573 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003574 return true;
3575
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003576 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003577 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003578
Sean Callanan79ed1a82010-01-19 20:22:31 +00003579 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003580
3581 TheCondState.CondMet = ExprValue;
3582 TheCondState.Ignore = !TheCondState.CondMet;
3583 }
3584
3585 return false;
3586}
3587
Jim Grosbach4a200922013-09-20 23:08:21 +00003588/// parseDirectiveIfb
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003589/// ::= .ifb string
Jim Grosbach4a200922013-09-20 23:08:21 +00003590bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003591 TheCondStack.push_back(TheCondState);
3592 TheCondState.TheCond = AsmCond::IfCond;
3593
Benjamin Kramer29739e72012-05-12 16:52:21 +00003594 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003595 eatToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003596 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003597 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003598
3599 if (getLexer().isNot(AsmToken::EndOfStatement))
3600 return TokError("unexpected token in '.ifb' directive");
3601
3602 Lex();
3603
3604 TheCondState.CondMet = ExpectBlank == Str.empty();
3605 TheCondState.Ignore = !TheCondState.CondMet;
3606 }
3607
3608 return false;
3609}
3610
Jim Grosbach4a200922013-09-20 23:08:21 +00003611/// parseDirectiveIfc
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003612/// ::= .ifc string1, string2
Jim Grosbach4a200922013-09-20 23:08:21 +00003613bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003614 TheCondStack.push_back(TheCondState);
3615 TheCondState.TheCond = AsmCond::IfCond;
3616
Benjamin Kramer29739e72012-05-12 16:52:21 +00003617 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003618 eatToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003619 } else {
Jim Grosbach4a200922013-09-20 23:08:21 +00003620 StringRef Str1 = parseStringToComma();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003621
3622 if (getLexer().isNot(AsmToken::Comma))
3623 return TokError("unexpected token in '.ifc' directive");
3624
3625 Lex();
3626
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003627 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003628
3629 if (getLexer().isNot(AsmToken::EndOfStatement))
3630 return TokError("unexpected token in '.ifc' directive");
3631
3632 Lex();
3633
3634 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3635 TheCondState.Ignore = !TheCondState.CondMet;
3636 }
3637
3638 return false;
3639}
3640
Jim Grosbach4a200922013-09-20 23:08:21 +00003641/// parseDirectiveIfdef
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003642/// ::= .ifdef symbol
Jim Grosbach4a200922013-09-20 23:08:21 +00003643bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003644 StringRef Name;
3645 TheCondStack.push_back(TheCondState);
3646 TheCondState.TheCond = AsmCond::IfCond;
3647
3648 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003649 eatToEndOfStatement();
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003650 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003651 if (parseIdentifier(Name))
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003652 return TokError("expected identifier after '.ifdef'");
3653
3654 Lex();
3655
3656 MCSymbol *Sym = getContext().LookupSymbol(Name);
3657
3658 if (expect_defined)
3659 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3660 else
3661 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3662 TheCondState.Ignore = !TheCondState.CondMet;
3663 }
3664
3665 return false;
3666}
3667
Jim Grosbach4a200922013-09-20 23:08:21 +00003668/// parseDirectiveElseIf
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003669/// ::= .elseif expression
Jim Grosbach4a200922013-09-20 23:08:21 +00003670bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003671 if (TheCondState.TheCond != AsmCond::IfCond &&
3672 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper955d1e92013-04-22 04:24:02 +00003673 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3674 " an .elseif");
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003675 TheCondState.TheCond = AsmCond::ElseIfCond;
3676
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003677 bool LastIgnoreState = false;
3678 if (!TheCondStack.empty())
Craig Topper955d1e92013-04-22 04:24:02 +00003679 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003680 if (LastIgnoreState || TheCondState.CondMet) {
3681 TheCondState.Ignore = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003682 eatToEndOfStatement();
Craig Topperefa703d2013-04-22 04:22:40 +00003683 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003684 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003685 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003686 return true;
3687
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003688 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003689 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003690
Sean Callanan79ed1a82010-01-19 20:22:31 +00003691 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003692 TheCondState.CondMet = ExprValue;
3693 TheCondState.Ignore = !TheCondState.CondMet;
3694 }
3695
3696 return false;
3697}
3698
Jim Grosbach4a200922013-09-20 23:08:21 +00003699/// parseDirectiveElse
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003700/// ::= .else
Jim Grosbach4a200922013-09-20 23:08:21 +00003701bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003702 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003703 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003704
Sean Callanan79ed1a82010-01-19 20:22:31 +00003705 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003706
3707 if (TheCondState.TheCond != AsmCond::IfCond &&
3708 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper955d1e92013-04-22 04:24:02 +00003709 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3710 ".elseif");
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003711 TheCondState.TheCond = AsmCond::ElseCond;
3712 bool LastIgnoreState = false;
3713 if (!TheCondStack.empty())
3714 LastIgnoreState = TheCondStack.back().Ignore;
3715 if (LastIgnoreState || TheCondState.CondMet)
3716 TheCondState.Ignore = true;
3717 else
3718 TheCondState.Ignore = false;
3719
3720 return false;
3721}
3722
Jim Grosbach4a200922013-09-20 23:08:21 +00003723/// parseDirectiveEndIf
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003724/// ::= .endif
Jim Grosbach4a200922013-09-20 23:08:21 +00003725bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003726 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003727 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003728
Sean Callanan79ed1a82010-01-19 20:22:31 +00003729 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003730
Jim Grosbach4a200922013-09-20 23:08:21 +00003731 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003732 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3733 ".else");
3734 if (!TheCondStack.empty()) {
3735 TheCondState = TheCondStack.back();
3736 TheCondStack.pop_back();
3737 }
3738
3739 return false;
3740}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003741
Eli Bendersky6ee13082013-01-15 22:59:42 +00003742void AsmParser::initializeDirectiveKindMap() {
3743 DirectiveKindMap[".set"] = DK_SET;
3744 DirectiveKindMap[".equ"] = DK_EQU;
3745 DirectiveKindMap[".equiv"] = DK_EQUIV;
3746 DirectiveKindMap[".ascii"] = DK_ASCII;
3747 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3748 DirectiveKindMap[".string"] = DK_STRING;
3749 DirectiveKindMap[".byte"] = DK_BYTE;
3750 DirectiveKindMap[".short"] = DK_SHORT;
3751 DirectiveKindMap[".value"] = DK_VALUE;
3752 DirectiveKindMap[".2byte"] = DK_2BYTE;
3753 DirectiveKindMap[".long"] = DK_LONG;
3754 DirectiveKindMap[".int"] = DK_INT;
3755 DirectiveKindMap[".4byte"] = DK_4BYTE;
3756 DirectiveKindMap[".quad"] = DK_QUAD;
3757 DirectiveKindMap[".8byte"] = DK_8BYTE;
3758 DirectiveKindMap[".single"] = DK_SINGLE;
3759 DirectiveKindMap[".float"] = DK_FLOAT;
3760 DirectiveKindMap[".double"] = DK_DOUBLE;
3761 DirectiveKindMap[".align"] = DK_ALIGN;
3762 DirectiveKindMap[".align32"] = DK_ALIGN32;
3763 DirectiveKindMap[".balign"] = DK_BALIGN;
3764 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3765 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3766 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3767 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3768 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3769 DirectiveKindMap[".org"] = DK_ORG;
3770 DirectiveKindMap[".fill"] = DK_FILL;
3771 DirectiveKindMap[".zero"] = DK_ZERO;
3772 DirectiveKindMap[".extern"] = DK_EXTERN;
3773 DirectiveKindMap[".globl"] = DK_GLOBL;
3774 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky6ee13082013-01-15 22:59:42 +00003775 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3776 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3777 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3778 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3779 DirectiveKindMap[".reference"] = DK_REFERENCE;
3780 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3781 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3782 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3783 DirectiveKindMap[".comm"] = DK_COMM;
3784 DirectiveKindMap[".common"] = DK_COMMON;
3785 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3786 DirectiveKindMap[".abort"] = DK_ABORT;
3787 DirectiveKindMap[".include"] = DK_INCLUDE;
3788 DirectiveKindMap[".incbin"] = DK_INCBIN;
3789 DirectiveKindMap[".code16"] = DK_CODE16;
3790 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3791 DirectiveKindMap[".rept"] = DK_REPT;
3792 DirectiveKindMap[".irp"] = DK_IRP;
3793 DirectiveKindMap[".irpc"] = DK_IRPC;
3794 DirectiveKindMap[".endr"] = DK_ENDR;
3795 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3796 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3797 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3798 DirectiveKindMap[".if"] = DK_IF;
3799 DirectiveKindMap[".ifb"] = DK_IFB;
3800 DirectiveKindMap[".ifnb"] = DK_IFNB;
3801 DirectiveKindMap[".ifc"] = DK_IFC;
3802 DirectiveKindMap[".ifnc"] = DK_IFNC;
3803 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3804 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3805 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3806 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3807 DirectiveKindMap[".else"] = DK_ELSE;
3808 DirectiveKindMap[".endif"] = DK_ENDIF;
3809 DirectiveKindMap[".skip"] = DK_SKIP;
3810 DirectiveKindMap[".space"] = DK_SPACE;
3811 DirectiveKindMap[".file"] = DK_FILE;
3812 DirectiveKindMap[".line"] = DK_LINE;
3813 DirectiveKindMap[".loc"] = DK_LOC;
3814 DirectiveKindMap[".stabs"] = DK_STABS;
3815 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3816 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3817 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3818 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3819 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3820 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3821 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3822 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3823 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3824 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3825 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3826 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3827 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3828 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3829 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3830 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3831 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3832 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3833 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3834 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3835 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju83ba58e2013-09-26 14:49:40 +00003836 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky6ee13082013-01-15 22:59:42 +00003837 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3838 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3839 DirectiveKindMap[".macro"] = DK_MACRO;
3840 DirectiveKindMap[".endm"] = DK_ENDM;
3841 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3842 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003843}
3844
Jim Grosbach4a200922013-09-20 23:08:21 +00003845MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003846 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003847
Rafael Espindola761cb062012-06-03 23:57:14 +00003848 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003849 for (;;) {
3850 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003851 if (getLexer().is(AsmToken::Eof)) {
3852 Error(DirectiveLoc, "no matching '.endr' in definition");
3853 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003854 }
3855
Rafael Espindola761cb062012-06-03 23:57:14 +00003856 if (Lexer.is(AsmToken::Identifier) &&
3857 (getTok().getIdentifier() == ".rept")) {
3858 ++NestLevel;
3859 }
3860
3861 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4a200922013-09-20 23:08:21 +00003862 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola761cb062012-06-03 23:57:14 +00003863 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003864 EndToken = getTok();
3865 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003866 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3867 TokError("unexpected token in '.endr' directive");
3868 return 0;
3869 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003870 break;
3871 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003872 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003873 }
3874
Rafael Espindola761cb062012-06-03 23:57:14 +00003875 // Otherwise, scan till the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003876 eatToEndOfStatement();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003877 }
3878
3879 const char *BodyStart = StartToken.getLoc().getPointer();
3880 const char *BodyEnd = EndToken.getLoc().getPointer();
3881 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3882
Rafael Espindola761cb062012-06-03 23:57:14 +00003883 // We Are Anonymous.
3884 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003885 MCAsmMacroParameters Parameters;
Benjamin Kramera2b0c332013-08-04 09:06:29 +00003886 MacroLikeBodies.push_back(MCAsmMacro(Name, Body, Parameters));
3887 return &MacroLikeBodies.back();
Rafael Espindola761cb062012-06-03 23:57:14 +00003888}
3889
Jim Grosbach4a200922013-09-20 23:08:21 +00003890void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003891 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003892 OS << ".endr\n";
3893
3894 MemoryBuffer *Instantiation =
Jim Grosbach4a200922013-09-20 23:08:21 +00003895 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003896
Rafael Espindola761cb062012-06-03 23:57:14 +00003897 // Create the macro instantiation object and add to the current macro
3898 // instantiation stack.
Jim Grosbach4a200922013-09-20 23:08:21 +00003899 MacroInstantiation *MI = new MacroInstantiation(
3900 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
Rafael Espindola761cb062012-06-03 23:57:14 +00003901 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003902
Rafael Espindola761cb062012-06-03 23:57:14 +00003903 // Jump to the macro instantiation and prime the lexer.
3904 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3905 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3906 Lex();
3907}
3908
Jim Grosbach4a200922013-09-20 23:08:21 +00003909bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc) {
Rafael Espindola761cb062012-06-03 23:57:14 +00003910 int64_t Count;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003911 if (parseAbsoluteExpression(Count))
Rafael Espindola761cb062012-06-03 23:57:14 +00003912 return TokError("unexpected token in '.rept' directive");
3913
3914 if (Count < 0)
3915 return TokError("Count is negative");
3916
3917 if (Lexer.isNot(AsmToken::EndOfStatement))
3918 return TokError("unexpected token in '.rept' directive");
3919
3920 // Eat the end of statement.
3921 Lex();
3922
3923 // Lex the rept definition.
Jim Grosbach4a200922013-09-20 23:08:21 +00003924 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003925 if (!M)
3926 return true;
3927
3928 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3929 // to hold the macro body with substitutions.
3930 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003931 MCAsmMacroParameters Parameters;
3932 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003933 raw_svector_ostream OS(Buf);
3934 while (Count--) {
3935 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3936 return true;
3937 }
Jim Grosbach4a200922013-09-20 23:08:21 +00003938 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003939
3940 return false;
3941}
3942
Jim Grosbach4a200922013-09-20 23:08:21 +00003943/// parseDirectiveIrp
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003944/// ::= .irp symbol,values
Jim Grosbach4a200922013-09-20 23:08:21 +00003945bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003946 MCAsmMacroParameters Parameters;
3947 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003948
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003949 if (parseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003950 return TokError("expected identifier in '.irp' directive");
3951
3952 Parameters.push_back(Parameter);
3953
3954 if (Lexer.isNot(AsmToken::Comma))
3955 return TokError("expected comma in '.irp' directive");
3956
3957 Lex();
3958
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003959 MCAsmMacroArguments A;
Jim Grosbach4a200922013-09-20 23:08:21 +00003960 if (parseMacroArguments(0, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003961 return true;
3962
3963 // Eat the end of statement.
3964 Lex();
3965
3966 // Lex the irp definition.
Jim Grosbach4a200922013-09-20 23:08:21 +00003967 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003968 if (!M)
3969 return true;
3970
3971 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3972 // to hold the macro body with substitutions.
3973 SmallString<256> Buf;
3974 raw_svector_ostream OS(Buf);
3975
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003976 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3977 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003978 Args.push_back(*i);
3979
3980 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3981 return true;
3982 }
3983
Jim Grosbach4a200922013-09-20 23:08:21 +00003984 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003985
3986 return false;
3987}
3988
Jim Grosbach4a200922013-09-20 23:08:21 +00003989/// parseDirectiveIrpc
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003990/// ::= .irpc symbol,values
Jim Grosbach4a200922013-09-20 23:08:21 +00003991bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003992 MCAsmMacroParameters Parameters;
3993 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003994
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003995 if (parseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003996 return TokError("expected identifier in '.irpc' directive");
3997
3998 Parameters.push_back(Parameter);
3999
4000 if (Lexer.isNot(AsmToken::Comma))
4001 return TokError("expected comma in '.irpc' directive");
4002
4003 Lex();
4004
Eli Benderskyc0c67b02013-01-14 23:22:36 +00004005 MCAsmMacroArguments A;
Jim Grosbach4a200922013-09-20 23:08:21 +00004006 if (parseMacroArguments(0, A))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004007 return true;
4008
4009 if (A.size() != 1 || A.front().size() != 1)
4010 return TokError("unexpected token in '.irpc' directive");
4011
4012 // Eat the end of statement.
4013 Lex();
4014
4015 // Lex the irpc definition.
Jim Grosbach4a200922013-09-20 23:08:21 +00004016 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004017 if (!M)
4018 return true;
4019
4020 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4021 // to hold the macro body with substitutions.
4022 SmallString<256> Buf;
4023 raw_svector_ostream OS(Buf);
4024
4025 StringRef Values = A.front().front().getString();
4026 std::size_t I, End = Values.size();
4027 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00004028 MCAsmMacroArgument Arg;
Jim Grosbach4a200922013-09-20 23:08:21 +00004029 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004030
Eli Benderskyc0c67b02013-01-14 23:22:36 +00004031 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004032 Args.push_back(Arg);
4033
4034 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4035 return true;
4036 }
4037
Jim Grosbach4a200922013-09-20 23:08:21 +00004038 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004039
4040 return false;
4041}
4042
Jim Grosbach4a200922013-09-20 23:08:21 +00004043bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola761cb062012-06-03 23:57:14 +00004044 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00004045 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004046
4047 // The only .repl that should get here are the ones created by
Jim Grosbach4a200922013-09-20 23:08:21 +00004048 // instantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004049 assert(getLexer().is(AsmToken::EndOfStatement));
4050
Jim Grosbach4a200922013-09-20 23:08:21 +00004051 handleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004052 return false;
4053}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00004054
Jim Grosbach4a200922013-09-20 23:08:21 +00004055bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer75234372013-02-15 20:37:21 +00004056 size_t Len) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004057 const MCExpr *Value;
4058 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004059 if (parseExpression(Value))
Eli Friedman2128aae2012-10-22 23:58:19 +00004060 return true;
4061 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4062 if (!MCE)
4063 return Error(ExprLoc, "unexpected expression in _emit");
4064 uint64_t IntValue = MCE->getValue();
4065 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4066 return Error(ExprLoc, "literal value out of range for directive");
4067
Chad Rosier469b1442013-02-12 21:33:51 +00004068 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4069 return false;
4070}
4071
Jim Grosbach4a200922013-09-20 23:08:21 +00004072bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosier469b1442013-02-12 21:33:51 +00004073 const MCExpr *Value;
4074 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004075 if (parseExpression(Value))
Chad Rosier469b1442013-02-12 21:33:51 +00004076 return true;
4077 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4078 if (!MCE)
4079 return Error(ExprLoc, "unexpected expression in align");
4080 uint64_t IntValue = MCE->getValue();
4081 if (!isPowerOf2_64(IntValue))
4082 return Error(ExprLoc, "literal value not a power of two greater then zero");
4083
Jim Grosbach4a200922013-09-20 23:08:21 +00004084 Info.AsmRewrites->push_back(
4085 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
Eli Friedman2128aae2012-10-22 23:58:19 +00004086 return false;
4087}
4088
Chad Rosier19aa3e32013-02-13 21:27:17 +00004089// We are comparing pointers, but the pointers are relative to a single string.
4090// Thus, this should always be deterministic.
Benjamin Kramer0d293e42013-09-22 14:09:50 +00004091static int rewritesSort(const AsmRewrite *AsmRewriteA,
4092 const AsmRewrite *AsmRewriteB) {
Chad Rosierabde6752013-02-13 18:38:58 +00004093 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4094 return -1;
4095 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4096 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004097
Chad Rosier6b369ce2013-04-08 17:43:47 +00004098 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4099 // rewrite to the same location. Make sure the SizeDirective rewrite is
4100 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4101 // ensures the sort algorithm is stable.
Jim Grosbach4a200922013-09-20 23:08:21 +00004102 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4103 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004104 return -1;
Chad Rosier6b369ce2013-04-08 17:43:47 +00004105
Jim Grosbach4a200922013-09-20 23:08:21 +00004106 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4107 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004108 return 1;
Jim Grosbach4a200922013-09-20 23:08:21 +00004109 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb1953982013-02-13 01:03:13 +00004110}
4111
Jim Grosbach4a200922013-09-20 23:08:21 +00004112bool AsmParser::parseMSInlineAsm(
4113 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4114 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4115 SmallVectorImpl<std::string> &Constraints,
4116 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4117 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004118 SmallVector<void *, 4> InputDecls;
4119 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00004120 SmallVector<bool, 4> InputDeclsAddressOf;
4121 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004122 SmallVector<std::string, 4> InputConstraints;
4123 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer75234372013-02-15 20:37:21 +00004124 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004125
Benjamin Kramer75234372013-02-15 20:37:21 +00004126 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004127
4128 // Prime the lexer.
4129 Lex();
4130
4131 // While we have input, parse each statement.
4132 unsigned InputIdx = 0;
4133 unsigned OutputIdx = 0;
4134 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004135 ParseStatementInfo Info(&AsmStrRewrites);
Jim Grosbach4a200922013-09-20 23:08:21 +00004136 if (parseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00004137 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004138
Chad Rosier57498012012-12-12 22:45:52 +00004139 if (Info.ParseError)
4140 return true;
4141
Benjamin Kramer75234372013-02-15 20:37:21 +00004142 if (Info.Opcode == ~0U)
4143 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004144
Benjamin Kramer75234372013-02-15 20:37:21 +00004145 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004146
Benjamin Kramer75234372013-02-15 20:37:21 +00004147 // Build the list of clobbers, outputs and inputs.
4148 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4149 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004150
Benjamin Kramer75234372013-02-15 20:37:21 +00004151 // Immediate.
Chad Rosier811ddf62013-03-19 21:58:18 +00004152 if (Operand->isImm())
Benjamin Kramer75234372013-02-15 20:37:21 +00004153 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004154
Benjamin Kramer75234372013-02-15 20:37:21 +00004155 // Register operand.
4156 if (Operand->isReg() && !Operand->needAddressOf()) {
4157 unsigned NumDefs = Desc.getNumDefs();
4158 // Clobber.
4159 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4160 ClobberRegs.push_back(Operand->getReg());
4161 continue;
4162 }
4163
4164 // Expr/Input or Output.
Chad Rosierb976e402013-04-09 17:53:49 +00004165 StringRef SymName = Operand->getSymName();
4166 if (SymName.empty())
4167 continue;
4168
Chad Rosier087c3092013-04-22 22:12:12 +00004169 void *OpDecl = Operand->getOpDecl();
Benjamin Kramer75234372013-02-15 20:37:21 +00004170 if (!OpDecl)
4171 continue;
4172
4173 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierb976e402013-04-09 17:53:49 +00004174 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer75234372013-02-15 20:37:21 +00004175 if (isOutput) {
4176 ++InputIdx;
4177 OutputDecls.push_back(OpDecl);
4178 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4179 OutputConstraints.push_back('=' + Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004180 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
Benjamin Kramer75234372013-02-15 20:37:21 +00004181 } else {
4182 InputDecls.push_back(OpDecl);
4183 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4184 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004185 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004186 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004187 }
4188 }
4189
4190 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004191 NumOutputs = OutputDecls.size();
4192 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004193
4194 // Set the unique clobbers.
Benjamin Kramer75234372013-02-15 20:37:21 +00004195 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4196 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4197 ClobberRegs.end());
4198 Clobbers.assign(ClobberRegs.size(), std::string());
4199 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4200 raw_string_ostream OS(Clobbers[I]);
4201 IP->printRegName(OS, ClobberRegs[I]);
4202 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004203
4204 // Merge the various outputs and inputs. Output are expected first.
4205 if (NumOutputs || NumInputs) {
4206 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004207 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004208 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004209 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004210 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004211 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004212 }
4213 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004214 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004215 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004216 }
4217 }
4218
4219 // Build the IR assembly string.
4220 std::string AsmStringIR;
4221 raw_string_ostream OS(AsmStringIR);
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004222 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4223 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
Jim Grosbach4a200922013-09-20 23:08:21 +00004224 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
Benjamin Kramer75234372013-02-15 20:37:21 +00004225 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4226 E = AsmStrRewrites.end();
4227 I != E; ++I) {
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004228 AsmRewriteKind Kind = (*I).Kind;
4229 if (Kind == AOK_Delete)
4230 continue;
4231
Chad Rosierb1f8c132012-10-18 15:49:34 +00004232 const char *Loc = (*I).Loc.getPointer();
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004233 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier96d58e62012-10-19 20:57:14 +00004234
Chad Rosier023c8802013-03-19 17:32:17 +00004235 // Emit everything up to the immediate/expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004236 unsigned Len = Loc - AsmStart;
Chad Rosierf06cc982013-04-11 21:49:30 +00004237 if (Len)
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004238 OS << StringRef(AsmStart, Len);
Chad Rosier96d58e62012-10-19 20:57:14 +00004239
Chad Rosier5a719fc2012-10-23 17:43:43 +00004240 // Skip the original expression.
4241 if (Kind == AOK_Skip) {
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004242 AsmStart = Loc + (*I).Len;
Chad Rosier5a719fc2012-10-23 17:43:43 +00004243 continue;
4244 }
4245
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004246 unsigned AdditionalSkip = 0;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004247 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004248 switch (Kind) {
Jim Grosbach4a200922013-09-20 23:08:21 +00004249 default:
4250 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004251 case AOK_Imm:
Benjamin Kramer75234372013-02-15 20:37:21 +00004252 OS << "$$" << (*I).Val;
Chad Rosierefcb3d92012-10-26 18:04:20 +00004253 break;
4254 case AOK_ImmPrefix:
Benjamin Kramer75234372013-02-15 20:37:21 +00004255 OS << "$$";
Chad Rosierb1f8c132012-10-18 15:49:34 +00004256 break;
4257 case AOK_Input:
Benjamin Kramer75234372013-02-15 20:37:21 +00004258 OS << '$' << InputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004259 break;
4260 case AOK_Output:
Benjamin Kramer75234372013-02-15 20:37:21 +00004261 OS << '$' << OutputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004262 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004263 case AOK_SizeDirective:
Benjamin Kramer75234372013-02-15 20:37:21 +00004264 switch ((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004265 default: break;
4266 case 8: OS << "byte ptr "; break;
4267 case 16: OS << "word ptr "; break;
4268 case 32: OS << "dword ptr "; break;
4269 case 64: OS << "qword ptr "; break;
4270 case 80: OS << "xword ptr "; break;
4271 case 128: OS << "xmmword ptr "; break;
4272 case 256: OS << "ymmword ptr "; break;
4273 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004274 break;
4275 case AOK_Emit:
4276 OS << ".byte";
4277 break;
Chad Rosier469b1442013-02-12 21:33:51 +00004278 case AOK_Align: {
4279 unsigned Val = (*I).Val;
4280 OS << ".align " << Val;
4281
4282 // Skip the original immediate.
Benjamin Kramer75234372013-02-15 20:37:21 +00004283 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosier469b1442013-02-12 21:33:51 +00004284 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4285 break;
4286 }
Chad Rosier6a020a72012-10-25 20:41:34 +00004287 case AOK_DotOperator:
4288 OS << (*I).Val;
4289 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004290 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004291
Chad Rosierb1f8c132012-10-18 15:49:34 +00004292 // Skip the original expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004293 AsmStart = Loc + (*I).Len + AdditionalSkip;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004294 }
4295
4296 // Emit the remainder of the asm string.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004297 if (AsmStart != AsmEnd)
4298 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004299
4300 AsmString = OS.str();
4301 return false;
4302}
4303
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004304/// \brief Create an MCAsmParser instance.
Jim Grosbach4a200922013-09-20 23:08:21 +00004305MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4306 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004307 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004308}