clang  6.0.0svn
ParseStmtAsm.cpp
Go to the documentation of this file.
1 //===---- 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 "clang/AST/ASTContext.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/TargetInfo.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringExtras.h"
21 #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"
27 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/MC/MCTargetOptions.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/TargetSelect.h"
35 using namespace clang;
36 
37 namespace {
38 class 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 
49 public:
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 
57  void LookupInlineAsmIdentifier(StringRef &LineBuf,
58  llvm::InlineAsmIdentifierInfo &Info,
59  bool IsUnevaluatedContext) override {
60  // Collect the desired tokens.
61  SmallVector<Token, 16> LineToks;
62  const Token *FirstOrigToken = nullptr;
63  findTokensForString(LineBuf, LineToks, FirstOrigToken);
64 
65  unsigned NumConsumedToks;
67  LineToks, NumConsumedToks, IsUnevaluatedContext);
68 
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 
92  // Initialize Info with the lookup result.
93  if (!Result.isUsable())
94  return;
95  TheParser.getActions().FillInlineAsmIdentifierInfo(Result.get(), Info);
96  }
97 
98  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 
107  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 
117 private:
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 
147  SourceLocation translateLocation(const llvm::SourceMgr &LSM, llvm::SMLoc SMLoc) {
148  // 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).
151  const llvm::MemoryBuffer *LBuf =
152  LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(SMLoc));
153  unsigned Offset = SMLoc.getPointer() - LBuf->getBufferStart();
154 
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  }
170  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());
176  TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage();
177  }
178 };
179 }
180 
181 /// Parse an identifier in an MS-style inline assembly block.
183  unsigned &NumLineToksConsumed,
184  bool IsUnevaluatedContext) {
185  // 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 
197  PP.EnterTokenStream(LineToks, /*DisableMacroExpansions*/ true);
198 
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) {
205  ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
206  }
207 
208  // Require an identifier here.
209  SourceLocation TemplateKWLoc;
211  bool Invalid = true;
213  if (Tok.is(tok::kw_this)) {
214  Result = ParseCXXThis();
215  Invalid = false;
216  } else {
217  Invalid = ParseUnqualifiedId(SS,
218  /*EnteringContext=*/false,
219  /*AllowDestructorName=*/false,
220  /*AllowConstructorName=*/false,
221  /*AllowDeductionGuide=*/false,
222  /*ObjectType=*/nullptr, TemplateKWLoc, Id);
223  // Perform the lookup.
224  Result = Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id,
225  IsUnevaluatedContext);
226  }
227  // 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.
237  Result = Actions.LookupInlineAsmVarDeclField(Result.get(), Id->getName(),
238  Tok.getLocation());
239  }
240 
241  // 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 
273  return Result;
274 }
275 
276 /// Turn a sequence of our tokens back into a string that we can hand
277 /// to the MC asm parser.
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 
333 /// isTypeQualifier - Return true if the current token could be the
334 /// start of a type-qualifier-list.
335 static 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.
355 static bool isGCCAsmStatement(const Token &TokAfterAsm) {
356  return TokAfterAsm.is(tok::l_paren) || TokAfterAsm.is(tok::kw_goto) ||
357  isTypeQualifier(TokAfterAsm);
358 }
359 
360 /// 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 ///
375 StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
376  SourceManager &SrcMgr = PP.getSourceManager();
377  SourceLocation EndLoc = AsmLoc;
378  SmallVector<Token, 4> AsmToks;
379 
380  bool SingleLineMode = true;
381  unsigned BraceNesting = 0;
382  unsigned short savedBraceCount = BraceCount;
383  bool InAsmComment = false;
384  FileID FID;
385  unsigned LineNo = 0;
386  unsigned NumTokensRead = 0;
388  bool SkippedStartOfLine = false;
389 
390  if (Tok.is(tok::l_brace)) {
391  // Braced inline asm: consume the opening brace.
392  SingleLineMode = false;
393  BraceNesting = 1;
394  EndLoc = ConsumeBrace();
395  LBraceLocs.push_back(EndLoc);
396  ++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);
403  LBraceLocs.push_back(SourceLocation());
404  }
405 
406  SourceLocation TokLoc = Tok.getLocation();
407  do {
408  // If we hit EOF, we're done, period.
409  if (isEofOrEom())
410  break;
411 
412  if (!InAsmComment && Tok.is(tok::l_brace)) {
413  // Consume the opening brace.
414  SkippedStartOfLine = Tok.isAtStartOfLine();
415  AsmToks.push_back(Tok);
416  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)) {
423  // A semicolon in an asm is the start of a comment.
424  InAsmComment = true;
425  if (!SingleLineMode) {
426  // 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  }
432  } else if (SingleLineMode || InAsmComment) {
433  // 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) {
439  // If this is a single-line __asm, we're done, except if the next
440  // line is MS-style asm too, in which case we finish a comment
441  // if needed and then keep processing the next line as a single
442  // line __asm.
443  bool isAsm = Tok.is(tok::kw_asm);
444  if (SingleLineMode && (!isAsm || isGCCAsmStatement(NextToken())))
445  break;
446  // We're no longer in a comment.
447  InAsmComment = false;
448  if (isAsm) {
449  // If this is a new __asm {} block we want to process it separately
450  // from the single-line __asm statements
451  if (PP.LookAhead(0).is(tok::l_brace))
452  break;
453  LineNo = SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second);
454  SkippedStartOfLine = Tok.isAtStartOfLine();
455  } 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);
460  }
461  } else if (!InAsmComment && Tok.is(tok::r_brace)) {
462  // 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;
467  }
468  }
469  if (!InAsmComment && BraceNesting && Tok.is(tok::r_brace) &&
470  BraceCount == (savedBraceCount + BraceNesting)) {
471  // Consume the closing brace.
472  SkippedStartOfLine = Tok.isAtStartOfLine();
473  // Don't want to add the closing brace of the whole asm block
474  if (SingleLineMode || BraceNesting > 1) {
476  AsmToks.push_back(Tok);
477  }
478  EndLoc = ConsumeBrace();
479  BraceNesting--;
480  // Finish if all of the opened braces in the inline asm section were
481  // consumed.
482  if (BraceNesting == 0 && !SingleLineMode)
483  break;
484  else {
485  LBraceLocs.pop_back();
486  TokLoc = Tok.getLocation();
487  ++NumTokensRead;
488  continue;
489  }
490  }
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 {
498  // 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)
502  AsmToks.push_back(Tok);
503  ConsumeAnyToken();
504  }
505  TokLoc = Tok.getLocation();
506  ++NumTokensRead;
507  SkippedStartOfLine = false;
508  } while (1);
509 
510  if (BraceNesting && BraceCount != savedBraceCount) {
511  // __asm without closing brace (this can happen at EOF).
512  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  }
517  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;
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 
545  assert(!LBraceLocs.empty() && "Should have at least one location here");
546 
547  // 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()) {
550  return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, StringRef(),
551  /*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 
561  const TargetOptions &TO = Actions.Context.getTargetInfo().getTargetOpts();
562  std::string FeaturesStr =
563  llvm::join(TO.Features.begin(), TO.Features.end(), ",");
564 
565  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(
571  TheTarget->createMCSubtargetInfo(TT, TO.CPU, FeaturesStr));
572 
573  llvm::SourceMgr TempSrcMgr;
574  llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
575  MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, Ctx);
576  std::unique_ptr<llvm::MemoryBuffer> Buffer =
577  llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
578 
579  // Tell SrcMgr about this buffer, which is what the parser will pick up.
580  TempSrcMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());
581 
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 
591  std::unique_ptr<llvm::MCInstPrinter> IP(
592  TheTarget->createMCInstPrinter(llvm::Triple(TT), 1, *MAI, *MII, *MRI));
593 
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;
610  SmallVector<std::string, 4> Constraints;
612  if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR, NumOutputs,
613  NumInputs, OpExprs, Constraints, Clobbers,
614  MII.get(), IP.get(), Callback))
615  return StmtError();
616 
617  // 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  });
622 
623  // Build the vector of clobber StringRefs.
624  ClobberRefs.insert(ClobberRefs.end(), Clobbers.begin(), Clobbers.end());
625 
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.
645  return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmStringIR,
646  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 ///
669 StmtResult Parser::ParseAsmStatement(bool &msAsm) {
670  assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
671  SourceLocation AsmLoc = ConsumeToken();
672 
673  if (getLangOpts().AsmBlocks && !isGCCAsmStatement(Tok)) {
674  msAsm = true;
675  return ParseMicrosoftAsmStatement(AsmLoc);
676  }
677 
678  DeclSpec DS(AttrFactory);
679  SourceLocation Loc = Tok.getLocation();
680  ParseTypeQualifierListOpt(DS, AR_VendorAttributesParsed);
681 
682  // GNU asms accept, but warn, about type-qualifiers other than volatile.
684  Diag(Loc, diag::warn_asm_qualifier_ignored) << "const";
686  Diag(Loc, diag::warn_asm_qualifier_ignored) << "restrict";
687  // FIXME: Once GCC supports _Atomic, check whether it permits it here.
689  Diag(Loc, diag::warn_asm_qualifier_ignored) << "_Atomic";
690 
691  // Remember if this was a volatile asm.
692  bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
693 
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 
701  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());
710 
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 
719  if (AsmString.isInvalid()) {
720  // Consume up to and including the closing paren.
721  T.skipToEnd();
722  return StmtError();
723  }
724 
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.
811 bool 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();
854  ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
855  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 }
Defines the clang::ASTContext interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info)
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {...
Definition: Token.h:95
StringRef P
SourceLocation getCloseLocation() const
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition: Token.h:234
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:57
Options for controlling the target.
Definition: TargetOptions.h:26
tok::TokenKind getKind() const
Definition: Token.h:90
static bool isGCCAsmStatement(const Token &TokAfterAsm)
One of these records is kept for each identifier that is lexed.
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
void setKind(tok::TokenKind K)
Definition: Token.h:91
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ...
LabelDecl * GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate)
std::pair< FileID, unsigned > getDecomposedExpansionLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:900
PtrTy get() const
Definition: Ownership.h:162
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the &#39;spelling&#39; of the token at the given location; does not go up to the spelling location or ...
uint32_t Offset
Definition: CacheTokens.cpp:43
const FormatToken & Tok
StmtResult StmtError()
Definition: Ownership.h:268
Defines the Diagnostic-related interfaces.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
Expr - This represents one expression.
Definition: Expr.h:106
std::string Label
int Id
Definition: ASTDiff.cpp:191
const FunctionProtoType * T
static bool buildMSAsmString(Preprocessor &PP, SourceLocation AsmLoc, ArrayRef< Token > AsmToks, SmallVectorImpl< unsigned > &TokOffsets, SmallString< 512 > &Asm)
Turn a sequence of our tokens back into a string that we can hand to the MC asm parser.
Sema & getActions() const
Definition: Parser.h:274
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:124
bool isInvalid() const
Definition: Ownership.h:158
bool isUsable() const
Definition: Ownership.h:159
The result type of a method or function.
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:144
Encodes a location in the source.
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:177
LabelDecl - Represents the declaration of a label.
Definition: Decl.h:427
ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl< Token > &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated)
Parse an identifier in an MS-style inline assembly block.
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings startin...
Definition: TargetOptions.h:55
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:266
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc)
StringRef getName() const
Return the actual identifier string.
static bool isTypeQualifier(const Token &Tok)
isTypeQualifier - Return true if the current token could be the start of a type-qualifier-list.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isNot(tok::TokenKind K) const
Definition: Token.h:96
Dataflow Directional Tag Classes.
StringRef getMSAsmLabel() const
Definition: Decl.h:465
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:543
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:72
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:252
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
Defines the clang::TargetInfo interface.
void clearFlag(TokenFlags Flag)
Unset the specified flag.
Definition: Token.h:244
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
Definition: Token.h:270
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
This class handles loading and caching of source files into memory.
void startToken()
Reset all flags to cleared.
Definition: Token.h:169
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:98
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr *> VL, ArrayRef< Expr *> PL, ArrayRef< Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
void * getPtrEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) pointer encoding for it...