blob: 3bd7fcc5e38ca9190a977e90e525479ede5e79af [file] [log] [blame]
Alp Toker1b935a82014-06-08 05:40:04 +00001//===---- ParseStmtAsm.cpp - Assembly Statement Parser --------------------===//
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 file implements parsing for GCC and Microsoft inline assembly.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
Alp Toker1b935a82014-06-08 05:40:04 +000015#include "clang/AST/ASTContext.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/TargetInfo.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000018#include "clang/Parse/RAIIObjectsForParser.h"
Alp Toker1b935a82014-06-08 05:40:04 +000019#include "llvm/ADT/SmallString.h"
Marina Yatsina41c45fa2016-02-03 11:32:08 +000020#include "llvm/ADT/StringExtras.h"
Alp Toker1b935a82014-06-08 05:40:04 +000021#include "llvm/MC/MCAsmInfo.h"
22#include "llvm/MC/MCContext.h"
23#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/MC/MCInstrInfo.h"
25#include "llvm/MC/MCObjectFileInfo.h"
26#include "llvm/MC/MCParser/MCAsmParser.h"
Benjamin Kramer5e456302016-01-27 10:01:30 +000027#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Alp Toker1b935a82014-06-08 05:40:04 +000028#include "llvm/MC/MCRegisterInfo.h"
29#include "llvm/MC/MCStreamer.h"
30#include "llvm/MC/MCSubtargetInfo.h"
Alp Toker1b935a82014-06-08 05:40:04 +000031#include "llvm/MC/MCTargetOptions.h"
32#include "llvm/Support/SourceMgr.h"
33#include "llvm/Support/TargetRegistry.h"
34#include "llvm/Support/TargetSelect.h"
35using namespace clang;
36
37namespace {
38class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
39 Parser &TheParser;
40 SourceLocation AsmLoc;
41 StringRef AsmString;
42
43 /// The tokens we streamed into AsmString and handed off to MC.
44 ArrayRef<Token> AsmToks;
45
46 /// The offset of each token in AsmToks within AsmString.
47 ArrayRef<unsigned> AsmTokOffsets;
48
49public:
50 ClangAsmParserCallback(Parser &P, SourceLocation Loc, StringRef AsmString,
51 ArrayRef<Token> Toks, ArrayRef<unsigned> Offsets)
52 : TheParser(P), AsmLoc(Loc), AsmString(AsmString), AsmToks(Toks),
53 AsmTokOffsets(Offsets) {
54 assert(AsmToks.size() == AsmTokOffsets.size());
55 }
56
Coby Tayree61504192017-09-29 07:02:49 +000057 void LookupInlineAsmIdentifier(StringRef &LineBuf,
58 llvm::InlineAsmIdentifierInfo &Info,
59 bool IsUnevaluatedContext) override {
Alp Toker1b935a82014-06-08 05:40:04 +000060 // Collect the desired tokens.
61 SmallVector<Token, 16> LineToks;
62 const Token *FirstOrigToken = nullptr;
63 findTokensForString(LineBuf, LineToks, FirstOrigToken);
64
65 unsigned NumConsumedToks;
66 ExprResult Result = TheParser.ParseMSAsmIdentifier(
Coby Tayree61504192017-09-29 07:02:49 +000067 LineToks, NumConsumedToks, IsUnevaluatedContext);
Alp Toker1b935a82014-06-08 05:40:04 +000068
69 // If we consumed the entire line, tell MC that.
70 // Also do this if we consumed nothing as a way of reporting failure.
71 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
72 // By not modifying LineBuf, we're implicitly consuming it all.
73
74 // Otherwise, consume up to the original tokens.
75 } else {
76 assert(FirstOrigToken && "not using original tokens?");
77
78 // Since we're using original tokens, apply that offset.
79 assert(FirstOrigToken[NumConsumedToks].getLocation() ==
80 LineToks[NumConsumedToks].getLocation());
81 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
82 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
83
84 // The total length we've consumed is the relative offset
85 // of the last token we consumed plus its length.
86 unsigned TotalOffset =
87 (AsmTokOffsets[LastIndex] + AsmToks[LastIndex].getLength() -
88 AsmTokOffsets[FirstIndex]);
89 LineBuf = LineBuf.substr(0, TotalOffset);
90 }
91
Coby Tayree61504192017-09-29 07:02:49 +000092 // Initialize Info with the lookup result.
93 if (!Result.isUsable())
94 return;
95 TheParser.getActions().FillInlineAsmIdentifierInfo(Result.get(), Info);
Alp Toker1b935a82014-06-08 05:40:04 +000096 }
97
Ehsan Akhgari31097582014-09-22 02:21:54 +000098 StringRef LookupInlineAsmLabel(StringRef Identifier, llvm::SourceMgr &LSM,
99 llvm::SMLoc Location,
100 bool Create) override {
101 SourceLocation Loc = translateLocation(LSM, Location);
102 LabelDecl *Label =
103 TheParser.getActions().GetOrCreateMSAsmLabel(Identifier, Loc, Create);
104 return Label->getMSAsmLabel();
105 }
106
Alp Toker1b935a82014-06-08 05:40:04 +0000107 bool LookupInlineAsmField(StringRef Base, StringRef Member,
108 unsigned &Offset) override {
109 return TheParser.getActions().LookupInlineAsmField(Base, Member, Offset,
110 AsmLoc);
111 }
112
113 static void DiagHandlerCallback(const llvm::SMDiagnostic &D, void *Context) {
114 ((ClangAsmParserCallback *)Context)->handleDiagnostic(D);
115 }
116
117private:
118 /// Collect the appropriate tokens for the given string.
119 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
120 const Token *&FirstOrigToken) const {
121 // For now, assert that the string we're working with is a substring
122 // of what we gave to MC. This lets us use the original tokens.
123 assert(!std::less<const char *>()(Str.begin(), AsmString.begin()) &&
124 !std::less<const char *>()(AsmString.end(), Str.end()));
125
126 // Try to find a token whose offset matches the first token.
127 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
128 const unsigned *FirstTokOffset = std::lower_bound(
129 AsmTokOffsets.begin(), AsmTokOffsets.end(), FirstCharOffset);
130
131 // For now, assert that the start of the string exactly
132 // corresponds to the start of a token.
133 assert(*FirstTokOffset == FirstCharOffset);
134
135 // Use all the original tokens for this line. (We assume the
136 // end of the line corresponds cleanly to a token break.)
137 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
138 FirstOrigToken = &AsmToks[FirstTokIndex];
139 unsigned LastCharOffset = Str.end() - AsmString.begin();
140 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
141 if (AsmTokOffsets[i] >= LastCharOffset)
142 break;
143 TempToks.push_back(AsmToks[i]);
144 }
145 }
146
Ehsan Akhgari31097582014-09-22 02:21:54 +0000147 SourceLocation translateLocation(const llvm::SourceMgr &LSM, llvm::SMLoc SMLoc) {
Alp Toker1b935a82014-06-08 05:40:04 +0000148 // Compute an offset into the inline asm buffer.
149 // FIXME: This isn't right if .macro is involved (but hopefully, no
150 // real-world code does that).
Alp Toker1b935a82014-06-08 05:40:04 +0000151 const llvm::MemoryBuffer *LBuf =
Ehsan Akhgari31097582014-09-22 02:21:54 +0000152 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(SMLoc));
153 unsigned Offset = SMLoc.getPointer() - LBuf->getBufferStart();
Alp Toker1b935a82014-06-08 05:40:04 +0000154
155 // Figure out which token that offset points into.
156 const unsigned *TokOffsetPtr =
157 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
158 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
159 unsigned TokOffset = *TokOffsetPtr;
160
161 // If we come up with an answer which seems sane, use it; otherwise,
162 // just point at the __asm keyword.
163 // FIXME: Assert the answer is sane once we handle .macro correctly.
164 SourceLocation Loc = AsmLoc;
165 if (TokIndex < AsmToks.size()) {
166 const Token &Tok = AsmToks[TokIndex];
167 Loc = Tok.getLocation();
168 Loc = Loc.getLocWithOffset(Offset - TokOffset);
169 }
Ehsan Akhgari31097582014-09-22 02:21:54 +0000170 return Loc;
171 }
172
173 void handleDiagnostic(const llvm::SMDiagnostic &D) {
174 const llvm::SourceMgr &LSM = *D.getSourceMgr();
175 SourceLocation Loc = translateLocation(LSM, D.getLoc());
Alp Toker1b935a82014-06-08 05:40:04 +0000176 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage();
177 }
178};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000179}
Alp Toker1b935a82014-06-08 05:40:04 +0000180
181/// Parse an identifier in an MS-style inline assembly block.
Alp Toker1b935a82014-06-08 05:40:04 +0000182ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
183 unsigned &NumLineToksConsumed,
Alp Toker1b935a82014-06-08 05:40:04 +0000184 bool IsUnevaluatedContext) {
Alp Toker1b935a82014-06-08 05:40:04 +0000185 // Push a fake token on the end so that we don't overrun the token
186 // stream. We use ';' because it expression-parsing should never
187 // overrun it.
188 const tok::TokenKind EndOfStream = tok::semi;
189 Token EndOfStreamTok;
190 EndOfStreamTok.startToken();
191 EndOfStreamTok.setKind(EndOfStream);
192 LineToks.push_back(EndOfStreamTok);
193
194 // Also copy the current token over.
195 LineToks.push_back(Tok);
196
David Blaikie2eabcc92016-02-09 18:52:09 +0000197 PP.EnterTokenStream(LineToks, /*DisableMacroExpansions*/ true);
Alp Toker1b935a82014-06-08 05:40:04 +0000198
199 // Clear the current token and advance to the first token in LineToks.
200 ConsumeAnyToken();
201
202 // Parse an optional scope-specifier if we're in C++.
203 CXXScopeSpec SS;
204 if (getLangOpts().CPlusPlus) {
David Blaikieefdccaa2016-01-15 23:43:34 +0000205 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Alp Toker1b935a82014-06-08 05:40:04 +0000206 }
207
208 // Require an identifier here.
209 SourceLocation TemplateKWLoc;
210 UnqualifiedId Id;
Michael Zuckerman229158c2015-12-15 14:04:18 +0000211 bool Invalid = true;
212 ExprResult Result;
213 if (Tok.is(tok::kw_this)) {
214 Result = ParseCXXThis();
215 Invalid = false;
216 } else {
David Blaikieefdccaa2016-01-15 23:43:34 +0000217 Invalid = ParseUnqualifiedId(SS,
218 /*EnteringContext=*/false,
219 /*AllowDestructorName=*/false,
220 /*AllowConstructorName=*/false,
Richard Smith35845152017-02-07 01:37:30 +0000221 /*AllowDeductionGuide=*/false,
David Blaikieefdccaa2016-01-15 23:43:34 +0000222 /*ObjectType=*/nullptr, TemplateKWLoc, Id);
Michael Zuckerman229158c2015-12-15 14:04:18 +0000223 // Perform the lookup.
Coby Tayree61504192017-09-29 07:02:49 +0000224 Result = Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id,
Michael Zuckerman229158c2015-12-15 14:04:18 +0000225 IsUnevaluatedContext);
226 }
Reid Kleckner14e96b42015-08-26 21:57:20 +0000227 // While the next two tokens are 'period' 'identifier', repeatedly parse it as
228 // a field access. We have to avoid consuming assembler directives that look
229 // like '.' 'else'.
230 while (Result.isUsable() && Tok.is(tok::period)) {
231 Token IdTok = PP.LookAhead(0);
232 if (IdTok.isNot(tok::identifier))
233 break;
234 ConsumeToken(); // Consume the period.
235 IdentifierInfo *Id = Tok.getIdentifierInfo();
236 ConsumeToken(); // Consume the identifier.
David Majnemer758e7982016-01-05 00:08:41 +0000237 Result = Actions.LookupInlineAsmVarDeclField(Result.get(), Id->getName(),
Coby Tayree61504192017-09-29 07:02:49 +0000238 Tok.getLocation());
Reid Kleckner14e96b42015-08-26 21:57:20 +0000239 }
240
Alp Toker1b935a82014-06-08 05:40:04 +0000241 // Figure out how many tokens we are into LineToks.
242 unsigned LineIndex = 0;
243 if (Tok.is(EndOfStream)) {
244 LineIndex = LineToks.size() - 2;
245 } else {
246 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
247 LineIndex++;
248 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
249 }
250 }
251
252 // If we've run into the poison token we inserted before, or there
253 // was a parsing error, then claim the entire line.
254 if (Invalid || Tok.is(EndOfStream)) {
255 NumLineToksConsumed = LineToks.size() - 2;
256 } else {
257 // Otherwise, claim up to the start of the next token.
258 NumLineToksConsumed = LineIndex;
259 }
260
261 // Finally, restore the old parsing state by consuming all the tokens we
262 // staged before, implicitly killing off the token-lexer we pushed.
263 for (unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; ++i) {
264 ConsumeAnyToken();
265 }
266 assert(Tok.is(EndOfStream));
267 ConsumeToken();
268
269 // Leave LineToks in its original state.
270 LineToks.pop_back();
271 LineToks.pop_back();
272
Reid Kleckner14e96b42015-08-26 21:57:20 +0000273 return Result;
Alp Toker1b935a82014-06-08 05:40:04 +0000274}
275
276/// Turn a sequence of our tokens back into a string that we can hand
277/// to the MC asm parser.
278static bool buildMSAsmString(Preprocessor &PP, SourceLocation AsmLoc,
279 ArrayRef<Token> AsmToks,
280 SmallVectorImpl<unsigned> &TokOffsets,
281 SmallString<512> &Asm) {
282 assert(!AsmToks.empty() && "Didn't expect an empty AsmToks!");
283
284 // Is this the start of a new assembly statement?
285 bool isNewStatement = true;
286
287 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
288 const Token &Tok = AsmToks[i];
289
290 // Start each new statement with a newline and a tab.
291 if (!isNewStatement && (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
292 Asm += "\n\t";
293 isNewStatement = true;
294 }
295
296 // Preserve the existence of leading whitespace except at the
297 // start of a statement.
298 if (!isNewStatement && Tok.hasLeadingSpace())
299 Asm += ' ';
300
301 // Remember the offset of this token.
302 TokOffsets.push_back(Asm.size());
303
304 // Don't actually write '__asm' into the assembly stream.
305 if (Tok.is(tok::kw_asm)) {
306 // Complain about __asm at the end of the stream.
307 if (i + 1 == e) {
308 PP.Diag(AsmLoc, diag::err_asm_empty);
309 return true;
310 }
311
312 continue;
313 }
314
315 // Append the spelling of the token.
316 SmallString<32> SpellingBuffer;
317 bool SpellingInvalid = false;
318 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
319 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
320
321 // We are no longer at the start of a statement.
322 isNewStatement = false;
323 }
324
325 // Ensure that the buffer is null-terminated.
326 Asm.push_back('\0');
327 Asm.pop_back();
328
329 assert(TokOffsets.size() == AsmToks.size());
330 return false;
331}
332
Denis Zobnin628b0222016-04-21 10:59:18 +0000333/// isTypeQualifier - Return true if the current token could be the
334/// start of a type-qualifier-list.
335static bool isTypeQualifier(const Token &Tok) {
336 switch (Tok.getKind()) {
337 default: return false;
338 // type-qualifier
339 case tok::kw_const:
340 case tok::kw_volatile:
341 case tok::kw_restrict:
342 case tok::kw___private:
343 case tok::kw___local:
344 case tok::kw___global:
345 case tok::kw___constant:
346 case tok::kw___generic:
347 case tok::kw___read_only:
348 case tok::kw___read_write:
349 case tok::kw___write_only:
350 return true;
351 }
352}
353
354// Determine if this is a GCC-style asm statement.
355static bool isGCCAsmStatement(const Token &TokAfterAsm) {
356 return TokAfterAsm.is(tok::l_paren) || TokAfterAsm.is(tok::kw_goto) ||
357 isTypeQualifier(TokAfterAsm);
358}
359
Alp Toker1b935a82014-06-08 05:40:04 +0000360/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
361/// this routine is called to collect the tokens for an MS asm statement.
362///
363/// [MS] ms-asm-statement:
364/// ms-asm-block
365/// ms-asm-block ms-asm-statement
366///
367/// [MS] ms-asm-block:
368/// '__asm' ms-asm-line '\n'
369/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
370///
371/// [MS] ms-asm-instruction-block
372/// ms-asm-line
373/// ms-asm-line '\n' ms-asm-instruction-block
374///
375StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
376 SourceManager &SrcMgr = PP.getSourceManager();
377 SourceLocation EndLoc = AsmLoc;
378 SmallVector<Token, 4> AsmToks;
379
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000380 bool SingleLineMode = true;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000381 unsigned BraceNesting = 0;
Ehsan Akhgari833ed942014-07-15 02:21:41 +0000382 unsigned short savedBraceCount = BraceCount;
Alp Toker1b935a82014-06-08 05:40:04 +0000383 bool InAsmComment = false;
384 FileID FID;
385 unsigned LineNo = 0;
386 unsigned NumTokensRead = 0;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000387 SmallVector<SourceLocation, 4> LBraceLocs;
388 bool SkippedStartOfLine = false;
Alp Toker1b935a82014-06-08 05:40:04 +0000389
390 if (Tok.is(tok::l_brace)) {
391 // Braced inline asm: consume the opening brace.
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000392 SingleLineMode = false;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000393 BraceNesting = 1;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000394 EndLoc = ConsumeBrace();
395 LBraceLocs.push_back(EndLoc);
Alp Toker1b935a82014-06-08 05:40:04 +0000396 ++NumTokensRead;
397 } else {
398 // Single-line inline asm; compute which line it is on.
399 std::pair<FileID, unsigned> ExpAsmLoc =
400 SrcMgr.getDecomposedExpansionLoc(EndLoc);
401 FID = ExpAsmLoc.first;
402 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000403 LBraceLocs.push_back(SourceLocation());
Alp Toker1b935a82014-06-08 05:40:04 +0000404 }
405
406 SourceLocation TokLoc = Tok.getLocation();
407 do {
408 // If we hit EOF, we're done, period.
409 if (isEofOrEom())
410 break;
411
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000412 if (!InAsmComment && Tok.is(tok::l_brace)) {
413 // Consume the opening brace.
414 SkippedStartOfLine = Tok.isAtStartOfLine();
Marina Yatsina5f776792016-03-07 18:10:25 +0000415 AsmToks.push_back(Tok);
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000416 EndLoc = ConsumeBrace();
417 BraceNesting++;
418 LBraceLocs.push_back(EndLoc);
419 TokLoc = Tok.getLocation();
420 ++NumTokensRead;
421 continue;
422 } else if (!InAsmComment && Tok.is(tok::semi)) {
Alp Toker1b935a82014-06-08 05:40:04 +0000423 // A semicolon in an asm is the start of a comment.
424 InAsmComment = true;
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000425 if (!SingleLineMode) {
Alp Toker1b935a82014-06-08 05:40:04 +0000426 // Compute which line the comment is on.
427 std::pair<FileID, unsigned> ExpSemiLoc =
428 SrcMgr.getDecomposedExpansionLoc(TokLoc);
429 FID = ExpSemiLoc.first;
430 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
431 }
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000432 } else if (SingleLineMode || InAsmComment) {
Alp Toker1b935a82014-06-08 05:40:04 +0000433 // If end-of-line is significant, check whether this token is on a
434 // new line.
435 std::pair<FileID, unsigned> ExpLoc =
436 SrcMgr.getDecomposedExpansionLoc(TokLoc);
437 if (ExpLoc.first != FID ||
438 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000439 // If this is a single-line __asm, we're done, except if the next
Denis Zobnin628b0222016-04-21 10:59:18 +0000440 // line is MS-style asm too, in which case we finish a comment
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000441 // if needed and then keep processing the next line as a single
442 // line __asm.
443 bool isAsm = Tok.is(tok::kw_asm);
Denis Zobnin628b0222016-04-21 10:59:18 +0000444 if (SingleLineMode && (!isAsm || isGCCAsmStatement(NextToken())))
Alp Toker1b935a82014-06-08 05:40:04 +0000445 break;
446 // We're no longer in a comment.
447 InAsmComment = false;
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000448 if (isAsm) {
Simon Pilgrim2c518802017-03-30 14:13:19 +0000449 // If this is a new __asm {} block we want to process it separately
Marina Yatsina146d2ec2016-02-23 08:53:45 +0000450 // from the single-line __asm statements
451 if (PP.LookAhead(0).is(tok::l_brace))
452 break;
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000453 LineNo = SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second);
454 SkippedStartOfLine = Tok.isAtStartOfLine();
Coby Tayreec0fb36f2017-02-05 10:23:06 +0000455 } else if (Tok.is(tok::semi)) {
456 // A multi-line asm-statement, where next line is a comment
457 InAsmComment = true;
458 FID = ExpLoc.first;
459 LineNo = SrcMgr.getLineNumber(FID, ExpLoc.second);
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000460 }
Alp Toker1b935a82014-06-08 05:40:04 +0000461 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000462 // In MSVC mode, braces only participate in brace matching and
463 // separating the asm statements. This is an intentional
464 // departure from the Apple gcc behavior.
465 if (!BraceNesting)
466 break;
Alp Toker1b935a82014-06-08 05:40:04 +0000467 }
468 }
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000469 if (!InAsmComment && BraceNesting && Tok.is(tok::r_brace) &&
470 BraceCount == (savedBraceCount + BraceNesting)) {
471 // Consume the closing brace.
472 SkippedStartOfLine = Tok.isAtStartOfLine();
Marina Yatsina5f776792016-03-07 18:10:25 +0000473 // Don't want to add the closing brace of the whole asm block
474 if (SingleLineMode || BraceNesting > 1) {
475 Tok.clearFlag(Token::LeadingSpace);
476 AsmToks.push_back(Tok);
477 }
Alp Toker1b935a82014-06-08 05:40:04 +0000478 EndLoc = ConsumeBrace();
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000479 BraceNesting--;
Nico Weber022e5072014-07-17 18:19:30 +0000480 // Finish if all of the opened braces in the inline asm section were
481 // consumed.
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000482 if (BraceNesting == 0 && !SingleLineMode)
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000483 break;
484 else {
485 LBraceLocs.pop_back();
486 TokLoc = Tok.getLocation();
487 ++NumTokensRead;
488 continue;
489 }
Alp Toker1b935a82014-06-08 05:40:04 +0000490 }
491
492 // Consume the next token; make sure we don't modify the brace count etc.
493 // if we are in a comment.
494 EndLoc = TokLoc;
495 if (InAsmComment)
496 PP.Lex(Tok);
497 else {
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000498 // Set the token as the start of line if we skipped the original start
499 // of line token in case it was a nested brace.
500 if (SkippedStartOfLine)
501 Tok.setFlag(Token::StartOfLine);
Alp Toker1b935a82014-06-08 05:40:04 +0000502 AsmToks.push_back(Tok);
503 ConsumeAnyToken();
504 }
505 TokLoc = Tok.getLocation();
506 ++NumTokensRead;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000507 SkippedStartOfLine = false;
Alp Toker1b935a82014-06-08 05:40:04 +0000508 } while (1);
509
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000510 if (BraceNesting && BraceCount != savedBraceCount) {
Alp Toker1b935a82014-06-08 05:40:04 +0000511 // __asm without closing brace (this can happen at EOF).
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000512 for (unsigned i = 0; i < BraceNesting; ++i) {
513 Diag(Tok, diag::err_expected) << tok::r_brace;
514 Diag(LBraceLocs.back(), diag::note_matching) << tok::l_brace;
515 LBraceLocs.pop_back();
516 }
Alp Toker1b935a82014-06-08 05:40:04 +0000517 return StmtError();
518 } else if (NumTokensRead == 0) {
519 // Empty __asm.
520 Diag(Tok, diag::err_expected) << tok::l_brace;
521 return StmtError();
522 }
523
524 // Okay, prepare to use MC to parse the assembly.
525 SmallVector<StringRef, 4> ConstraintRefs;
526 SmallVector<Expr *, 4> Exprs;
527 SmallVector<StringRef, 4> ClobberRefs;
528
529 // We need an actual supported target.
530 const llvm::Triple &TheTriple = Actions.Context.getTargetInfo().getTriple();
531 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
532 const std::string &TT = TheTriple.getTriple();
533 const llvm::Target *TheTarget = nullptr;
534 bool UnsupportedArch =
535 (ArchTy != llvm::Triple::x86 && ArchTy != llvm::Triple::x86_64);
536 if (UnsupportedArch) {
537 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
538 } else {
539 std::string Error;
540 TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
541 if (!TheTarget)
542 Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
543 }
544
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000545 assert(!LBraceLocs.empty() && "Should have at least one location here");
546
Alp Toker1b935a82014-06-08 05:40:04 +0000547 // If we don't support assembly, or the assembly is empty, we don't
548 // need to instantiate the AsmParser, etc.
549 if (!TheTarget || AsmToks.empty()) {
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000550 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, StringRef(),
Alp Toker1b935a82014-06-08 05:40:04 +0000551 /*NumOutputs*/ 0, /*NumInputs*/ 0,
552 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
553 }
554
555 // Expand the tokens into a string buffer.
556 SmallString<512> AsmString;
557 SmallVector<unsigned, 8> TokOffsets;
558 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
559 return StmtError();
560
Benjamin Kramer24952ce2017-10-22 20:16:28 +0000561 const TargetOptions &TO = Actions.Context.getTargetInfo().getTargetOpts();
Marina Yatsina41c45fa2016-02-03 11:32:08 +0000562 std::string FeaturesStr =
563 llvm::join(TO.Features.begin(), TO.Features.end(), ",");
564
Alp Toker1b935a82014-06-08 05:40:04 +0000565 std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
566 std::unique_ptr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
567 // Get the instruction descriptor.
568 std::unique_ptr<llvm::MCInstrInfo> MII(TheTarget->createMCInstrInfo());
569 std::unique_ptr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
570 std::unique_ptr<llvm::MCSubtargetInfo> STI(
Marina Yatsina41c45fa2016-02-03 11:32:08 +0000571 TheTarget->createMCSubtargetInfo(TT, TO.CPU, FeaturesStr));
Alp Toker1b935a82014-06-08 05:40:04 +0000572
573 llvm::SourceMgr TempSrcMgr;
574 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
Rafael Espindola2e8a7d32017-08-02 20:32:35 +0000575 MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, Ctx);
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000576 std::unique_ptr<llvm::MemoryBuffer> Buffer =
577 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
Alp Toker1b935a82014-06-08 05:40:04 +0000578
579 // Tell SrcMgr about this buffer, which is what the parser will pick up.
David Blaikie9e095d92014-08-21 21:01:00 +0000580 TempSrcMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());
Alp Toker1b935a82014-06-08 05:40:04 +0000581
582 std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
583 std::unique_ptr<llvm::MCAsmParser> Parser(
584 createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
585
586 // FIXME: init MCOptions from sanitizer flags here.
587 llvm::MCTargetOptions MCOptions;
588 std::unique_ptr<llvm::MCTargetAsmParser> TargetParser(
589 TheTarget->createMCAsmParser(*STI, *Parser, *MII, MCOptions));
590
Daniel Sanders50f17232015-09-15 16:17:27 +0000591 std::unique_ptr<llvm::MCInstPrinter> IP(
592 TheTarget->createMCInstPrinter(llvm::Triple(TT), 1, *MAI, *MII, *MRI));
Alp Toker1b935a82014-06-08 05:40:04 +0000593
594 // Change to the Intel dialect.
595 Parser->setAssemblerDialect(1);
596 Parser->setTargetParser(*TargetParser.get());
597 Parser->setParsingInlineAsm(true);
598 TargetParser->setParsingInlineAsm(true);
599
600 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString, AsmToks,
601 TokOffsets);
602 TargetParser->setSemaCallback(&Callback);
603 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
604 &Callback);
605
606 unsigned NumOutputs;
607 unsigned NumInputs;
608 std::string AsmStringIR;
609 SmallVector<std::pair<void *, bool>, 4> OpExprs;
610 SmallVector<std::string, 4> Constraints;
611 SmallVector<std::string, 4> Clobbers;
612 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR, NumOutputs,
613 NumInputs, OpExprs, Constraints, Clobbers,
614 MII.get(), IP.get(), Callback))
615 return StmtError();
616
Reid Klecknerfb9f6472017-02-14 21:38:17 +0000617 // Filter out "fpsw" and "mxcsr". They aren't valid GCC asm clobber
618 // constraints. Clang always adds fpsr to the clobber list anyway.
619 llvm::erase_if(Clobbers, [](const std::string &C) {
620 return C == "fpsw" || C == "mxcsr";
621 });
Alp Toker1b935a82014-06-08 05:40:04 +0000622
623 // Build the vector of clobber StringRefs.
David Majnemer05c69862014-06-23 02:16:41 +0000624 ClobberRefs.insert(ClobberRefs.end(), Clobbers.begin(), Clobbers.end());
Alp Toker1b935a82014-06-08 05:40:04 +0000625
626 // Recast the void pointers and build the vector of constraint StringRefs.
627 unsigned NumExprs = NumOutputs + NumInputs;
628 ConstraintRefs.resize(NumExprs);
629 Exprs.resize(NumExprs);
630 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
631 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
632 if (!OpExpr)
633 return StmtError();
634
635 // Need address of variable.
636 if (OpExprs[i].second)
637 OpExpr =
638 Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr).get();
639
640 ConstraintRefs[i] = StringRef(Constraints[i]);
641 Exprs[i] = OpExpr;
642 }
643
644 // FIXME: We should be passing source locations for better diagnostics.
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000645 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmStringIR,
Alp Toker1b935a82014-06-08 05:40:04 +0000646 NumOutputs, NumInputs, ConstraintRefs,
647 ClobberRefs, Exprs, EndLoc);
648}
649
650/// ParseAsmStatement - Parse a GNU extended asm statement.
651/// asm-statement:
652/// gnu-asm-statement
653/// ms-asm-statement
654///
655/// [GNU] gnu-asm-statement:
656/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
657///
658/// [GNU] asm-argument:
659/// asm-string-literal
660/// asm-string-literal ':' asm-operands[opt]
661/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
662/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
663/// ':' asm-clobbers
664///
665/// [GNU] asm-clobbers:
666/// asm-string-literal
667/// asm-clobbers ',' asm-string-literal
668///
669StmtResult Parser::ParseAsmStatement(bool &msAsm) {
670 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
671 SourceLocation AsmLoc = ConsumeToken();
672
Denis Zobnin628b0222016-04-21 10:59:18 +0000673 if (getLangOpts().AsmBlocks && !isGCCAsmStatement(Tok)) {
Alp Toker1b935a82014-06-08 05:40:04 +0000674 msAsm = true;
675 return ParseMicrosoftAsmStatement(AsmLoc);
676 }
Steven Wucb0d13f2015-01-16 23:05:28 +0000677
Alp Toker1b935a82014-06-08 05:40:04 +0000678 DeclSpec DS(AttrFactory);
679 SourceLocation Loc = Tok.getLocation();
Aaron Ballman08b06592014-07-22 12:44:22 +0000680 ParseTypeQualifierListOpt(DS, AR_VendorAttributesParsed);
Alp Toker1b935a82014-06-08 05:40:04 +0000681
682 // GNU asms accept, but warn, about type-qualifiers other than volatile.
683 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Richard Smith01d96982016-12-02 23:00:28 +0000684 Diag(Loc, diag::warn_asm_qualifier_ignored) << "const";
Alp Toker1b935a82014-06-08 05:40:04 +0000685 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith01d96982016-12-02 23:00:28 +0000686 Diag(Loc, diag::warn_asm_qualifier_ignored) << "restrict";
Alp Toker1b935a82014-06-08 05:40:04 +0000687 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
688 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
Richard Smith01d96982016-12-02 23:00:28 +0000689 Diag(Loc, diag::warn_asm_qualifier_ignored) << "_Atomic";
Alp Toker1b935a82014-06-08 05:40:04 +0000690
691 // Remember if this was a volatile asm.
692 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Denis Zobnin628b0222016-04-21 10:59:18 +0000693
694 // TODO: support "asm goto" constructs (PR#9295).
695 if (Tok.is(tok::kw_goto)) {
696 Diag(Tok, diag::err_asm_goto_not_supported_yet);
697 SkipUntil(tok::r_paren, StopAtSemi);
698 return StmtError();
699 }
700
Alp Toker1b935a82014-06-08 05:40:04 +0000701 if (Tok.isNot(tok::l_paren)) {
702 Diag(Tok, diag::err_expected_lparen_after) << "asm";
703 SkipUntil(tok::r_paren, StopAtSemi);
704 return StmtError();
705 }
706 BalancedDelimiterTracker T(*this, tok::l_paren);
707 T.consumeOpen();
708
709 ExprResult AsmString(ParseAsmStringLiteral());
Steven Wu18bbe192015-05-12 00:16:37 +0000710
711 // Check if GNU-style InlineAsm is disabled.
712 // Error on anything other than empty string.
713 if (!(getLangOpts().GNUAsm || AsmString.isInvalid())) {
714 const auto *SL = cast<StringLiteral>(AsmString.get());
715 if (!SL->getString().trim().empty())
716 Diag(Loc, diag::err_gnu_inline_asm_disabled);
717 }
718
Alp Toker1b935a82014-06-08 05:40:04 +0000719 if (AsmString.isInvalid()) {
720 // Consume up to and including the closing paren.
721 T.skipToEnd();
722 return StmtError();
723 }
724
725 SmallVector<IdentifierInfo *, 4> Names;
726 ExprVector Constraints;
727 ExprVector Exprs;
728 ExprVector Clobbers;
729
730 if (Tok.is(tok::r_paren)) {
731 // We have a simple asm expression like 'asm("foo")'.
732 T.consumeClose();
733 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
734 /*NumOutputs*/ 0, /*NumInputs*/ 0, nullptr,
735 Constraints, Exprs, AsmString.get(),
736 Clobbers, T.getCloseLocation());
737 }
738
739 // Parse Outputs, if present.
740 bool AteExtraColon = false;
741 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
742 // In C++ mode, parse "::" like ": :".
743 AteExtraColon = Tok.is(tok::coloncolon);
744 ConsumeToken();
745
746 if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
747 return StmtError();
748 }
749
750 unsigned NumOutputs = Names.size();
751
752 // Parse Inputs, if present.
753 if (AteExtraColon || Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
754 // In C++ mode, parse "::" like ": :".
755 if (AteExtraColon)
756 AteExtraColon = false;
757 else {
758 AteExtraColon = Tok.is(tok::coloncolon);
759 ConsumeToken();
760 }
761
762 if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
763 return StmtError();
764 }
765
766 assert(Names.size() == Constraints.size() &&
767 Constraints.size() == Exprs.size() && "Input operand size mismatch!");
768
769 unsigned NumInputs = Names.size() - NumOutputs;
770
771 // Parse the clobbers, if present.
772 if (AteExtraColon || Tok.is(tok::colon)) {
773 if (!AteExtraColon)
774 ConsumeToken();
775
776 // Parse the asm-string list for clobbers if present.
777 if (Tok.isNot(tok::r_paren)) {
778 while (1) {
779 ExprResult Clobber(ParseAsmStringLiteral());
780
781 if (Clobber.isInvalid())
782 break;
783
784 Clobbers.push_back(Clobber.get());
785
786 if (!TryConsumeToken(tok::comma))
787 break;
788 }
789 }
790 }
791
792 T.consumeClose();
793 return Actions.ActOnGCCAsmStmt(
794 AsmLoc, false, isVolatile, NumOutputs, NumInputs, Names.data(),
795 Constraints, Exprs, AsmString.get(), Clobbers, T.getCloseLocation());
796}
797
798/// ParseAsmOperands - Parse the asm-operands production as used by
799/// asm-statement, assuming the leading ':' token was eaten.
800///
801/// [GNU] asm-operands:
802/// asm-operand
803/// asm-operands ',' asm-operand
804///
805/// [GNU] asm-operand:
806/// asm-string-literal '(' expression ')'
807/// '[' identifier ']' asm-string-literal '(' expression ')'
808///
809//
810// FIXME: Avoid unnecessary std::string trashing.
811bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
812 SmallVectorImpl<Expr *> &Constraints,
813 SmallVectorImpl<Expr *> &Exprs) {
814 // 'asm-operands' isn't present?
815 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
816 return false;
817
818 while (1) {
819 // Read the [id] if present.
820 if (Tok.is(tok::l_square)) {
821 BalancedDelimiterTracker T(*this, tok::l_square);
822 T.consumeOpen();
823
824 if (Tok.isNot(tok::identifier)) {
825 Diag(Tok, diag::err_expected) << tok::identifier;
826 SkipUntil(tok::r_paren, StopAtSemi);
827 return true;
828 }
829
830 IdentifierInfo *II = Tok.getIdentifierInfo();
831 ConsumeToken();
832
833 Names.push_back(II);
834 T.consumeClose();
835 } else
836 Names.push_back(nullptr);
837
838 ExprResult Constraint(ParseAsmStringLiteral());
839 if (Constraint.isInvalid()) {
840 SkipUntil(tok::r_paren, StopAtSemi);
841 return true;
842 }
843 Constraints.push_back(Constraint.get());
844
845 if (Tok.isNot(tok::l_paren)) {
846 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
847 SkipUntil(tok::r_paren, StopAtSemi);
848 return true;
849 }
850
851 // Read the parenthesized expression.
852 BalancedDelimiterTracker T(*this, tok::l_paren);
853 T.consumeOpen();
Kaelyn Takata15867822014-11-21 18:48:04 +0000854 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
Alp Toker1b935a82014-06-08 05:40:04 +0000855 T.consumeClose();
856 if (Res.isInvalid()) {
857 SkipUntil(tok::r_paren, StopAtSemi);
858 return true;
859 }
860 Exprs.push_back(Res.get());
861 // Eat the comma and continue parsing if it exists.
862 if (!TryConsumeToken(tok::comma))
863 return false;
864 }
865}