blob: d3281393f92369c3dfd32e84da18a811e824eb02 [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"
15#include "RAIIObjectsForParser.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/TargetInfo.h"
19#include "llvm/ADT/SmallString.h"
20#include "llvm/MC/MCAsmInfo.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCInstPrinter.h"
23#include "llvm/MC/MCInstrInfo.h"
24#include "llvm/MC/MCObjectFileInfo.h"
25#include "llvm/MC/MCParser/MCAsmParser.h"
26#include "llvm/MC/MCRegisterInfo.h"
27#include "llvm/MC/MCStreamer.h"
28#include "llvm/MC/MCSubtargetInfo.h"
29#include "llvm/MC/MCTargetAsmParser.h"
30#include "llvm/MC/MCTargetOptions.h"
31#include "llvm/Support/SourceMgr.h"
32#include "llvm/Support/TargetRegistry.h"
33#include "llvm/Support/TargetSelect.h"
34using namespace clang;
35
36namespace {
37class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
38 Parser &TheParser;
39 SourceLocation AsmLoc;
40 StringRef AsmString;
41
42 /// The tokens we streamed into AsmString and handed off to MC.
43 ArrayRef<Token> AsmToks;
44
45 /// The offset of each token in AsmToks within AsmString.
46 ArrayRef<unsigned> AsmTokOffsets;
47
48public:
49 ClangAsmParserCallback(Parser &P, SourceLocation Loc, StringRef AsmString,
50 ArrayRef<Token> Toks, ArrayRef<unsigned> Offsets)
51 : TheParser(P), AsmLoc(Loc), AsmString(AsmString), AsmToks(Toks),
52 AsmTokOffsets(Offsets) {
53 assert(AsmToks.size() == AsmTokOffsets.size());
54 }
55
56 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
57 llvm::InlineAsmIdentifierInfo &Info,
58 bool IsUnevaluatedContext) override {
59 // Collect the desired tokens.
60 SmallVector<Token, 16> LineToks;
61 const Token *FirstOrigToken = nullptr;
62 findTokensForString(LineBuf, LineToks, FirstOrigToken);
63
64 unsigned NumConsumedToks;
65 ExprResult Result = TheParser.ParseMSAsmIdentifier(
66 LineToks, NumConsumedToks, &Info, IsUnevaluatedContext);
67
68 // If we consumed the entire line, tell MC that.
69 // Also do this if we consumed nothing as a way of reporting failure.
70 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
71 // By not modifying LineBuf, we're implicitly consuming it all.
72
73 // Otherwise, consume up to the original tokens.
74 } else {
75 assert(FirstOrigToken && "not using original tokens?");
76
77 // Since we're using original tokens, apply that offset.
78 assert(FirstOrigToken[NumConsumedToks].getLocation() ==
79 LineToks[NumConsumedToks].getLocation());
80 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
81 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
82
83 // The total length we've consumed is the relative offset
84 // of the last token we consumed plus its length.
85 unsigned TotalOffset =
86 (AsmTokOffsets[LastIndex] + AsmToks[LastIndex].getLength() -
87 AsmTokOffsets[FirstIndex]);
88 LineBuf = LineBuf.substr(0, TotalOffset);
89 }
90
91 // Initialize the "decl" with the lookup result.
92 Info.OpDecl = static_cast<void *>(Result.get());
93 return Info.OpDecl;
94 }
95
Ehsan Akhgari31097582014-09-22 02:21:54 +000096 StringRef LookupInlineAsmLabel(StringRef Identifier, llvm::SourceMgr &LSM,
97 llvm::SMLoc Location,
98 bool Create) override {
99 SourceLocation Loc = translateLocation(LSM, Location);
100 LabelDecl *Label =
101 TheParser.getActions().GetOrCreateMSAsmLabel(Identifier, Loc, Create);
102 return Label->getMSAsmLabel();
103 }
104
Alp Toker1b935a82014-06-08 05:40:04 +0000105 bool LookupInlineAsmField(StringRef Base, StringRef Member,
106 unsigned &Offset) override {
107 return TheParser.getActions().LookupInlineAsmField(Base, Member, Offset,
108 AsmLoc);
109 }
110
111 static void DiagHandlerCallback(const llvm::SMDiagnostic &D, void *Context) {
112 ((ClangAsmParserCallback *)Context)->handleDiagnostic(D);
113 }
114
115private:
116 /// Collect the appropriate tokens for the given string.
117 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
118 const Token *&FirstOrigToken) const {
119 // For now, assert that the string we're working with is a substring
120 // of what we gave to MC. This lets us use the original tokens.
121 assert(!std::less<const char *>()(Str.begin(), AsmString.begin()) &&
122 !std::less<const char *>()(AsmString.end(), Str.end()));
123
124 // Try to find a token whose offset matches the first token.
125 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
126 const unsigned *FirstTokOffset = std::lower_bound(
127 AsmTokOffsets.begin(), AsmTokOffsets.end(), FirstCharOffset);
128
129 // For now, assert that the start of the string exactly
130 // corresponds to the start of a token.
131 assert(*FirstTokOffset == FirstCharOffset);
132
133 // Use all the original tokens for this line. (We assume the
134 // end of the line corresponds cleanly to a token break.)
135 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
136 FirstOrigToken = &AsmToks[FirstTokIndex];
137 unsigned LastCharOffset = Str.end() - AsmString.begin();
138 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
139 if (AsmTokOffsets[i] >= LastCharOffset)
140 break;
141 TempToks.push_back(AsmToks[i]);
142 }
143 }
144
Ehsan Akhgari31097582014-09-22 02:21:54 +0000145 SourceLocation translateLocation(const llvm::SourceMgr &LSM, llvm::SMLoc SMLoc) {
Alp Toker1b935a82014-06-08 05:40:04 +0000146 // Compute an offset into the inline asm buffer.
147 // FIXME: This isn't right if .macro is involved (but hopefully, no
148 // real-world code does that).
Alp Toker1b935a82014-06-08 05:40:04 +0000149 const llvm::MemoryBuffer *LBuf =
Ehsan Akhgari31097582014-09-22 02:21:54 +0000150 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(SMLoc));
151 unsigned Offset = SMLoc.getPointer() - LBuf->getBufferStart();
Alp Toker1b935a82014-06-08 05:40:04 +0000152
153 // Figure out which token that offset points into.
154 const unsigned *TokOffsetPtr =
155 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
156 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
157 unsigned TokOffset = *TokOffsetPtr;
158
159 // If we come up with an answer which seems sane, use it; otherwise,
160 // just point at the __asm keyword.
161 // FIXME: Assert the answer is sane once we handle .macro correctly.
162 SourceLocation Loc = AsmLoc;
163 if (TokIndex < AsmToks.size()) {
164 const Token &Tok = AsmToks[TokIndex];
165 Loc = Tok.getLocation();
166 Loc = Loc.getLocWithOffset(Offset - TokOffset);
167 }
Ehsan Akhgari31097582014-09-22 02:21:54 +0000168 return Loc;
169 }
170
171 void handleDiagnostic(const llvm::SMDiagnostic &D) {
172 const llvm::SourceMgr &LSM = *D.getSourceMgr();
173 SourceLocation Loc = translateLocation(LSM, D.getLoc());
Alp Toker1b935a82014-06-08 05:40:04 +0000174 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage();
175 }
176};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000177}
Alp Toker1b935a82014-06-08 05:40:04 +0000178
179/// Parse an identifier in an MS-style inline assembly block.
180///
181/// \param CastInfo - a void* so that we don't have to teach Parser.h
182/// about the actual type.
183ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
184 unsigned &NumLineToksConsumed,
185 void *CastInfo,
186 bool IsUnevaluatedContext) {
187 llvm::InlineAsmIdentifierInfo &Info =
188 *(llvm::InlineAsmIdentifierInfo *)CastInfo;
189
190 // Push a fake token on the end so that we don't overrun the token
191 // stream. We use ';' because it expression-parsing should never
192 // overrun it.
193 const tok::TokenKind EndOfStream = tok::semi;
194 Token EndOfStreamTok;
195 EndOfStreamTok.startToken();
196 EndOfStreamTok.setKind(EndOfStream);
197 LineToks.push_back(EndOfStreamTok);
198
199 // Also copy the current token over.
200 LineToks.push_back(Tok);
201
202 PP.EnterTokenStream(LineToks.begin(), LineToks.size(),
203 /*disable macros*/ true,
204 /*owns tokens*/ false);
205
206 // Clear the current token and advance to the first token in LineToks.
207 ConsumeAnyToken();
208
209 // Parse an optional scope-specifier if we're in C++.
210 CXXScopeSpec SS;
211 if (getLangOpts().CPlusPlus) {
212 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
213 }
214
215 // Require an identifier here.
216 SourceLocation TemplateKWLoc;
217 UnqualifiedId Id;
218 bool Invalid =
219 ParseUnqualifiedId(SS,
220 /*EnteringContext=*/false,
221 /*AllowDestructorName=*/false,
222 /*AllowConstructorName=*/false,
223 /*ObjectType=*/ParsedType(), TemplateKWLoc, Id);
224
Reid Kleckner14e96b42015-08-26 21:57:20 +0000225 // Perform the lookup.
226 ExprResult Result = Actions.LookupInlineAsmIdentifier(
227 SS, TemplateKWLoc, Id, Info, IsUnevaluatedContext);
228
229 // While the next two tokens are 'period' 'identifier', repeatedly parse it as
230 // a field access. We have to avoid consuming assembler directives that look
231 // like '.' 'else'.
232 while (Result.isUsable() && Tok.is(tok::period)) {
233 Token IdTok = PP.LookAhead(0);
234 if (IdTok.isNot(tok::identifier))
235 break;
236 ConsumeToken(); // Consume the period.
237 IdentifierInfo *Id = Tok.getIdentifierInfo();
238 ConsumeToken(); // Consume the identifier.
239 unsigned OffsetUnused;
240 Result = Actions.LookupInlineAsmVarDeclField(
241 Result.get(), Id->getName(), OffsetUnused, Info, Tok.getLocation());
242 }
243
Alp Toker1b935a82014-06-08 05:40:04 +0000244 // Figure out how many tokens we are into LineToks.
245 unsigned LineIndex = 0;
246 if (Tok.is(EndOfStream)) {
247 LineIndex = LineToks.size() - 2;
248 } else {
249 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
250 LineIndex++;
251 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
252 }
253 }
254
255 // If we've run into the poison token we inserted before, or there
256 // was a parsing error, then claim the entire line.
257 if (Invalid || Tok.is(EndOfStream)) {
258 NumLineToksConsumed = LineToks.size() - 2;
259 } else {
260 // Otherwise, claim up to the start of the next token.
261 NumLineToksConsumed = LineIndex;
262 }
263
264 // Finally, restore the old parsing state by consuming all the tokens we
265 // staged before, implicitly killing off the token-lexer we pushed.
266 for (unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; ++i) {
267 ConsumeAnyToken();
268 }
269 assert(Tok.is(EndOfStream));
270 ConsumeToken();
271
272 // Leave LineToks in its original state.
273 LineToks.pop_back();
274 LineToks.pop_back();
275
Reid Kleckner14e96b42015-08-26 21:57:20 +0000276 return Result;
Alp Toker1b935a82014-06-08 05:40:04 +0000277}
278
279/// Turn a sequence of our tokens back into a string that we can hand
280/// to the MC asm parser.
281static bool buildMSAsmString(Preprocessor &PP, SourceLocation AsmLoc,
282 ArrayRef<Token> AsmToks,
283 SmallVectorImpl<unsigned> &TokOffsets,
284 SmallString<512> &Asm) {
285 assert(!AsmToks.empty() && "Didn't expect an empty AsmToks!");
286
287 // Is this the start of a new assembly statement?
288 bool isNewStatement = true;
289
290 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
291 const Token &Tok = AsmToks[i];
292
293 // Start each new statement with a newline and a tab.
294 if (!isNewStatement && (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
295 Asm += "\n\t";
296 isNewStatement = true;
297 }
298
299 // Preserve the existence of leading whitespace except at the
300 // start of a statement.
301 if (!isNewStatement && Tok.hasLeadingSpace())
302 Asm += ' ';
303
304 // Remember the offset of this token.
305 TokOffsets.push_back(Asm.size());
306
307 // Don't actually write '__asm' into the assembly stream.
308 if (Tok.is(tok::kw_asm)) {
309 // Complain about __asm at the end of the stream.
310 if (i + 1 == e) {
311 PP.Diag(AsmLoc, diag::err_asm_empty);
312 return true;
313 }
314
315 continue;
316 }
317
318 // Append the spelling of the token.
319 SmallString<32> SpellingBuffer;
320 bool SpellingInvalid = false;
321 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
322 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
323
324 // We are no longer at the start of a statement.
325 isNewStatement = false;
326 }
327
328 // Ensure that the buffer is null-terminated.
329 Asm.push_back('\0');
330 Asm.pop_back();
331
332 assert(TokOffsets.size() == AsmToks.size());
333 return false;
334}
335
336/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
337/// this routine is called to collect the tokens for an MS asm statement.
338///
339/// [MS] ms-asm-statement:
340/// ms-asm-block
341/// ms-asm-block ms-asm-statement
342///
343/// [MS] ms-asm-block:
344/// '__asm' ms-asm-line '\n'
345/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
346///
347/// [MS] ms-asm-instruction-block
348/// ms-asm-line
349/// ms-asm-line '\n' ms-asm-instruction-block
350///
351StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
352 SourceManager &SrcMgr = PP.getSourceManager();
353 SourceLocation EndLoc = AsmLoc;
354 SmallVector<Token, 4> AsmToks;
355
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000356 bool SingleLineMode = true;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000357 unsigned BraceNesting = 0;
Ehsan Akhgari833ed942014-07-15 02:21:41 +0000358 unsigned short savedBraceCount = BraceCount;
Alp Toker1b935a82014-06-08 05:40:04 +0000359 bool InAsmComment = false;
360 FileID FID;
361 unsigned LineNo = 0;
362 unsigned NumTokensRead = 0;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000363 SmallVector<SourceLocation, 4> LBraceLocs;
364 bool SkippedStartOfLine = false;
Alp Toker1b935a82014-06-08 05:40:04 +0000365
366 if (Tok.is(tok::l_brace)) {
367 // Braced inline asm: consume the opening brace.
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000368 SingleLineMode = false;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000369 BraceNesting = 1;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000370 EndLoc = ConsumeBrace();
371 LBraceLocs.push_back(EndLoc);
Alp Toker1b935a82014-06-08 05:40:04 +0000372 ++NumTokensRead;
373 } else {
374 // Single-line inline asm; compute which line it is on.
375 std::pair<FileID, unsigned> ExpAsmLoc =
376 SrcMgr.getDecomposedExpansionLoc(EndLoc);
377 FID = ExpAsmLoc.first;
378 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000379 LBraceLocs.push_back(SourceLocation());
Alp Toker1b935a82014-06-08 05:40:04 +0000380 }
381
382 SourceLocation TokLoc = Tok.getLocation();
383 do {
384 // If we hit EOF, we're done, period.
385 if (isEofOrEom())
386 break;
387
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000388 if (!InAsmComment && Tok.is(tok::l_brace)) {
389 // Consume the opening brace.
390 SkippedStartOfLine = Tok.isAtStartOfLine();
391 EndLoc = ConsumeBrace();
392 BraceNesting++;
393 LBraceLocs.push_back(EndLoc);
394 TokLoc = Tok.getLocation();
395 ++NumTokensRead;
396 continue;
397 } else if (!InAsmComment && Tok.is(tok::semi)) {
Alp Toker1b935a82014-06-08 05:40:04 +0000398 // A semicolon in an asm is the start of a comment.
399 InAsmComment = true;
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000400 if (!SingleLineMode) {
Alp Toker1b935a82014-06-08 05:40:04 +0000401 // Compute which line the comment is on.
402 std::pair<FileID, unsigned> ExpSemiLoc =
403 SrcMgr.getDecomposedExpansionLoc(TokLoc);
404 FID = ExpSemiLoc.first;
405 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
406 }
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000407 } else if (SingleLineMode || InAsmComment) {
Alp Toker1b935a82014-06-08 05:40:04 +0000408 // If end-of-line is significant, check whether this token is on a
409 // new line.
410 std::pair<FileID, unsigned> ExpLoc =
411 SrcMgr.getDecomposedExpansionLoc(TokLoc);
412 if (ExpLoc.first != FID ||
413 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000414 // If this is a single-line __asm, we're done, except if the next
415 // line begins with an __asm too, in which case we finish a comment
416 // if needed and then keep processing the next line as a single
417 // line __asm.
418 bool isAsm = Tok.is(tok::kw_asm);
419 if (SingleLineMode && !isAsm)
Alp Toker1b935a82014-06-08 05:40:04 +0000420 break;
421 // We're no longer in a comment.
422 InAsmComment = false;
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000423 if (isAsm) {
424 LineNo = SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second);
425 SkippedStartOfLine = Tok.isAtStartOfLine();
426 }
Alp Toker1b935a82014-06-08 05:40:04 +0000427 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000428 // In MSVC mode, braces only participate in brace matching and
429 // separating the asm statements. This is an intentional
430 // departure from the Apple gcc behavior.
431 if (!BraceNesting)
432 break;
Alp Toker1b935a82014-06-08 05:40:04 +0000433 }
434 }
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000435 if (!InAsmComment && BraceNesting && Tok.is(tok::r_brace) &&
436 BraceCount == (savedBraceCount + BraceNesting)) {
437 // Consume the closing brace.
438 SkippedStartOfLine = Tok.isAtStartOfLine();
Alp Toker1b935a82014-06-08 05:40:04 +0000439 EndLoc = ConsumeBrace();
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000440 BraceNesting--;
Nico Weber022e5072014-07-17 18:19:30 +0000441 // Finish if all of the opened braces in the inline asm section were
442 // consumed.
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000443 if (BraceNesting == 0 && !SingleLineMode)
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000444 break;
445 else {
446 LBraceLocs.pop_back();
447 TokLoc = Tok.getLocation();
448 ++NumTokensRead;
449 continue;
450 }
Alp Toker1b935a82014-06-08 05:40:04 +0000451 }
452
453 // Consume the next token; make sure we don't modify the brace count etc.
454 // if we are in a comment.
455 EndLoc = TokLoc;
456 if (InAsmComment)
457 PP.Lex(Tok);
458 else {
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000459 // Set the token as the start of line if we skipped the original start
460 // of line token in case it was a nested brace.
461 if (SkippedStartOfLine)
462 Tok.setFlag(Token::StartOfLine);
Alp Toker1b935a82014-06-08 05:40:04 +0000463 AsmToks.push_back(Tok);
464 ConsumeAnyToken();
465 }
466 TokLoc = Tok.getLocation();
467 ++NumTokensRead;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000468 SkippedStartOfLine = false;
Alp Toker1b935a82014-06-08 05:40:04 +0000469 } while (1);
470
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000471 if (BraceNesting && BraceCount != savedBraceCount) {
Alp Toker1b935a82014-06-08 05:40:04 +0000472 // __asm without closing brace (this can happen at EOF).
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000473 for (unsigned i = 0; i < BraceNesting; ++i) {
474 Diag(Tok, diag::err_expected) << tok::r_brace;
475 Diag(LBraceLocs.back(), diag::note_matching) << tok::l_brace;
476 LBraceLocs.pop_back();
477 }
Alp Toker1b935a82014-06-08 05:40:04 +0000478 return StmtError();
479 } else if (NumTokensRead == 0) {
480 // Empty __asm.
481 Diag(Tok, diag::err_expected) << tok::l_brace;
482 return StmtError();
483 }
484
485 // Okay, prepare to use MC to parse the assembly.
486 SmallVector<StringRef, 4> ConstraintRefs;
487 SmallVector<Expr *, 4> Exprs;
488 SmallVector<StringRef, 4> ClobberRefs;
489
490 // We need an actual supported target.
491 const llvm::Triple &TheTriple = Actions.Context.getTargetInfo().getTriple();
492 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
493 const std::string &TT = TheTriple.getTriple();
494 const llvm::Target *TheTarget = nullptr;
495 bool UnsupportedArch =
496 (ArchTy != llvm::Triple::x86 && ArchTy != llvm::Triple::x86_64);
497 if (UnsupportedArch) {
498 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
499 } else {
500 std::string Error;
501 TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
502 if (!TheTarget)
503 Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
504 }
505
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000506 assert(!LBraceLocs.empty() && "Should have at least one location here");
507
Alp Toker1b935a82014-06-08 05:40:04 +0000508 // If we don't support assembly, or the assembly is empty, we don't
509 // need to instantiate the AsmParser, etc.
510 if (!TheTarget || AsmToks.empty()) {
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000511 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, StringRef(),
Alp Toker1b935a82014-06-08 05:40:04 +0000512 /*NumOutputs*/ 0, /*NumInputs*/ 0,
513 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
514 }
515
516 // Expand the tokens into a string buffer.
517 SmallString<512> AsmString;
518 SmallVector<unsigned, 8> TokOffsets;
519 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
520 return StmtError();
521
522 std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
523 std::unique_ptr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
524 // Get the instruction descriptor.
525 std::unique_ptr<llvm::MCInstrInfo> MII(TheTarget->createMCInstrInfo());
526 std::unique_ptr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
527 std::unique_ptr<llvm::MCSubtargetInfo> STI(
528 TheTarget->createMCSubtargetInfo(TT, "", ""));
529
530 llvm::SourceMgr TempSrcMgr;
531 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
Daniel Sanders8d8b13d2015-06-16 12:18:07 +0000532 MOFI->InitMCObjectFileInfo(TheTriple, llvm::Reloc::Default,
533 llvm::CodeModel::Default, Ctx);
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000534 std::unique_ptr<llvm::MemoryBuffer> Buffer =
535 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
Alp Toker1b935a82014-06-08 05:40:04 +0000536
537 // Tell SrcMgr about this buffer, which is what the parser will pick up.
David Blaikie9e095d92014-08-21 21:01:00 +0000538 TempSrcMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());
Alp Toker1b935a82014-06-08 05:40:04 +0000539
540 std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
541 std::unique_ptr<llvm::MCAsmParser> Parser(
542 createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
543
544 // FIXME: init MCOptions from sanitizer flags here.
545 llvm::MCTargetOptions MCOptions;
546 std::unique_ptr<llvm::MCTargetAsmParser> TargetParser(
547 TheTarget->createMCAsmParser(*STI, *Parser, *MII, MCOptions));
548
Daniel Sanders50f17232015-09-15 16:17:27 +0000549 std::unique_ptr<llvm::MCInstPrinter> IP(
550 TheTarget->createMCInstPrinter(llvm::Triple(TT), 1, *MAI, *MII, *MRI));
Alp Toker1b935a82014-06-08 05:40:04 +0000551
552 // Change to the Intel dialect.
553 Parser->setAssemblerDialect(1);
554 Parser->setTargetParser(*TargetParser.get());
555 Parser->setParsingInlineAsm(true);
556 TargetParser->setParsingInlineAsm(true);
557
558 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString, AsmToks,
559 TokOffsets);
560 TargetParser->setSemaCallback(&Callback);
561 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
562 &Callback);
563
564 unsigned NumOutputs;
565 unsigned NumInputs;
566 std::string AsmStringIR;
567 SmallVector<std::pair<void *, bool>, 4> OpExprs;
568 SmallVector<std::string, 4> Constraints;
569 SmallVector<std::string, 4> Clobbers;
570 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR, NumOutputs,
571 NumInputs, OpExprs, Constraints, Clobbers,
572 MII.get(), IP.get(), Callback))
573 return StmtError();
574
575 // Filter out "fpsw". Clang doesn't accept it, and it always lists flags and
576 // fpsr as clobbers.
577 auto End = std::remove(Clobbers.begin(), Clobbers.end(), "fpsw");
578 Clobbers.erase(End, Clobbers.end());
579
580 // Build the vector of clobber StringRefs.
David Majnemer05c69862014-06-23 02:16:41 +0000581 ClobberRefs.insert(ClobberRefs.end(), Clobbers.begin(), Clobbers.end());
Alp Toker1b935a82014-06-08 05:40:04 +0000582
583 // Recast the void pointers and build the vector of constraint StringRefs.
584 unsigned NumExprs = NumOutputs + NumInputs;
585 ConstraintRefs.resize(NumExprs);
586 Exprs.resize(NumExprs);
587 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
588 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
589 if (!OpExpr)
590 return StmtError();
591
592 // Need address of variable.
593 if (OpExprs[i].second)
594 OpExpr =
595 Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr).get();
596
597 ConstraintRefs[i] = StringRef(Constraints[i]);
598 Exprs[i] = OpExpr;
599 }
600
601 // FIXME: We should be passing source locations for better diagnostics.
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000602 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmStringIR,
Alp Toker1b935a82014-06-08 05:40:04 +0000603 NumOutputs, NumInputs, ConstraintRefs,
604 ClobberRefs, Exprs, EndLoc);
605}
606
607/// ParseAsmStatement - Parse a GNU extended asm statement.
608/// asm-statement:
609/// gnu-asm-statement
610/// ms-asm-statement
611///
612/// [GNU] gnu-asm-statement:
613/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
614///
615/// [GNU] asm-argument:
616/// asm-string-literal
617/// asm-string-literal ':' asm-operands[opt]
618/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
619/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
620/// ':' asm-clobbers
621///
622/// [GNU] asm-clobbers:
623/// asm-string-literal
624/// asm-clobbers ',' asm-string-literal
625///
626StmtResult Parser::ParseAsmStatement(bool &msAsm) {
627 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
628 SourceLocation AsmLoc = ConsumeToken();
629
630 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
631 !isTypeQualifier()) {
632 msAsm = true;
633 return ParseMicrosoftAsmStatement(AsmLoc);
634 }
Steven Wucb0d13f2015-01-16 23:05:28 +0000635
Alp Toker1b935a82014-06-08 05:40:04 +0000636 DeclSpec DS(AttrFactory);
637 SourceLocation Loc = Tok.getLocation();
Aaron Ballman08b06592014-07-22 12:44:22 +0000638 ParseTypeQualifierListOpt(DS, AR_VendorAttributesParsed);
Alp Toker1b935a82014-06-08 05:40:04 +0000639
640 // GNU asms accept, but warn, about type-qualifiers other than volatile.
641 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
642 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
643 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
644 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
645 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
646 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
647 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
648
649 // Remember if this was a volatile asm.
650 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
651 if (Tok.isNot(tok::l_paren)) {
652 Diag(Tok, diag::err_expected_lparen_after) << "asm";
653 SkipUntil(tok::r_paren, StopAtSemi);
654 return StmtError();
655 }
656 BalancedDelimiterTracker T(*this, tok::l_paren);
657 T.consumeOpen();
658
659 ExprResult AsmString(ParseAsmStringLiteral());
Steven Wu18bbe192015-05-12 00:16:37 +0000660
661 // Check if GNU-style InlineAsm is disabled.
662 // Error on anything other than empty string.
663 if (!(getLangOpts().GNUAsm || AsmString.isInvalid())) {
664 const auto *SL = cast<StringLiteral>(AsmString.get());
665 if (!SL->getString().trim().empty())
666 Diag(Loc, diag::err_gnu_inline_asm_disabled);
667 }
668
Alp Toker1b935a82014-06-08 05:40:04 +0000669 if (AsmString.isInvalid()) {
670 // Consume up to and including the closing paren.
671 T.skipToEnd();
672 return StmtError();
673 }
674
675 SmallVector<IdentifierInfo *, 4> Names;
676 ExprVector Constraints;
677 ExprVector Exprs;
678 ExprVector Clobbers;
679
680 if (Tok.is(tok::r_paren)) {
681 // We have a simple asm expression like 'asm("foo")'.
682 T.consumeClose();
683 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
684 /*NumOutputs*/ 0, /*NumInputs*/ 0, nullptr,
685 Constraints, Exprs, AsmString.get(),
686 Clobbers, T.getCloseLocation());
687 }
688
689 // Parse Outputs, if present.
690 bool AteExtraColon = false;
691 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
692 // In C++ mode, parse "::" like ": :".
693 AteExtraColon = Tok.is(tok::coloncolon);
694 ConsumeToken();
695
696 if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
697 return StmtError();
698 }
699
700 unsigned NumOutputs = Names.size();
701
702 // Parse Inputs, if present.
703 if (AteExtraColon || Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
704 // In C++ mode, parse "::" like ": :".
705 if (AteExtraColon)
706 AteExtraColon = false;
707 else {
708 AteExtraColon = Tok.is(tok::coloncolon);
709 ConsumeToken();
710 }
711
712 if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
713 return StmtError();
714 }
715
716 assert(Names.size() == Constraints.size() &&
717 Constraints.size() == Exprs.size() && "Input operand size mismatch!");
718
719 unsigned NumInputs = Names.size() - NumOutputs;
720
721 // Parse the clobbers, if present.
722 if (AteExtraColon || Tok.is(tok::colon)) {
723 if (!AteExtraColon)
724 ConsumeToken();
725
726 // Parse the asm-string list for clobbers if present.
727 if (Tok.isNot(tok::r_paren)) {
728 while (1) {
729 ExprResult Clobber(ParseAsmStringLiteral());
730
731 if (Clobber.isInvalid())
732 break;
733
734 Clobbers.push_back(Clobber.get());
735
736 if (!TryConsumeToken(tok::comma))
737 break;
738 }
739 }
740 }
741
742 T.consumeClose();
743 return Actions.ActOnGCCAsmStmt(
744 AsmLoc, false, isVolatile, NumOutputs, NumInputs, Names.data(),
745 Constraints, Exprs, AsmString.get(), Clobbers, T.getCloseLocation());
746}
747
748/// ParseAsmOperands - Parse the asm-operands production as used by
749/// asm-statement, assuming the leading ':' token was eaten.
750///
751/// [GNU] asm-operands:
752/// asm-operand
753/// asm-operands ',' asm-operand
754///
755/// [GNU] asm-operand:
756/// asm-string-literal '(' expression ')'
757/// '[' identifier ']' asm-string-literal '(' expression ')'
758///
759//
760// FIXME: Avoid unnecessary std::string trashing.
761bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
762 SmallVectorImpl<Expr *> &Constraints,
763 SmallVectorImpl<Expr *> &Exprs) {
764 // 'asm-operands' isn't present?
765 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
766 return false;
767
768 while (1) {
769 // Read the [id] if present.
770 if (Tok.is(tok::l_square)) {
771 BalancedDelimiterTracker T(*this, tok::l_square);
772 T.consumeOpen();
773
774 if (Tok.isNot(tok::identifier)) {
775 Diag(Tok, diag::err_expected) << tok::identifier;
776 SkipUntil(tok::r_paren, StopAtSemi);
777 return true;
778 }
779
780 IdentifierInfo *II = Tok.getIdentifierInfo();
781 ConsumeToken();
782
783 Names.push_back(II);
784 T.consumeClose();
785 } else
786 Names.push_back(nullptr);
787
788 ExprResult Constraint(ParseAsmStringLiteral());
789 if (Constraint.isInvalid()) {
790 SkipUntil(tok::r_paren, StopAtSemi);
791 return true;
792 }
793 Constraints.push_back(Constraint.get());
794
795 if (Tok.isNot(tok::l_paren)) {
796 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
797 SkipUntil(tok::r_paren, StopAtSemi);
798 return true;
799 }
800
801 // Read the parenthesized expression.
802 BalancedDelimiterTracker T(*this, tok::l_paren);
803 T.consumeOpen();
Kaelyn Takata15867822014-11-21 18:48:04 +0000804 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
Alp Toker1b935a82014-06-08 05:40:04 +0000805 T.consumeClose();
806 if (Res.isInvalid()) {
807 SkipUntil(tok::r_paren, StopAtSemi);
808 return true;
809 }
810 Exprs.push_back(Res.get());
811 // Eat the comma and continue parsing if it exists.
812 if (!TryConsumeToken(tok::comma))
813 return false;
814 }
815}