Coverage Report

Created: 2019-07-24 05:18

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