Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Parse/ParseStmtAsm.cpp
Line
Count
Source (jump to first uncovered line)
1
//===---- ParseStmtAsm.cpp - Assembly Statement Parser --------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements parsing for GCC and Microsoft inline assembly.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Parse/Parser.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/Basic/Diagnostic.h"
16
#include "clang/Basic/TargetInfo.h"
17
#include "clang/Parse/RAIIObjectsForParser.h"
18
#include "llvm/ADT/SmallString.h"
19
#include "llvm/ADT/StringExtras.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/MCParser/MCTargetAsmParser.h"
27
#include "llvm/MC/MCRegisterInfo.h"
28
#include "llvm/MC/MCStreamer.h"
29
#include "llvm/MC/MCSubtargetInfo.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"
34
using namespace clang;
35
36
namespace {
37
class 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
48
public:
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
226
        AsmTokOffsets(Offsets) {
53
226
    assert(AsmToks.size() == AsmTokOffsets.size());
54
226
  }
55
56
  void LookupInlineAsmIdentifier(StringRef &LineBuf,
57
                                 llvm::InlineAsmIdentifierInfo &Info,
58
                                 bool IsUnevaluatedContext) override;
59
60
  StringRef LookupInlineAsmLabel(StringRef Identifier, llvm::SourceMgr &LSM,
61
                                 llvm::SMLoc Location,
62
                                 bool Create) override;
63
64
  bool LookupInlineAsmField(StringRef Base, StringRef Member,
65
25
                            unsigned &Offset) override {
66
25
    return TheParser.getActions().LookupInlineAsmField(Base, Member, Offset,
67
25
                                                       AsmLoc);
68
25
  }
69
70
20
  static void DiagHandlerCallback(const llvm::SMDiagnostic &D, void *Context) {
71
20
    ((ClangAsmParserCallback *)Context)->handleDiagnostic(D);
72
20
  }
73
74
private:
75
  /// Collect the appropriate tokens for the given string.
76
  void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
77
                           const Token *&FirstOrigToken) const;
78
79
  SourceLocation translateLocation(const llvm::SourceMgr &LSM,
80
                                   llvm::SMLoc SMLoc);
81
82
  void handleDiagnostic(const llvm::SMDiagnostic &D);
83
};
84
}
85
86
void ClangAsmParserCallback::LookupInlineAsmIdentifier(
87
    StringRef &LineBuf, llvm::InlineAsmIdentifierInfo &Info,
88
228
    bool IsUnevaluatedContext) {
89
228
  // Collect the desired tokens.
90
228
  SmallVector<Token, 16> LineToks;
91
228
  const Token *FirstOrigToken = nullptr;
92
228
  findTokensForString(LineBuf, LineToks, FirstOrigToken);
93
228
94
228
  unsigned NumConsumedToks;
95
228
  ExprResult Result = TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks,
96
228
                                                     IsUnevaluatedContext);
97
228
98
228
  // If we consumed the entire line, tell MC that.
99
228
  // Also do this if we consumed nothing as a way of reporting failure.
100
228
  if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
101
48
    // By not modifying LineBuf, we're implicitly consuming it all.
102
48
103
48
    // Otherwise, consume up to the original tokens.
104
180
  } else {
105
180
    assert(FirstOrigToken && "not using original tokens?");
106
180
107
180
    // Since we're using original tokens, apply that offset.
108
180
    assert(FirstOrigToken[NumConsumedToks].getLocation() ==
109
180
           LineToks[NumConsumedToks].getLocation());
110
180
    unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
111
180
    unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
112
180
113
180
    // The total length we've consumed is the relative offset
114
180
    // of the last token we consumed plus its length.
115
180
    unsigned TotalOffset =
116
180
        (AsmTokOffsets[LastIndex] + AsmToks[LastIndex].getLength() -
117
180
         AsmTokOffsets[FirstIndex]);
118
180
    LineBuf = LineBuf.substr(0, TotalOffset);
119
180
  }
120
228
121
228
  // Initialize Info with the lookup result.
122
228
  if (!Result.isUsable())
123
25
    return;
124
203
  TheParser.getActions().FillInlineAsmIdentifierInfo(Result.get(), Info);
125
203
}
126
127
StringRef ClangAsmParserCallback::LookupInlineAsmLabel(StringRef Identifier,
128
                                                       llvm::SourceMgr &LSM,
129
                                                       llvm::SMLoc Location,
130
43
                                                       bool Create) {
131
43
  SourceLocation Loc = translateLocation(LSM, Location);
132
43
  LabelDecl *Label =
133
43
      TheParser.getActions().GetOrCreateMSAsmLabel(Identifier, Loc, Create);
134
43
  return Label->getMSAsmLabel();
135
43
}
136
137
void ClangAsmParserCallback::findTokensForString(
138
    StringRef Str, SmallVectorImpl<Token> &TempToks,
139
228
    const Token *&FirstOrigToken) const {
140
228
  // For now, assert that the string we're working with is a substring
141
228
  // of what we gave to MC.  This lets us use the original tokens.
142
228
  assert(!std::less<const char *>()(Str.begin(), AsmString.begin()) &&
143
228
         !std::less<const char *>()(AsmString.end(), Str.end()));
144
228
145
228
  // Try to find a token whose offset matches the first token.
146
228
  unsigned FirstCharOffset = Str.begin() - AsmString.begin();
147
228
  const unsigned *FirstTokOffset =
148
228
      llvm::lower_bound(AsmTokOffsets, FirstCharOffset);
149
228
150
228
  // For now, assert that the start of the string exactly
151
228
  // corresponds to the start of a token.
152
228
  assert(*FirstTokOffset == FirstCharOffset);
153
228
154
228
  // Use all the original tokens for this line.  (We assume the
155
228
  // end of the line corresponds cleanly to a token break.)
156
228
  unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
157
228
  FirstOrigToken = &AsmToks[FirstTokIndex];
158
228
  unsigned LastCharOffset = Str.end() - AsmString.begin();
159
4.08k
  for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; 
++i3.86k
) {
160
3.86k
    if (AsmTokOffsets[i] >= LastCharOffset)
161
0
      break;
162
3.86k
    TempToks.push_back(AsmToks[i]);
163
3.86k
  }
164
228
}
165
166
SourceLocation
167
ClangAsmParserCallback::translateLocation(const llvm::SourceMgr &LSM,
168
63
                                          llvm::SMLoc SMLoc) {
169
63
  // Compute an offset into the inline asm buffer.
170
63
  // FIXME: This isn't right if .macro is involved (but hopefully, no
171
63
  // real-world code does that).
172
63
  const llvm::MemoryBuffer *LBuf =
173
63
      LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(SMLoc));
174
63
  unsigned Offset = SMLoc.getPointer() - LBuf->getBufferStart();
175
63
176
63
  // Figure out which token that offset points into.
177
63
  const unsigned *TokOffsetPtr = llvm::lower_bound(AsmTokOffsets, Offset);
178
63
  unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
179
63
  unsigned TokOffset = *TokOffsetPtr;
180
63
181
63
  // If we come up with an answer which seems sane, use it; otherwise,
182
63
  // just point at the __asm keyword.
183
63
  // FIXME: Assert the answer is sane once we handle .macro correctly.
184
63
  SourceLocation Loc = AsmLoc;
185
63
  if (TokIndex < AsmToks.size()) {
186
61
    const Token &Tok = AsmToks[TokIndex];
187
61
    Loc = Tok.getLocation();
188
61
    Loc = Loc.getLocWithOffset(Offset - TokOffset);
189
61
  }
190
63
  return Loc;
191
63
}
192
193
20
void ClangAsmParserCallback::handleDiagnostic(const llvm::SMDiagnostic &D) {
194
20
  const llvm::SourceMgr &LSM = *D.getSourceMgr();
195
20
  SourceLocation Loc = translateLocation(LSM, D.getLoc());
196
20
  TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage();
197
20
}
198
199
/// Parse an identifier in an MS-style inline assembly block.
200
ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
201
                                        unsigned &NumLineToksConsumed,
202
228
                                        bool IsUnevaluatedContext) {
203
228
  // Push a fake token on the end so that we don't overrun the token
204
228
  // stream.  We use ';' because it expression-parsing should never
205
228
  // overrun it.
206
228
  const tok::TokenKind EndOfStream = tok::semi;
207
228
  Token EndOfStreamTok;
208
228
  EndOfStreamTok.startToken();
209
228
  EndOfStreamTok.setKind(EndOfStream);
210
228
  LineToks.push_back(EndOfStreamTok);
211
228
212
228
  // Also copy the current token over.
213
228
  LineToks.push_back(Tok);
214
228
215
228
  PP.EnterTokenStream(LineToks, /*DisableMacroExpansions*/ true,
216
228
                      /*IsReinject*/ true);
217
228
218
228
  // Clear the current token and advance to the first token in LineToks.
219
228
  ConsumeAnyToken();
220
228
221
228
  // Parse an optional scope-specifier if we're in C++.
222
228
  CXXScopeSpec SS;
223
228
  if (getLangOpts().CPlusPlus) {
224
61
    ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
225
61
  }
226
228
227
228
  // Require an identifier here.
228
228
  SourceLocation TemplateKWLoc;
229
228
  UnqualifiedId Id;
230
228
  bool Invalid = true;
231
228
  ExprResult Result;
232
228
  if (Tok.is(tok::kw_this)) {
233
3
    Result = ParseCXXThis();
234
3
    Invalid = false;
235
225
  } else {
236
225
    Invalid = ParseUnqualifiedId(SS,
237
225
                                 /*EnteringContext=*/false,
238
225
                                 /*AllowDestructorName=*/false,
239
225
                                 /*AllowConstructorName=*/false,
240
225
                                 /*AllowDeductionGuide=*/false,
241
225
                                 /*ObjectType=*/nullptr, &TemplateKWLoc, Id);
242
225
    // Perform the lookup.
243
225
    Result = Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id,
244
225
                                               IsUnevaluatedContext);
245
225
  }
246
228
  // While the next two tokens are 'period' 'identifier', repeatedly parse it as
247
228
  // a field access. We have to avoid consuming assembler directives that look
248
228
  // like '.' 'else'.
249
270
  while (Result.isUsable() && 
Tok.is(tok::period)245
) {
250
42
    Token IdTok = PP.LookAhead(0);
251
42
    if (IdTok.isNot(tok::identifier))
252
0
      break;
253
42
    ConsumeToken(); // Consume the period.
254
42
    IdentifierInfo *Id = Tok.getIdentifierInfo();
255
42
    ConsumeToken(); // Consume the identifier.
256
42
    Result = Actions.LookupInlineAsmVarDeclField(Result.get(), Id->getName(),
257
42
                                                 Tok.getLocation());
258
42
  }
259
228
260
228
  // Figure out how many tokens we are into LineToks.
261
228
  unsigned LineIndex = 0;
262
228
  if (Tok.is(EndOfStream)) {
263
48
    LineIndex = LineToks.size() - 2;
264
180
  } else {
265
470
    while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
266
290
      LineIndex++;
267
290
      assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
268
290
    }
269
180
  }
270
228
271
228
  // If we've run into the poison token we inserted before, or there
272
228
  // was a parsing error, then claim the entire line.
273
228
  if (Invalid || Tok.is(EndOfStream)) {
274
48
    NumLineToksConsumed = LineToks.size() - 2;
275
180
  } else {
276
180
    // Otherwise, claim up to the start of the next token.
277
180
    NumLineToksConsumed = LineIndex;
278
180
  }
279
228
280
228
  // Finally, restore the old parsing state by consuming all the tokens we
281
228
  // staged before, implicitly killing off the token-lexer we pushed.
282
3.68k
  for (unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; 
++i3.45k
) {
283
3.45k
    ConsumeAnyToken();
284
3.45k
  }
285
228
  assert(Tok.is(EndOfStream));
286
228
  ConsumeToken();
287
228
288
228
  // Leave LineToks in its original state.
289
228
  LineToks.pop_back();
290
228
  LineToks.pop_back();
291
228
292
228
  return Result;
293
228
}
294
295
/// Turn a sequence of our tokens back into a string that we can hand
296
/// to the MC asm parser.
297
static bool buildMSAsmString(Preprocessor &PP, SourceLocation AsmLoc,
298
                             ArrayRef<Token> AsmToks,
299
                             SmallVectorImpl<unsigned> &TokOffsets,
300
227
                             SmallString<512> &Asm) {
301
227
  assert(!AsmToks.empty() && "Didn't expect an empty AsmToks!");
302
227
303
227
  // Is this the start of a new assembly statement?
304
227
  bool isNewStatement = true;
305
227
306
3.02k
  for (unsigned i = 0, e = AsmToks.size(); i < e; 
++i2.79k
) {
307
2.79k
    const Token &Tok = AsmToks[i];
308
2.79k
309
2.79k
    // Start each new statement with a newline and a tab.
310
2.79k
    if (!isNewStatement && 
(2.41k
Tok.is(tok::kw_asm)2.41k
||
Tok.isAtStartOfLine()2.26k
)) {
311
248
      Asm += "\n\t";
312
248
      isNewStatement = true;
313
248
    }
314
2.79k
315
2.79k
    // Preserve the existence of leading whitespace except at the
316
2.79k
    // start of a statement.
317
2.79k
    if (!isNewStatement && 
Tok.hasLeadingSpace()2.16k
)
318
1.10k
      Asm += ' ';
319
2.79k
320
2.79k
    // Remember the offset of this token.
321
2.79k
    TokOffsets.push_back(Asm.size());
322
2.79k
323
2.79k
    // Don't actually write '__asm' into the assembly stream.
324
2.79k
    if (Tok.is(tok::kw_asm)) {
325
155
      // Complain about __asm at the end of the stream.
326
155
      if (i + 1 == e) {
327
1
        PP.Diag(AsmLoc, diag::err_asm_empty);
328
1
        return true;
329
1
      }
330
154
331
154
      continue;
332
154
    }
333
2.63k
334
2.63k
    // Append the spelling of the token.
335
2.63k
    SmallString<32> SpellingBuffer;
336
2.63k
    bool SpellingInvalid = false;
337
2.63k
    Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
338
2.63k
    assert(!SpellingInvalid && "spelling was invalid after correct parse?");
339
2.63k
340
2.63k
    // We are no longer at the start of a statement.
341
2.63k
    isNewStatement = false;
342
2.63k
  }
343
227
344
227
  // Ensure that the buffer is null-terminated.
345
227
  Asm.push_back('\0');
346
226
  Asm.pop_back();
347
226
348
226
  assert(TokOffsets.size() == AsmToks.size());
349
226
  return false;
350
227
}
351
352
/// isTypeQualifier - Return true if the current token could be the
353
/// start of a type-qualifier-list.
354
595
static bool isTypeQualifier(const Token &Tok) {
355
595
  switch (Tok.getKind()) {
356
381
  default: return false;
357
0
  // type-qualifier
358
214
  case tok::kw_const:
359
214
  case tok::kw_volatile:
360
214
  case tok::kw_restrict:
361
214
  case tok::kw___private:
362
214
  case tok::kw___local:
363
214
  case tok::kw___global:
364
214
  case tok::kw___constant:
365
214
  case tok::kw___generic:
366
214
  case tok::kw___read_only:
367
214
  case tok::kw___read_write:
368
214
  case tok::kw___write_only:
369
214
    return true;
370
595
  }
371
595
}
372
373
// Determine if this is a GCC-style asm statement.
374
716
static bool isGCCAsmStatement(const Token &TokAfterAsm) {
375
716
  return TokAfterAsm.is(tok::l_paren) || 
TokAfterAsm.is(tok::kw_goto)597
||
376
716
         
isTypeQualifier(TokAfterAsm)595
;
377
716
}
378
379
/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
380
/// this routine is called to collect the tokens for an MS asm statement.
381
///
382
/// [MS]  ms-asm-statement:
383
///         ms-asm-block
384
///         ms-asm-block ms-asm-statement
385
///
386
/// [MS]  ms-asm-block:
387
///         '__asm' ms-asm-line '\n'
388
///         '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
389
///
390
/// [MS]  ms-asm-instruction-block
391
///         ms-asm-line
392
///         ms-asm-line '\n' ms-asm-instruction-block
393
///
394
243
StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
395
243
  SourceManager &SrcMgr = PP.getSourceManager();
396
243
  SourceLocation EndLoc = AsmLoc;
397
243
  SmallVector<Token, 4> AsmToks;
398
243
399
243
  bool SingleLineMode = true;
400
243
  unsigned BraceNesting = 0;
401
243
  unsigned short savedBraceCount = BraceCount;
402
243
  bool InAsmComment = false;
403
243
  FileID FID;
404
243
  unsigned LineNo = 0;
405
243
  unsigned NumTokensRead = 0;
406
243
  SmallVector<SourceLocation, 4> LBraceLocs;
407
243
  bool SkippedStartOfLine = false;
408
243
409
243
  if (Tok.is(tok::l_brace)) {
410
128
    // Braced inline asm: consume the opening brace.
411
128
    SingleLineMode = false;
412
128
    BraceNesting = 1;
413
128
    EndLoc = ConsumeBrace();
414
128
    LBraceLocs.push_back(EndLoc);
415
128
    ++NumTokensRead;
416
128
  } else {
417
115
    // Single-line inline asm; compute which line it is on.
418
115
    std::pair<FileID, unsigned> ExpAsmLoc =
419
115
        SrcMgr.getDecomposedExpansionLoc(EndLoc);
420
115
    FID = ExpAsmLoc.first;
421
115
    LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
422
115
    LBraceLocs.push_back(SourceLocation());
423
115
  }
424
243
425
243
  SourceLocation TokLoc = Tok.getLocation();
426
3.19k
  do {
427
3.19k
    // If we hit EOF, we're done, period.
428
3.19k
    if (isEofOrEom())
429
3
      break;
430
3.19k
431
3.19k
    if (!InAsmComment && 
Tok.is(tok::l_brace)3.04k
) {
432
17
      // Consume the opening brace.
433
17
      SkippedStartOfLine = Tok.isAtStartOfLine();
434
17
      AsmToks.push_back(Tok);
435
17
      EndLoc = ConsumeBrace();
436
17
      BraceNesting++;
437
17
      LBraceLocs.push_back(EndLoc);
438
17
      TokLoc = Tok.getLocation();
439
17
      ++NumTokensRead;
440
17
      continue;
441
3.17k
    } else if (!InAsmComment && 
Tok.is(tok::semi)3.02k
) {
442
48
      // A semicolon in an asm is the start of a comment.
443
48
      InAsmComment = true;
444
48
      if (!SingleLineMode) {
445
9
        // Compute which line the comment is on.
446
9
        std::pair<FileID, unsigned> ExpSemiLoc =
447
9
            SrcMgr.getDecomposedExpansionLoc(TokLoc);
448
9
        FID = ExpSemiLoc.first;
449
9
        LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
450
9
      }
451
3.12k
    } else if (SingleLineMode || 
InAsmComment1.39k
) {
452
1.76k
      // If end-of-line is significant, check whether this token is on a
453
1.76k
      // new line.
454
1.76k
      std::pair<FileID, unsigned> ExpLoc =
455
1.76k
          SrcMgr.getDecomposedExpansionLoc(TokLoc);
456
1.76k
      if (ExpLoc.first != FID ||
457
1.76k
          SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
458
246
        // If this is a single-line __asm, we're done, except if the next
459
246
        // line is MS-style asm too, in which case we finish a comment
460
246
        // if needed and then keep processing the next line as a single
461
246
        // line __asm.
462
246
        bool isAsm = Tok.is(tok::kw_asm);
463
246
        if (SingleLineMode && 
(236
!isAsm236
||
isGCCAsmStatement(NextToken())142
))
464
98
          break;
465
148
        // We're no longer in a comment.
466
148
        InAsmComment = false;
467
148
        if (isAsm) {
468
138
          // If this is a new __asm {} block we want to process it separately
469
138
          // from the single-line __asm statements
470
138
          if (PP.LookAhead(0).is(tok::l_brace))
471
7
            break;
472
131
          LineNo = SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second);
473
131
          SkippedStartOfLine = Tok.isAtStartOfLine();
474
131
        } else 
if (10
Tok.is(tok::semi)10
) {
475
1
          // A multi-line asm-statement, where next line is a comment
476
1
          InAsmComment = true;
477
1
          FID = ExpLoc.first;
478
1
          LineNo = SrcMgr.getLineNumber(FID, ExpLoc.second);
479
1
        }
480
1.52k
      } else if (!InAsmComment && 
Tok.is(tok::r_brace)1.42k
) {
481
15
        // In MSVC mode, braces only participate in brace matching and
482
15
        // separating the asm statements.  This is an intentional
483
15
        // departure from the Apple gcc behavior.
484
15
        if (!BraceNesting)
485
10
          break;
486
3.05k
      }
487
1.76k
    }
488
3.05k
    if (!InAsmComment && 
BraceNesting2.90k
&&
Tok.is(tok::r_brace)1.38k
&&
489
3.05k
        
BraceCount == (savedBraceCount + BraceNesting)141
) {
490
141
      // Consume the closing brace.
491
141
      SkippedStartOfLine = Tok.isAtStartOfLine();
492
141
      // Don't want to add the closing brace of the whole asm block
493
141
      if (SingleLineMode || 
BraceNesting > 1136
) {
494
16
        Tok.clearFlag(Token::LeadingSpace);
495
16
        AsmToks.push_back(Tok);
496
16
      }
497
141
      EndLoc = ConsumeBrace();
498
141
      BraceNesting--;
499
141
      // Finish if all of the opened braces in the inline asm section were
500
141
      // consumed.
501
141
      if (BraceNesting == 0 && 
!SingleLineMode130
)
502
125
        break;
503
16
      else {
504
16
        LBraceLocs.pop_back();
505
16
        TokLoc = Tok.getLocation();
506
16
        ++NumTokensRead;
507
16
        continue;
508
16
      }
509
2.91k
    }
510
2.91k
511
2.91k
    // Consume the next token; make sure we don't modify the brace count etc.
512
2.91k
    // if we are in a comment.
513
2.91k
    EndLoc = TokLoc;
514
2.91k
    if (InAsmComment)
515
150
      PP.Lex(Tok);
516
2.76k
    else {
517
2.76k
      // Set the token as the start of line if we skipped the original start
518
2.76k
      // of line token in case it was a nested brace.
519
2.76k
      if (SkippedStartOfLine)
520
138
        Tok.setFlag(Token::StartOfLine);
521
2.76k
      AsmToks.push_back(Tok);
522
2.76k
      ConsumeAnyToken();
523
2.76k
    }
524
2.91k
    TokLoc = Tok.getLocation();
525
2.91k
    ++NumTokensRead;
526
2.91k
    SkippedStartOfLine = false;
527
2.95k
  } while (1);
528
243
529
243
  if (BraceNesting && 
BraceCount != savedBraceCount3
) {
530
3
    // __asm without closing brace (this can happen at EOF).
531
7
    for (unsigned i = 0; i < BraceNesting; 
++i4
) {
532
4
      Diag(Tok, diag::err_expected) << tok::r_brace;
533
4
      Diag(LBraceLocs.back(), diag::note_matching) << tok::l_brace;
534
4
      LBraceLocs.pop_back();
535
4
    }
536
3
    return StmtError();
537
240
  } else if (NumTokensRead == 0) {
538
2
    // Empty __asm.
539
2
    Diag(Tok, diag::err_expected) << tok::l_brace;
540
2
    return StmtError();
541
2
  }
542
238
543
238
  // Okay, prepare to use MC to parse the assembly.
544
238
  SmallVector<StringRef, 4> ConstraintRefs;
545
238
  SmallVector<Expr *, 4> Exprs;
546
238
  SmallVector<StringRef, 4> ClobberRefs;
547
238
548
238
  // We need an actual supported target.
549
238
  const llvm::Triple &TheTriple = Actions.Context.getTargetInfo().getTriple();
550
238
  const std::string &TT = TheTriple.getTriple();
551
238
  const llvm::Target *TheTarget = nullptr;
552
238
  if (!TheTriple.isX86()) {
553
2
    Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
554
236
  } else {
555
236
    std::string Error;
556
236
    TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
557
236
    if (!TheTarget)
558
0
      Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
559
236
  }
560
238
561
238
  assert(!LBraceLocs.empty() && "Should have at least one location here");
562
238
563
238
  SmallString<512> AsmString;
564
238
  auto EmptyStmt = [&] {
565
11
    return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmString,
566
11
                                  /*NumOutputs*/ 0, /*NumInputs*/ 0,
567
11
                                  ConstraintRefs, ClobberRefs, Exprs, EndLoc);
568
11
  };
569
238
  // If we don't support assembly, or the assembly is empty, we don't
570
238
  // need to instantiate the AsmParser, etc.
571
238
  if (!TheTarget || 
AsmToks.empty()236
) {
572
11
    return EmptyStmt();
573
11
  }
574
227
575
227
  // Expand the tokens into a string buffer.
576
227
  SmallVector<unsigned, 8> TokOffsets;
577
227
  if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
578
1
    return StmtError();
579
226
580
226
  const TargetOptions &TO = Actions.Context.getTargetInfo().getTargetOpts();
581
226
  std::string FeaturesStr =
582
226
      llvm::join(TO.Features.begin(), TO.Features.end(), ",");
583
226
584
226
  std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
585
226
  if (!MRI) {
586
0
    Diag(AsmLoc, diag::err_msasm_unable_to_create_target)
587
0
        << "target MC unavailable";
588
0
    return EmptyStmt();
589
0
  }
590
226
  // FIXME: init MCOptions from sanitizer flags here.
591
226
  llvm::MCTargetOptions MCOptions;
592
226
  std::unique_ptr<llvm::MCAsmInfo> MAI(
593
226
      TheTarget->createMCAsmInfo(*MRI, TT, MCOptions));
594
226
  // Get the instruction descriptor.
595
226
  std::unique_ptr<llvm::MCInstrInfo> MII(TheTarget->createMCInstrInfo());
596
226
  std::unique_ptr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
597
226
  std::unique_ptr<llvm::MCSubtargetInfo> STI(
598
226
      TheTarget->createMCSubtargetInfo(TT, TO.CPU, FeaturesStr));
599
226
  // Target MCTargetDesc may not be linked in clang-based tools.
600
226
  if (!MAI || !MII | !MOFI || !STI) {
601
0
    Diag(AsmLoc, diag::err_msasm_unable_to_create_target)
602
0
        << "target MC unavailable";
603
0
    return EmptyStmt();
604
0
  }
605
226
606
226
  llvm::SourceMgr TempSrcMgr;
607
226
  llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
608
226
  MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, Ctx);
609
226
  std::unique_ptr<llvm::MemoryBuffer> Buffer =
610
226
      llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
611
226
612
226
  // Tell SrcMgr about this buffer, which is what the parser will pick up.
613
226
  TempSrcMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());
614
226
615
226
  std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
616
226
  std::unique_ptr<llvm::MCAsmParser> Parser(
617
226
      createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
618
226
619
226
  std::unique_ptr<llvm::MCTargetAsmParser> TargetParser(
620
226
      TheTarget->createMCAsmParser(*STI, *Parser, *MII, MCOptions));
621
226
  // Target AsmParser may not be linked in clang-based tools.
622
226
  if (!TargetParser) {
623
0
    Diag(AsmLoc, diag::err_msasm_unable_to_create_target)
624
0
        << "target ASM parser unavailable";
625
0
    return EmptyStmt();
626
0
  }
627
226
628
226
  std::unique_ptr<llvm::MCInstPrinter> IP(
629
226
      TheTarget->createMCInstPrinter(llvm::Triple(TT), 1, *MAI, *MII, *MRI));
630
226
631
226
  // Change to the Intel dialect.
632
226
  Parser->setAssemblerDialect(1);
633
226
  Parser->setTargetParser(*TargetParser.get());
634
226
  Parser->setParsingInlineAsm(true);
635
226
  TargetParser->setParsingInlineAsm(true);
636
226
637
226
  ClangAsmParserCallback Callback(*this, AsmLoc, AsmString, AsmToks,
638
226
                                  TokOffsets);
639
226
  TargetParser->setSemaCallback(&Callback);
640
226
  TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
641
226
                            &Callback);
642
226
643
226
  unsigned NumOutputs;
644
226
  unsigned NumInputs;
645
226
  std::string AsmStringIR;
646
226
  SmallVector<std::pair<void *, bool>, 4> OpExprs;
647
226
  SmallVector<std::string, 4> Constraints;
648
226
  SmallVector<std::string, 4> Clobbers;
649
226
  if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR, NumOutputs,
650
226
                               NumInputs, OpExprs, Constraints, Clobbers,
651
226
                               MII.get(), IP.get(), Callback))
652
20
    return StmtError();
653
206
654
206
  // Filter out "fpsw" and "mxcsr". They aren't valid GCC asm clobber
655
206
  // constraints. Clang always adds fpsr to the clobber list anyway.
656
231
  
llvm::erase_if(Clobbers, [](const std::string &C) 206
{
657
231
    return C == "fpsr" || 
C == "mxcsr"229
;
658
231
  });
659
206
660
206
  // Build the vector of clobber StringRefs.
661
206
  ClobberRefs.insert(ClobberRefs.end(), Clobbers.begin(), Clobbers.end());
662
206
663
206
  // Recast the void pointers and build the vector of constraint StringRefs.
664
206
  unsigned NumExprs = NumOutputs + NumInputs;
665
206
  ConstraintRefs.resize(NumExprs);
666
206
  Exprs.resize(NumExprs);
667
347
  for (unsigned i = 0, e = NumExprs; i != e; 
++i141
) {
668
141
    Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
669
141
    if (!OpExpr)
670
0
      return StmtError();
671
141
672
141
    // Need address of variable.
673
141
    if (OpExprs[i].second)
674
10
      OpExpr =
675
10
          Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr).get();
676
141
677
141
    ConstraintRefs[i] = StringRef(Constraints[i]);
678
141
    Exprs[i] = OpExpr;
679
141
  }
680
206
681
206
  // FIXME: We should be passing source locations for better diagnostics.
682
206
  return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmStringIR,
683
206
                                NumOutputs, NumInputs, ConstraintRefs,
684
206
                                ClobberRefs, Exprs, EndLoc);
685
206
}
686
687
/// ParseAsmStatement - Parse a GNU extended asm statement.
688
///       asm-statement:
689
///         gnu-asm-statement
690
///         ms-asm-statement
691
///
692
/// [GNU] gnu-asm-statement:
693
///         'asm' type-qualifier[opt] '(' asm-argument ')' ';'
694
///
695
/// [GNU] asm-argument:
696
///         asm-string-literal
697
///         asm-string-literal ':' asm-operands[opt]
698
///         asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
699
///         asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
700
///                 ':' asm-clobbers
701
///
702
/// [GNU] asm-clobbers:
703
///         asm-string-literal
704
///         asm-clobbers ',' asm-string-literal
705
///
706
4.57k
StmtResult Parser::ParseAsmStatement(bool &msAsm) {
707
4.57k
  assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
708
4.57k
  SourceLocation AsmLoc = ConsumeToken();
709
4.57k
710
4.57k
  if (getLangOpts().AsmBlocks && 
!isGCCAsmStatement(Tok)574
) {
711
243
    msAsm = true;
712
243
    return ParseMicrosoftAsmStatement(AsmLoc);
713
243
  }
714
4.33k
715
4.33k
  DeclSpec DS(AttrFactory);
716
4.33k
  SourceLocation Loc = Tok.getLocation();
717
4.33k
  ParseTypeQualifierListOpt(DS, AR_VendorAttributesParsed);
718
4.33k
719
4.33k
  // GNU asms accept, but warn, about type-qualifiers other than volatile.
720
4.33k
  if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
721
2
    Diag(Loc, diag::warn_asm_qualifier_ignored) << "const";
722
4.33k
  if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
723
1
    Diag(Loc, diag::warn_asm_qualifier_ignored) << "restrict";
724
4.33k
  // FIXME: Once GCC supports _Atomic, check whether it permits it here.
725
4.33k
  if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
726
1
    Diag(Loc, diag::warn_asm_qualifier_ignored) << "_Atomic";
727
4.33k
728
4.33k
  // Remember if this was a volatile asm.
729
4.33k
  bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
730
4.33k
  // Remember if this was a goto asm.
731
4.33k
  bool isGotoAsm = false;
732
4.33k
733
4.33k
  if (Tok.is(tok::kw_goto)) {
734
123
    isGotoAsm = true;
735
123
    ConsumeToken();
736
123
  }
737
4.33k
738
4.33k
  if (Tok.isNot(tok::l_paren)) {
739
0
    Diag(Tok, diag::err_expected_lparen_after) << "asm";
740
0
    SkipUntil(tok::r_paren, StopAtSemi);
741
0
    return StmtError();
742
0
  }
743
4.33k
  BalancedDelimiterTracker T(*this, tok::l_paren);
744
4.33k
  T.consumeOpen();
745
4.33k
746
4.33k
  ExprResult AsmString(ParseAsmStringLiteral(/*ForAsmLabel*/ false));
747
4.33k
748
4.33k
  // Check if GNU-style InlineAsm is disabled.
749
4.33k
  // Error on anything other than empty string.
750
4.33k
  if (!(getLangOpts().GNUAsm || 
AsmString.isInvalid()2
)) {
751
2
    const auto *SL = cast<StringLiteral>(AsmString.get());
752
2
    if (!SL->getString().trim().empty())
753
1
      Diag(Loc, diag::err_gnu_inline_asm_disabled);
754
2
  }
755
4.33k
756
4.33k
  if (AsmString.isInvalid()) {
757
2
    // Consume up to and including the closing paren.
758
2
    T.skipToEnd();
759
2
    return StmtError();
760
2
  }
761
4.33k
762
4.33k
  SmallVector<IdentifierInfo *, 4> Names;
763
4.33k
  ExprVector Constraints;
764
4.33k
  ExprVector Exprs;
765
4.33k
  ExprVector Clobbers;
766
4.33k
767
4.33k
  if (Tok.is(tok::r_paren)) {
768
185
    // We have a simple asm expression like 'asm("foo")'.
769
185
    T.consumeClose();
770
185
    return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
771
185
                                   /*NumOutputs*/ 0, /*NumInputs*/ 0, nullptr,
772
185
                                   Constraints, Exprs, AsmString.get(),
773
185
                                   Clobbers, /*NumLabels*/ 0,
774
185
                                   T.getCloseLocation());
775
185
  }
776
4.14k
777
4.14k
  // Parse Outputs, if present.
778
4.14k
  bool AteExtraColon = false;
779
4.14k
  if (Tok.is(tok::colon) || 
Tok.is(tok::coloncolon)205
) {
780
4.14k
    // In C++ mode, parse "::" like ": :".
781
4.14k
    AteExtraColon = Tok.is(tok::coloncolon);
782
4.14k
    ConsumeToken();
783
4.14k
784
4.14k
    if (!AteExtraColon && 
ParseAsmOperandsOpt(Names, Constraints, Exprs)3.94k
)
785
2
      return StmtError();
786
4.14k
  }
787
4.14k
788
4.14k
  unsigned NumOutputs = Names.size();
789
4.14k
790
4.14k
  // Parse Inputs, if present.
791
4.14k
  if (AteExtraColon || 
Tok.is(tok::colon)3.94k
||
Tok.is(tok::coloncolon)142
) {
792
4.01k
    // In C++ mode, parse "::" like ": :".
793
4.01k
    if (AteExtraColon)
794
205
      AteExtraColon = false;
795
3.80k
    else {
796
3.80k
      AteExtraColon = Tok.is(tok::coloncolon);
797
3.80k
      ConsumeToken();
798
3.80k
    }
799
4.01k
800
4.01k
    if (!AteExtraColon && 
ParseAsmOperandsOpt(Names, Constraints, Exprs)4.00k
)
801
3
      return StmtError();
802
4.14k
  }
803
4.14k
804
4.14k
  assert(Names.size() == Constraints.size() &&
805
4.14k
         Constraints.size() == Exprs.size() && "Input operand size mismatch!");
806
4.14k
807
4.14k
  unsigned NumInputs = Names.size() - NumOutputs;
808
4.14k
809
4.14k
  // Parse the clobbers, if present.
810
4.14k
  if (AteExtraColon || 
Tok.is(tok::colon)4.13k
||
Tok.is(tok::coloncolon)1.60k
) {
811
2.56k
    if (AteExtraColon)
812
9
      AteExtraColon = false;
813
2.55k
    else {
814
2.55k
      AteExtraColon = Tok.is(tok::coloncolon);
815
2.55k
      ConsumeToken();
816
2.55k
    }
817
2.56k
    // Parse the asm-string list for clobbers if present.
818
2.56k
    if (!AteExtraColon && 
isTokenStringLiteral()2.54k
) {
819
3.06k
      while (1) {
820
3.06k
        ExprResult Clobber(ParseAsmStringLiteral(/*ForAsmLabel*/ false));
821
3.06k
822
3.06k
        if (Clobber.isInvalid())
823
0
          break;
824
3.06k
825
3.06k
        Clobbers.push_back(Clobber.get());
826
3.06k
827
3.06k
        if (!TryConsumeToken(tok::comma))
828
2.20k
          break;
829
3.06k
      }
830
2.20k
    }
831
2.56k
  }
832
4.14k
  if (!isGotoAsm && 
(4.02k
Tok.isNot(tok::r_paren)4.02k
||
AteExtraColon4.01k
)) {
833
8
    Diag(Tok, diag::err_expected) << tok::r_paren;
834
8
    SkipUntil(tok::r_paren, StopAtSemi);
835
8
    return StmtError();
836
8
  }
837
4.13k
838
4.13k
  // Parse the goto label, if present.
839
4.13k
  unsigned NumLabels = 0;
840
4.13k
  if (AteExtraColon || 
Tok.is(tok::colon)4.11k
) {
841
113
    if (!AteExtraColon)
842
93
      ConsumeToken();
843
113
844
164
    while (true) {
845
164
      if (Tok.isNot(tok::identifier)) {
846
8
        Diag(Tok, diag::err_expected) << tok::identifier;
847
8
        SkipUntil(tok::r_paren, StopAtSemi);
848
8
        return StmtError();
849
8
      }
850
156
      LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
851
156
                                                  Tok.getLocation());
852
156
      Names.push_back(Tok.getIdentifierInfo());
853
156
      if (!LD) {
854
0
        SkipUntil(tok::r_paren, StopAtSemi);
855
0
        return StmtError();
856
0
      }
857
156
      ExprResult Res =
858
156
          Actions.ActOnAddrLabel(Tok.getLocation(), Tok.getLocation(), LD);
859
156
      Exprs.push_back(Res.get());
860
156
      NumLabels++;
861
156
      ConsumeToken();
862
156
      if (!TryConsumeToken(tok::comma))
863
105
        break;
864
156
    }
865
4.02k
  } else if (isGotoAsm) {
866
8
    Diag(Tok, diag::err_expected) << tok::colon;
867
8
    SkipUntil(tok::r_paren, StopAtSemi);
868
8
    return StmtError();
869
8
  }
870
4.11k
  T.consumeClose();
871
4.11k
  return Actions.ActOnGCCAsmStmt(
872
4.11k
      AsmLoc, false, isVolatile, NumOutputs, NumInputs, Names.data(),
873
4.11k
      Constraints, Exprs, AsmString.get(), Clobbers, NumLabels,
874
4.11k
      T.getCloseLocation());
875
4.11k
}
876
877
/// ParseAsmOperands - Parse the asm-operands production as used by
878
/// asm-statement, assuming the leading ':' token was eaten.
879
///
880
/// [GNU] asm-operands:
881
///         asm-operand
882
///         asm-operands ',' asm-operand
883
///
884
/// [GNU] asm-operand:
885
///         asm-string-literal '(' expression ')'
886
///         '[' identifier ']' asm-string-literal '(' expression ')'
887
///
888
//
889
// FIXME: Avoid unnecessary std::string trashing.
890
bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
891
                                 SmallVectorImpl<Expr *> &Constraints,
892
7.94k
                                 SmallVectorImpl<Expr *> &Exprs) {
893
7.94k
  // 'asm-operands' isn't present?
894
7.94k
  if (!isTokenStringLiteral() && 
Tok.isNot(tok::l_square)2.57k
)
895
2.20k
    return false;
896
5.74k
897
12.8k
  
while (5.74k
1) {
898
12.8k
    // Read the [id] if present.
899
12.8k
    if (Tok.is(tok::l_square)) {
900
696
      BalancedDelimiterTracker T(*this, tok::l_square);
901
696
      T.consumeOpen();
902
696
903
696
      if (Tok.isNot(tok::identifier)) {
904
0
        Diag(Tok, diag::err_expected) << tok::identifier;
905
0
        SkipUntil(tok::r_paren, StopAtSemi);
906
0
        return true;
907
0
      }
908
696
909
696
      IdentifierInfo *II = Tok.getIdentifierInfo();
910
696
      ConsumeToken();
911
696
912
696
      Names.push_back(II);
913
696
      T.consumeClose();
914
696
    } else
915
12.1k
      Names.push_back(nullptr);
916
12.8k
917
12.8k
    ExprResult Constraint(ParseAsmStringLiteral(/*ForAsmLabel*/ false));
918
12.8k
    if (Constraint.isInvalid()) {
919
1
      SkipUntil(tok::r_paren, StopAtSemi);
920
1
      return true;
921
1
    }
922
12.8k
    Constraints.push_back(Constraint.get());
923
12.8k
924
12.8k
    if (Tok.isNot(tok::l_paren)) {
925
0
      Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
926
0
      SkipUntil(tok::r_paren, StopAtSemi);
927
0
      return true;
928
0
    }
929
12.8k
930
12.8k
    // Read the parenthesized expression.
931
12.8k
    BalancedDelimiterTracker T(*this, tok::l_paren);
932
12.8k
    T.consumeOpen();
933
12.8k
    ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
934
12.8k
    T.consumeClose();
935
12.8k
    if (Res.isInvalid()) {
936
4
      SkipUntil(tok::r_paren, StopAtSemi);
937
4
      return true;
938
4
    }
939
12.8k
    Exprs.push_back(Res.get());
940
12.8k
    // Eat the comma and continue parsing if it exists.
941
12.8k
    if (!TryConsumeToken(tok::comma))
942
5.74k
      return false;
943
12.8k
  }
944
5.74k
}