Coverage Report

Created: 2020-09-19 12:23

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Parse/ParseExpr.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
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
/// \file
10
/// Provides the Expression parsing implementation.
11
///
12
/// Expressions in C99 basically consist of a bunch of binary operators with
13
/// unary operators and other random stuff at the leaves.
14
///
15
/// In the C99 grammar, these unary operators bind tightest and are represented
16
/// as the 'cast-expression' production.  Everything else is either a binary
17
/// operator (e.g. '/') or a ternary operator ("?:").  The unary leaves are
18
/// handled by ParseCastExpression, the higher level pieces are handled by
19
/// ParseBinaryExpression.
20
///
21
//===----------------------------------------------------------------------===//
22
23
#include "clang/Parse/Parser.h"
24
#include "clang/AST/ASTContext.h"
25
#include "clang/AST/ExprCXX.h"
26
#include "clang/Basic/PrettyStackTrace.h"
27
#include "clang/Parse/RAIIObjectsForParser.h"
28
#include "clang/Sema/DeclSpec.h"
29
#include "clang/Sema/ParsedTemplate.h"
30
#include "clang/Sema/Scope.h"
31
#include "clang/Sema/TypoCorrection.h"
32
#include "llvm/ADT/SmallVector.h"
33
using namespace clang;
34
35
/// Simple precedence-based parser for binary/ternary operators.
36
///
37
/// Note: we diverge from the C99 grammar when parsing the assignment-expression
38
/// production.  C99 specifies that the LHS of an assignment operator should be
39
/// parsed as a unary-expression, but consistency dictates that it be a
40
/// conditional-expession.  In practice, the important thing here is that the
41
/// LHS of an assignment has to be an l-value, which productions between
42
/// unary-expression and conditional-expression don't produce.  Because we want
43
/// consistency, we parse the LHS as a conditional-expression, then check for
44
/// l-value-ness in semantic analysis stages.
45
///
46
/// \verbatim
47
///       pm-expression: [C++ 5.5]
48
///         cast-expression
49
///         pm-expression '.*' cast-expression
50
///         pm-expression '->*' cast-expression
51
///
52
///       multiplicative-expression: [C99 6.5.5]
53
///     Note: in C++, apply pm-expression instead of cast-expression
54
///         cast-expression
55
///         multiplicative-expression '*' cast-expression
56
///         multiplicative-expression '/' cast-expression
57
///         multiplicative-expression '%' cast-expression
58
///
59
///       additive-expression: [C99 6.5.6]
60
///         multiplicative-expression
61
///         additive-expression '+' multiplicative-expression
62
///         additive-expression '-' multiplicative-expression
63
///
64
///       shift-expression: [C99 6.5.7]
65
///         additive-expression
66
///         shift-expression '<<' additive-expression
67
///         shift-expression '>>' additive-expression
68
///
69
///       compare-expression: [C++20 expr.spaceship]
70
///         shift-expression
71
///         compare-expression '<=>' shift-expression
72
///
73
///       relational-expression: [C99 6.5.8]
74
///         compare-expression
75
///         relational-expression '<' compare-expression
76
///         relational-expression '>' compare-expression
77
///         relational-expression '<=' compare-expression
78
///         relational-expression '>=' compare-expression
79
///
80
///       equality-expression: [C99 6.5.9]
81
///         relational-expression
82
///         equality-expression '==' relational-expression
83
///         equality-expression '!=' relational-expression
84
///
85
///       AND-expression: [C99 6.5.10]
86
///         equality-expression
87
///         AND-expression '&' equality-expression
88
///
89
///       exclusive-OR-expression: [C99 6.5.11]
90
///         AND-expression
91
///         exclusive-OR-expression '^' AND-expression
92
///
93
///       inclusive-OR-expression: [C99 6.5.12]
94
///         exclusive-OR-expression
95
///         inclusive-OR-expression '|' exclusive-OR-expression
96
///
97
///       logical-AND-expression: [C99 6.5.13]
98
///         inclusive-OR-expression
99
///         logical-AND-expression '&&' inclusive-OR-expression
100
///
101
///       logical-OR-expression: [C99 6.5.14]
102
///         logical-AND-expression
103
///         logical-OR-expression '||' logical-AND-expression
104
///
105
///       conditional-expression: [C99 6.5.15]
106
///         logical-OR-expression
107
///         logical-OR-expression '?' expression ':' conditional-expression
108
/// [GNU]   logical-OR-expression '?' ':' conditional-expression
109
/// [C++] the third operand is an assignment-expression
110
///
111
///       assignment-expression: [C99 6.5.16]
112
///         conditional-expression
113
///         unary-expression assignment-operator assignment-expression
114
/// [C++]   throw-expression [C++ 15]
115
///
116
///       assignment-operator: one of
117
///         = *= /= %= += -= <<= >>= &= ^= |=
118
///
119
///       expression: [C99 6.5.17]
120
///         assignment-expression ...[opt]
121
///         expression ',' assignment-expression ...[opt]
122
/// \endverbatim
123
6.65M
ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
124
6.65M
  ExprResult LHS(ParseAssignmentExpression(isTypeCast));
125
6.65M
  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
126
6.65M
}
127
128
/// This routine is called when the '@' is seen and consumed.
129
/// Current token is an Identifier and is not a 'try'. This
130
/// routine is necessary to disambiguate \@try-statement from,
131
/// for example, \@encode-expression.
132
///
133
ExprResult
134
301
Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
135
301
  ExprResult LHS(ParseObjCAtExpression(AtLoc));
136
301
  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
137
301
}
138
139
/// This routine is called when a leading '__extension__' is seen and
140
/// consumed.  This is necessary because the token gets consumed in the
141
/// process of disambiguating between an expression and a declaration.
142
ExprResult
143
3.58k
Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
144
3.58k
  ExprResult LHS(true);
145
3.58k
  {
146
    // Silence extension warnings in the sub-expression
147
3.58k
    ExtensionRAIIObject O(Diags);
148
3.58k
149
3.58k
    LHS = ParseCastExpression(AnyCastExpr);
150
3.58k
  }
151
3.58k
152
3.58k
  if (!LHS.isInvalid())
153
3.58k
    LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
154
3.58k
                               LHS.get());
155
3.58k
156
3.58k
  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
157
3.58k
}
158
159
/// Parse an expr that doesn't include (top-level) commas.
160
22.2M
ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
161
22.2M
  if (Tok.is(tok::code_completion)) {
162
201
    Actions.CodeCompleteExpression(getCurScope(),
163
201
                                   PreferredType.get(Tok.getLocation()));
164
201
    cutOffParsing();
165
201
    return ExprError();
166
201
  }
167
22.2M
168
22.2M
  if (Tok.is(tok::kw_throw))
169
13.3k
    return ParseThrowExpression();
170
22.2M
  if (Tok.is(tok::kw_co_yield))
171
63
    return ParseCoyieldExpression();
172
22.2M
173
22.2M
  ExprResult LHS = ParseCastExpression(AnyCastExpr,
174
22.2M
                                       /*isAddressOfOperand=*/false,
175
22.2M
                                       isTypeCast);
176
22.2M
  return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
177
22.2M
}
178
179
/// Parse an assignment expression where part of an Objective-C message
180
/// send has already been parsed.
181
///
182
/// In this case \p LBracLoc indicates the location of the '[' of the message
183
/// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
184
/// the receiver of the message.
185
///
186
/// Since this handles full assignment-expression's, it handles postfix
187
/// expressions and other binary operators for these expressions as well.
188
ExprResult
189
Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
190
                                                    SourceLocation SuperLoc,
191
                                                    ParsedType ReceiverType,
192
68
                                                    Expr *ReceiverExpr) {
193
68
  ExprResult R
194
68
    = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
195
68
                                     ReceiverType, ReceiverExpr);
196
68
  R = ParsePostfixExpressionSuffix(R);
197
68
  return ParseRHSOfBinaryExpression(R, prec::Assignment);
198
68
}
199
200
ExprResult
201
5.54M
Parser::ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast) {
202
5.54M
  assert(Actions.ExprEvalContexts.back().Context ==
203
5.54M
             Sema::ExpressionEvaluationContext::ConstantEvaluated &&
204
5.54M
         "Call this function only if your ExpressionEvaluationContext is "
205
5.54M
         "already ConstantEvaluated");
206
5.54M
  ExprResult LHS(ParseCastExpression(AnyCastExpr, false, isTypeCast));
207
5.54M
  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
208
5.54M
  return Actions.ActOnConstantExpression(Res);
209
5.54M
}
210
211
153k
ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
212
  // C++03 [basic.def.odr]p2:
213
  //   An expression is potentially evaluated unless it appears where an
214
  //   integral constant expression is required (see 5.19) [...].
215
  // C++98 and C++11 have no such rule, but this is only a defect in C++98.
216
153k
  EnterExpressionEvaluationContext ConstantEvaluated(
217
153k
      Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
218
153k
  return ParseConstantExpressionInExprEvalContext(isTypeCast);
219
153k
}
220
221
21.6k
ExprResult Parser::ParseCaseExpression(SourceLocation CaseLoc) {
222
21.6k
  EnterExpressionEvaluationContext ConstantEvaluated(
223
21.6k
      Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
224
21.6k
  ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast));
225
21.6k
  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
226
21.6k
  return Actions.ActOnCaseExpr(CaseLoc, Res);
227
21.6k
}
228
229
/// Parse a constraint-expression.
230
///
231
/// \verbatim
232
///       constraint-expression: C++2a[temp.constr.decl]p1
233
///         logical-or-expression
234
/// \endverbatim
235
275
ExprResult Parser::ParseConstraintExpression() {
236
275
  EnterExpressionEvaluationContext ConstantEvaluated(
237
275
      Actions, Sema::ExpressionEvaluationContext::Unevaluated);
238
275
  ExprResult LHS(ParseCastExpression(AnyCastExpr));
239
275
  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
240
275
  if (Res.isUsable() && 
!Actions.CheckConstraintExpression(Res.get())272
) {
241
6
    Actions.CorrectDelayedTyposInExpr(Res);
242
6
    return ExprError();
243
6
  }
244
269
  return Res;
245
269
}
246
247
/// \brief Parse a constraint-logical-and-expression.
248
///
249
/// \verbatim
250
///       C++2a[temp.constr.decl]p1
251
///       constraint-logical-and-expression:
252
///         primary-expression
253
///         constraint-logical-and-expression '&&' primary-expression
254
///
255
/// \endverbatim
256
ExprResult
257
394
Parser::ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause) {
258
394
  EnterExpressionEvaluationContext ConstantEvaluated(
259
394
      Actions, Sema::ExpressionEvaluationContext::Unevaluated);
260
394
  bool NotPrimaryExpression = false;
261
424
  auto ParsePrimary = [&] () {
262
424
    ExprResult E = ParseCastExpression(PrimaryExprOnly,
263
424
                                       /*isAddressOfOperand=*/false,
264
424
                                       /*isTypeCast=*/NotTypeCast,
265
424
                                       /*isVectorLiteral=*/false,
266
424
                                       &NotPrimaryExpression);
267
424
    if (E.isInvalid())
268
3
      return ExprError();
269
421
    auto RecoverFromNonPrimary = [&] (ExprResult E, bool Note) {
270
11
        E = ParsePostfixExpressionSuffix(E);
271
        // Use InclusiveOr, the precedence just after '&&' to not parse the
272
        // next arguments to the logical and.
273
11
        E = ParseRHSOfBinaryExpression(E, prec::InclusiveOr);
274
11
        if (!E.isInvalid())
275
10
          Diag(E.get()->getExprLoc(),
276
10
               Note
277
2
               ? diag::note_unparenthesized_non_primary_expr_in_requires_clause
278
8
               : diag::err_unparenthesized_non_primary_expr_in_requires_clause)
279
10
               << FixItHint::CreateInsertion(E.get()->getBeginLoc(), "(")
280
10
               << FixItHint::CreateInsertion(
281
10
                   PP.getLocForEndOfToken(E.get()->getEndLoc()), ")")
282
10
               << E.get()->getSourceRange();
283
11
        return E;
284
11
    };
285
421
286
421
    if (NotPrimaryExpression ||
287
        // Check if the following tokens must be a part of a non-primary
288
        // expression
289
417
        getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
290
417
                           /*CPlusPlus11=*/true) > prec::LogicalAnd ||
291
        // Postfix operators other than '(' (which will be checked for in
292
        // CheckConstraintExpression).
293
415
        Tok.isOneOf(tok::period, tok::plusplus, tok::minusminus) ||
294
415
        (Tok.is(tok::l_square) && 
!NextToken().is(tok::l_square)0
)) {
295
6
      E = RecoverFromNonPrimary(E, /*Note=*/false);
296
6
      if (E.isInvalid())
297
0
        return ExprError();
298
6
      NotPrimaryExpression = false;
299
6
    }
300
421
    bool PossibleNonPrimary;
301
421
    bool IsConstraintExpr =
302
421
        Actions.CheckConstraintExpression(E.get(), Tok, &PossibleNonPrimary,
303
421
                                          IsTrailingRequiresClause);
304
421
    if (!IsConstraintExpr || 
PossibleNonPrimary418
) {
305
      // Atomic constraint might be an unparenthesized non-primary expression
306
      // (such as a binary operator), in which case we might get here (e.g. in
307
      // 'requires 0 + 1 && true' we would now be at '+', and parse and ignore
308
      // the rest of the addition expression). Try to parse the rest of it here.
309
6
      if (PossibleNonPrimary)
310
5
        E = RecoverFromNonPrimary(E, /*Note=*/!IsConstraintExpr);
311
6
      Actions.CorrectDelayedTyposInExpr(E);
312
6
      return ExprError();
313
6
    }
314
415
    return E;
315
415
  };
316
394
  ExprResult LHS = ParsePrimary();
317
394
  if (LHS.isInvalid())
318
9
    return ExprError();
319
415
  
while (385
Tok.is(tok::ampamp)) {
320
30
    SourceLocation LogicalAndLoc = ConsumeToken();
321
30
    ExprResult RHS = ParsePrimary();
322
30
    if (RHS.isInvalid()) {
323
0
      Actions.CorrectDelayedTyposInExpr(LHS);
324
0
      return ExprError();
325
0
    }
326
30
    ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalAndLoc,
327
30
                                       tok::ampamp, LHS.get(), RHS.get());
328
30
    if (!Op.isUsable()) {
329
0
      Actions.CorrectDelayedTyposInExpr(RHS);
330
0
      Actions.CorrectDelayedTyposInExpr(LHS);
331
0
      return ExprError();
332
0
    }
333
30
    LHS = Op;
334
30
  }
335
385
  return LHS;
336
385
}
337
338
/// \brief Parse a constraint-logical-or-expression.
339
///
340
/// \verbatim
341
///       C++2a[temp.constr.decl]p1
342
///       constraint-logical-or-expression:
343
///         constraint-logical-and-expression
344
///         constraint-logical-or-expression '||'
345
///             constraint-logical-and-expression
346
///
347
/// \endverbatim
348
ExprResult
349
386
Parser::ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause) {
350
386
  ExprResult LHS(ParseConstraintLogicalAndExpression(IsTrailingRequiresClause));
351
386
  if (!LHS.isUsable())
352
9
    return ExprError();
353
385
  
while (377
Tok.is(tok::pipepipe)) {
354
8
    SourceLocation LogicalOrLoc = ConsumeToken();
355
8
    ExprResult RHS =
356
8
        ParseConstraintLogicalAndExpression(IsTrailingRequiresClause);
357
8
    if (!RHS.isUsable()) {
358
0
      Actions.CorrectDelayedTyposInExpr(LHS);
359
0
      return ExprError();
360
0
    }
361
8
    ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalOrLoc,
362
8
                                       tok::pipepipe, LHS.get(), RHS.get());
363
8
    if (!Op.isUsable()) {
364
0
      Actions.CorrectDelayedTyposInExpr(RHS);
365
0
      Actions.CorrectDelayedTyposInExpr(LHS);
366
0
      return ExprError();
367
0
    }
368
8
    LHS = Op;
369
8
  }
370
377
  return LHS;
371
377
}
372
373
39.0k
bool Parser::isNotExpressionStart() {
374
39.0k
  tok::TokenKind K = Tok.getKind();
375
39.0k
  if (K == tok::l_brace || 
K == tok::r_brace39.0k
||
376
39.0k
      K == tok::kw_for  || K == tok::kw_while ||
377
39.0k
      K == tok::kw_if   || 
K == tok::kw_else39.0k
||
378
39.0k
      K == tok::kw_goto || K == tok::kw_try)
379
5
    return true;
380
  // If this is a decl-specifier, we can't be at the start of an expression.
381
39.0k
  return isKnownToBeDeclarationSpecifier();
382
39.0k
}
383
384
4.57M
bool Parser::isFoldOperator(prec::Level Level) const {
385
4.57M
  return Level > prec::Unknown && 
Level != prec::Conditional3.48M
&&
386
3.43M
         Level != prec::Spaceship;
387
4.57M
}
388
389
1.08M
bool Parser::isFoldOperator(tok::TokenKind Kind) const {
390
1.08M
  return isFoldOperator(getBinOpPrecedence(Kind, GreaterThanIsOperator, true));
391
1.08M
}
392
393
/// Parse a binary expression that starts with \p LHS and has a
394
/// precedence of at least \p MinPrec.
395
ExprResult
396
34.6M
Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
397
34.6M
  prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
398
34.6M
                                               GreaterThanIsOperator,
399
34.6M
                                               getLangOpts().CPlusPlus11);
400
34.6M
  SourceLocation ColonLoc;
401
34.6M
402
34.6M
  auto SavedType = PreferredType;
403
38.0M
  while (1) {
404
    // Every iteration may rely on a preferred type for the whole expression.
405
38.0M
    PreferredType = SavedType;
406
    // If this token has a lower precedence than we are allowed to parse (e.g.
407
    // because we are called recursively, or because the token is not a binop),
408
    // then we are done!
409
38.0M
    if (NextTokPrec < MinPrec)
410
34.6M
      return LHS;
411
3.48M
412
    // Consume the operator, saving the operator token for error reporting.
413
3.48M
    Token OpToken = Tok;
414
3.48M
    ConsumeToken();
415
3.48M
416
3.48M
    if (OpToken.is(tok::caretcaret)) {
417
1
      return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
418
1
    }
419
3.48M
420
    // If we're potentially in a template-id, we may now be able to determine
421
    // whether we're actually in one or not.
422
3.48M
    if (OpToken.isOneOf(tok::comma, tok::greater, tok::greatergreater,
423
3.48M
                        tok::greatergreatergreater) &&
424
158k
        checkPotentialAngleBracketDelimiter(OpToken))
425
18
      return ExprError();
426
3.48M
427
    // Bail out when encountering a comma followed by a token which can't
428
    // possibly be the start of an expression. For instance:
429
    //   int f() { return 1, }
430
    // We can't do this before consuming the comma, because
431
    // isNotExpressionStart() looks at the token stream.
432
3.48M
    if (OpToken.is(tok::comma) && 
isNotExpressionStart()39.0k
) {
433
8
      PP.EnterToken(Tok, /*IsReinject*/true);
434
8
      Tok = OpToken;
435
8
      return LHS;
436
8
    }
437
3.48M
438
    // If the next token is an ellipsis, then this is a fold-expression. Leave
439
    // it alone so we can handle it in the paren expression.
440
3.48M
    if (isFoldOperator(NextTokPrec) && 
Tok.is(tok::ellipsis)3.43M
) {
441
      // FIXME: We can't check this via lookahead before we consume the token
442
      // because that tickles a lexer bug.
443
289
      PP.EnterToken(Tok, /*IsReinject*/true);
444
289
      Tok = OpToken;
445
289
      return LHS;
446
289
    }
447
3.48M
448
    // In Objective-C++, alternative operator tokens can be used as keyword args
449
    // in message expressions. Unconsume the token so that it can reinterpreted
450
    // as an identifier in ParseObjCMessageExpressionBody. i.e., we support:
451
    //   [foo meth:0 and:0];
452
    //   [foo not_eq];
453
3.48M
    if (getLangOpts().ObjC && 
getLangOpts().CPlusPlus760k
&&
454
181k
        Tok.isOneOf(tok::colon, tok::r_square) &&
455
31
        OpToken.getIdentifierInfo() != nullptr) {
456
16
      PP.EnterToken(Tok, /*IsReinject*/true);
457
16
      Tok = OpToken;
458
16
      return LHS;
459
16
    }
460
3.48M
461
    // Special case handling for the ternary operator.
462
3.48M
    ExprResult TernaryMiddle(true);
463
3.48M
    if (NextTokPrec == prec::Conditional) {
464
55.2k
      if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)45.2k
) {
465
        // Parse a braced-init-list here for error recovery purposes.
466
1
        SourceLocation BraceLoc = Tok.getLocation();
467
1
        TernaryMiddle = ParseBraceInitializer();
468
1
        if (!TernaryMiddle.isInvalid()) {
469
1
          Diag(BraceLoc, diag::err_init_list_bin_op)
470
1
              << /*RHS*/ 1 << PP.getSpelling(OpToken)
471
1
              << Actions.getExprRange(TernaryMiddle.get());
472
1
          TernaryMiddle = ExprError();
473
1
        }
474
55.2k
      } else if (Tok.isNot(tok::colon)) {
475
        // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
476
55.0k
        ColonProtectionRAIIObject X(*this);
477
55.0k
478
        // Handle this production specially:
479
        //   logical-OR-expression '?' expression ':' conditional-expression
480
        // In particular, the RHS of the '?' is 'expression', not
481
        // 'logical-OR-expression' as we might expect.
482
55.0k
        TernaryMiddle = ParseExpression();
483
235
      } else {
484
        // Special case handling of "X ? Y : Z" where Y is empty:
485
        //   logical-OR-expression '?' ':' conditional-expression   [GNU]
486
235
        TernaryMiddle = nullptr;
487
235
        Diag(Tok, diag::ext_gnu_conditional_expr);
488
235
      }
489
55.2k
490
55.2k
      if (TernaryMiddle.isInvalid()) {
491
26
        Actions.CorrectDelayedTyposInExpr(LHS);
492
26
        LHS = ExprError();
493
26
        TernaryMiddle = nullptr;
494
26
      }
495
55.2k
496
55.2k
      if (!TryConsumeToken(tok::colon, ColonLoc)) {
497
        // Otherwise, we're missing a ':'.  Assume that this was a typo that
498
        // the user forgot. If we're not in a macro expansion, we can suggest
499
        // a fixit hint. If there were two spaces before the current token,
500
        // suggest inserting the colon in between them, otherwise insert ": ".
501
9
        SourceLocation FILoc = Tok.getLocation();
502
9
        const char *FIText = ": ";
503
9
        const SourceManager &SM = PP.getSourceManager();
504
9
        if (FILoc.isFileID() || 
PP.isAtStartOfMacroExpansion(FILoc, &FILoc)2
) {
505
9
          assert(FILoc.isFileID());
506
9
          bool IsInvalid = false;
507
9
          const char *SourcePtr =
508
9
            SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
509
9
          if (!IsInvalid && *SourcePtr == ' ') {
510
9
            SourcePtr =
511
9
              SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
512
9
            if (!IsInvalid && *SourcePtr == ' ') {
513
0
              FILoc = FILoc.getLocWithOffset(-1);
514
0
              FIText = ":";
515
0
            }
516
9
          }
517
9
        }
518
9
519
9
        Diag(Tok, diag::err_expected)
520
9
            << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
521
9
        Diag(OpToken, diag::note_matching) << tok::question;
522
9
        ColonLoc = Tok.getLocation();
523
9
      }
524
55.2k
    }
525
3.48M
526
3.48M
    PreferredType.enterBinary(Actions, Tok.getLocation(), LHS.get(),
527
3.48M
                              OpToken.getKind());
528
    // Parse another leaf here for the RHS of the operator.
529
    // ParseCastExpression works here because all RHS expressions in C have it
530
    // as a prefix, at least. However, in C++, an assignment-expression could
531
    // be a throw-expression, which is not a valid cast-expression.
532
    // Therefore we need some special-casing here.
533
    // Also note that the third operand of the conditional operator is
534
    // an assignment-expression in C++, and in C++11, we can have a
535
    // braced-init-list on the RHS of an assignment. For better diagnostics,
536
    // parse as if we were allowed braced-init-lists everywhere, and check that
537
    // they only appear on the RHS of assignments later.
538
3.48M
    ExprResult RHS;
539
3.48M
    bool RHSIsInitList = false;
540
3.48M
    if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)2.17M
) {
541
75
      RHS = ParseBraceInitializer();
542
75
      RHSIsInitList = true;
543
3.48M
    } else if (getLangOpts().CPlusPlus && 
NextTokPrec <= prec::Conditional2.20M
)
544
638k
      RHS = ParseAssignmentExpression();
545
2.85M
    else
546
2.85M
      RHS = ParseCastExpression(AnyCastExpr);
547
3.48M
548
3.48M
    if (RHS.isInvalid()) {
549
      // FIXME: Errors generated by the delayed typo correction should be
550
      // printed before errors from parsing the RHS, not after.
551
3.15k
      Actions.CorrectDelayedTyposInExpr(LHS);
552
3.15k
      if (TernaryMiddle.isUsable())
553
4
        TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
554
3.15k
      LHS = ExprError();
555
3.15k
    }
556
3.48M
557
    // Remember the precedence of this operator and get the precedence of the
558
    // operator immediately to the right of the RHS.
559
3.48M
    prec::Level ThisPrec = NextTokPrec;
560
3.48M
    NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
561
3.48M
                                     getLangOpts().CPlusPlus11);
562
3.48M
563
    // Assignment and conditional expressions are right-associative.
564
3.48M
    bool isRightAssoc = ThisPrec == prec::Conditional ||
565
3.43M
                        ThisPrec == prec::Assignment;
566
3.48M
567
    // Get the precedence of the operator to the right of the RHS.  If it binds
568
    // more tightly with RHS than we do, evaluate it completely first.
569
3.48M
    if (ThisPrec < NextTokPrec ||
570
3.35M
        (ThisPrec == NextTokPrec && 
isRightAssoc120k
)) {
571
134k
      if (!RHS.isInvalid() && 
RHSIsInitList134k
) {
572
4
        Diag(Tok, diag::err_init_list_bin_op)
573
4
          << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
574
4
        RHS = ExprError();
575
4
      }
576
      // If this is left-associative, only parse things on the RHS that bind
577
      // more tightly than the current operator.  If it is left-associative, it
578
      // is okay, to bind exactly as tightly.  For example, compile A=B=C=D as
579
      // A=(B=(C=D)), where each paren is a level of recursion here.
580
      // The function takes ownership of the RHS.
581
134k
      RHS = ParseRHSOfBinaryExpression(RHS,
582
134k
                            static_cast<prec::Level>(ThisPrec + !isRightAssoc));
583
134k
      RHSIsInitList = false;
584
134k
585
134k
      if (RHS.isInvalid()) {
586
        // FIXME: Errors generated by the delayed typo correction should be
587
        // printed before errors from ParseRHSOfBinaryExpression, not after.
588
314
        Actions.CorrectDelayedTyposInExpr(LHS);
589
314
        if (TernaryMiddle.isUsable())
590
0
          TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
591
314
        LHS = ExprError();
592
314
      }
593
134k
594
134k
      NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
595
134k
                                       getLangOpts().CPlusPlus11);
596
134k
    }
597
3.48M
598
3.48M
    if (!RHS.isInvalid() && 
RHSIsInitList3.48M
) {
599
71
      if (ThisPrec == prec::Assignment) {
600
68
        Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
601
68
          << Actions.getExprRange(RHS.get());
602
3
      } else if (ColonLoc.isValid()) {
603
1
        Diag(ColonLoc, diag::err_init_list_bin_op)
604
1
          << /*RHS*/1 << ":"
605
1
          << Actions.getExprRange(RHS.get());
606
1
        LHS = ExprError();
607
2
      } else {
608
2
        Diag(OpToken, diag::err_init_list_bin_op)
609
2
          << /*RHS*/1 << PP.getSpelling(OpToken)
610
2
          << Actions.getExprRange(RHS.get());
611
2
        LHS = ExprError();
612
2
      }
613
71
    }
614
3.48M
615
3.48M
    ExprResult OrigLHS = LHS;
616
3.48M
    if (!LHS.isInvalid()) {
617
      // Combine the LHS and RHS into the LHS (e.g. build AST).
618
3.48M
      if (TernaryMiddle.isInvalid()) {
619
        // If we're using '>>' as an operator within a template
620
        // argument list (in C++98), suggest the addition of
621
        // parentheses so that the code remains well-formed in C++0x.
622
3.42M
        if (!GreaterThanIsOperator && 
OpToken.is(tok::greatergreater)102k
)
623
4
          SuggestParentheses(OpToken.getLocation(),
624
4
                             diag::warn_cxx11_right_shift_in_template_arg,
625
4
                         SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
626
4
                                     Actions.getExprRange(RHS.get()).getEnd()));
627
3.42M
628
3.42M
        ExprResult BinOp =
629
3.42M
            Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
630
3.42M
                               OpToken.getKind(), LHS.get(), RHS.get());
631
3.42M
        if (BinOp.isInvalid())
632
3.28k
          BinOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
633
3.28k
                                             RHS.get()->getEndLoc(),
634
3.28k
                                             {LHS.get(), RHS.get()});
635
3.42M
636
3.42M
        LHS = BinOp;
637
55.1k
      } else {
638
55.1k
        ExprResult CondOp = Actions.ActOnConditionalOp(
639
55.1k
            OpToken.getLocation(), ColonLoc, LHS.get(), TernaryMiddle.get(),
640
55.1k
            RHS.get());
641
55.1k
        if (CondOp.isInvalid()) {
642
241
          std::vector<clang::Expr *> Args;
643
          // TernaryMiddle can be null for the GNU conditional expr extension.
644
241
          if (TernaryMiddle.get())
645
234
            Args = {LHS.get(), TernaryMiddle.get(), RHS.get()};
646
7
          else
647
7
            Args = {LHS.get(), RHS.get()};
648
241
          CondOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
649
241
                                              RHS.get()->getEndLoc(), Args);
650
241
        }
651
55.1k
652
55.1k
        LHS = CondOp;
653
55.1k
      }
654
      // In this case, ActOnBinOp or ActOnConditionalOp performed the
655
      // CorrectDelayedTyposInExpr check.
656
3.48M
      if (!getLangOpts().CPlusPlus)
657
1.27M
        continue;
658
2.21M
    }
659
2.21M
660
    // Ensure potential typos aren't left undiagnosed.
661
2.21M
    if (LHS.isInvalid()) {
662
4.10k
      Actions.CorrectDelayedTyposInExpr(OrigLHS);
663
4.10k
      Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
664
4.10k
      Actions.CorrectDelayedTyposInExpr(RHS);
665
4.10k
    }
666
2.21M
  }
667
34.6M
}
668
669
/// Parse a cast-expression, unary-expression or primary-expression, based
670
/// on \p ExprType.
671
///
672
/// \p isAddressOfOperand exists because an id-expression that is the
673
/// operand of address-of gets special treatment due to member pointers.
674
///
675
ExprResult Parser::ParseCastExpression(CastParseKind ParseKind,
676
                                       bool isAddressOfOperand,
677
                                       TypeCastState isTypeCast,
678
                                       bool isVectorLiteral,
679
37.0M
                                       bool *NotPrimaryExpression) {
680
37.0M
  bool NotCastExpr;
681
37.0M
  ExprResult Res = ParseCastExpression(ParseKind,
682
37.0M
                                       isAddressOfOperand,
683
37.0M
                                       NotCastExpr,
684
37.0M
                                       isTypeCast,
685
37.0M
                                       isVectorLiteral,
686
37.0M
                                       NotPrimaryExpression);
687
37.0M
  if (NotCastExpr)
688
14.5k
    Diag(Tok, diag::err_expected_expression);
689
37.0M
  return Res;
690
37.0M
}
691
692
namespace {
693
class CastExpressionIdValidator final : public CorrectionCandidateCallback {
694
 public:
695
  CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
696
12.7M
      : NextToken(Next), AllowNonTypes(AllowNonTypes) {
697
12.7M
    WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
698
12.7M
  }
699
700
417
  bool ValidateCandidate(const TypoCorrection &candidate) override {
701
417
    NamedDecl *ND = candidate.getCorrectionDecl();
702
417
    if (!ND)
703
14
      return candidate.isKeyword();
704
403
705
403
    if (isa<TypeDecl>(ND))
706
36
      return WantTypeSpecifiers;
707
367
708
367
    if (!AllowNonTypes || 
!CorrectionCandidateCallback::ValidateCandidate(candidate)359
)
709
8
      return false;
710
359
711
359
    if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
712
282
      return true;
713
77
714
77
    for (auto *C : candidate) {
715
77
      NamedDecl *ND = C->getUnderlyingDecl();
716
77
      if (isa<ValueDecl>(ND) && 
!isa<FunctionDecl>(ND)74
)
717
68
        return true;
718
77
    }
719
9
    return false;
720
77
  }
721
722
2.75k
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
723
2.75k
    return std::make_unique<CastExpressionIdValidator>(*this);
724
2.75k
  }
725
726
 private:
727
  Token NextToken;
728
  bool AllowNonTypes;
729
};
730
}
731
732
/// Parse a cast-expression, or, if \pisUnaryExpression is true, parse
733
/// a unary-expression.
734
///
735
/// \p isAddressOfOperand exists because an id-expression that is the operand
736
/// of address-of gets special treatment due to member pointers. NotCastExpr
737
/// is set to true if the token is not the start of a cast-expression, and no
738
/// diagnostic is emitted in this case and no tokens are consumed.
739
///
740
/// \verbatim
741
///       cast-expression: [C99 6.5.4]
742
///         unary-expression
743
///         '(' type-name ')' cast-expression
744
///
745
///       unary-expression:  [C99 6.5.3]
746
///         postfix-expression
747
///         '++' unary-expression
748
///         '--' unary-expression
749
/// [Coro]  'co_await' cast-expression
750
///         unary-operator cast-expression
751
///         'sizeof' unary-expression
752
///         'sizeof' '(' type-name ')'
753
/// [C++11] 'sizeof' '...' '(' identifier ')'
754
/// [GNU]   '__alignof' unary-expression
755
/// [GNU]   '__alignof' '(' type-name ')'
756
/// [C11]   '_Alignof' '(' type-name ')'
757
/// [C++11] 'alignof' '(' type-id ')'
758
/// [GNU]   '&&' identifier
759
/// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
760
/// [C++]   new-expression
761
/// [C++]   delete-expression
762
///
763
///       unary-operator: one of
764
///         '&'  '*'  '+'  '-'  '~'  '!'
765
/// [GNU]   '__extension__'  '__real'  '__imag'
766
///
767
///       primary-expression: [C99 6.5.1]
768
/// [C99]   identifier
769
/// [C++]   id-expression
770
///         constant
771
///         string-literal
772
/// [C++]   boolean-literal  [C++ 2.13.5]
773
/// [C++11] 'nullptr'        [C++11 2.14.7]
774
/// [C++11] user-defined-literal
775
///         '(' expression ')'
776
/// [C11]   generic-selection
777
/// [C++2a] requires-expression
778
///         '__func__'        [C99 6.4.2.2]
779
/// [GNU]   '__FUNCTION__'
780
/// [MS]    '__FUNCDNAME__'
781
/// [MS]    'L__FUNCTION__'
782
/// [MS]    '__FUNCSIG__'
783
/// [MS]    'L__FUNCSIG__'
784
/// [GNU]   '__PRETTY_FUNCTION__'
785
/// [GNU]   '(' compound-statement ')'
786
/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
787
/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
788
/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
789
///                                     assign-expr ')'
790
/// [GNU]   '__builtin_FILE' '(' ')'
791
/// [GNU]   '__builtin_FUNCTION' '(' ')'
792
/// [GNU]   '__builtin_LINE' '(' ')'
793
/// [CLANG] '__builtin_COLUMN' '(' ')'
794
/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
795
/// [GNU]   '__null'
796
/// [OBJC]  '[' objc-message-expr ']'
797
/// [OBJC]  '\@selector' '(' objc-selector-arg ')'
798
/// [OBJC]  '\@protocol' '(' identifier ')'
799
/// [OBJC]  '\@encode' '(' type-name ')'
800
/// [OBJC]  objc-string-literal
801
/// [C++]   simple-type-specifier '(' expression-list[opt] ')'      [C++ 5.2.3]
802
/// [C++11] simple-type-specifier braced-init-list                  [C++11 5.2.3]
803
/// [C++]   typename-specifier '(' expression-list[opt] ')'         [C++ 5.2.3]
804
/// [C++11] typename-specifier braced-init-list                     [C++11 5.2.3]
805
/// [C++]   'const_cast' '<' type-name '>' '(' expression ')'       [C++ 5.2p1]
806
/// [C++]   'dynamic_cast' '<' type-name '>' '(' expression ')'     [C++ 5.2p1]
807
/// [C++]   'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
808
/// [C++]   'static_cast' '<' type-name '>' '(' expression ')'      [C++ 5.2p1]
809
/// [C++]   'typeid' '(' expression ')'                             [C++ 5.2p1]
810
/// [C++]   'typeid' '(' type-id ')'                                [C++ 5.2p1]
811
/// [C++]   'this'          [C++ 9.3.2]
812
/// [G++]   unary-type-trait '(' type-id ')'
813
/// [G++]   binary-type-trait '(' type-id ',' type-id ')'           [TODO]
814
/// [EMBT]  array-type-trait '(' type-id ',' integer ')'
815
/// [clang] '^' block-literal
816
///
817
///       constant: [C99 6.4.4]
818
///         integer-constant
819
///         floating-constant
820
///         enumeration-constant -> identifier
821
///         character-constant
822
///
823
///       id-expression: [C++ 5.1]
824
///                   unqualified-id
825
///                   qualified-id
826
///
827
///       unqualified-id: [C++ 5.1]
828
///                   identifier
829
///                   operator-function-id
830
///                   conversion-function-id
831
///                   '~' class-name
832
///                   template-id
833
///
834
///       new-expression: [C++ 5.3.4]
835
///                   '::'[opt] 'new' new-placement[opt] new-type-id
836
///                                     new-initializer[opt]
837
///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
838
///                                     new-initializer[opt]
839
///
840
///       delete-expression: [C++ 5.3.5]
841
///                   '::'[opt] 'delete' cast-expression
842
///                   '::'[opt] 'delete' '[' ']' cast-expression
843
///
844
/// [GNU/Embarcadero] unary-type-trait:
845
///                   '__is_arithmetic'
846
///                   '__is_floating_point'
847
///                   '__is_integral'
848
///                   '__is_lvalue_expr'
849
///                   '__is_rvalue_expr'
850
///                   '__is_complete_type'
851
///                   '__is_void'
852
///                   '__is_array'
853
///                   '__is_function'
854
///                   '__is_reference'
855
///                   '__is_lvalue_reference'
856
///                   '__is_rvalue_reference'
857
///                   '__is_fundamental'
858
///                   '__is_object'
859
///                   '__is_scalar'
860
///                   '__is_compound'
861
///                   '__is_pointer'
862
///                   '__is_member_object_pointer'
863
///                   '__is_member_function_pointer'
864
///                   '__is_member_pointer'
865
///                   '__is_const'
866
///                   '__is_volatile'
867
///                   '__is_trivial'
868
///                   '__is_standard_layout'
869
///                   '__is_signed'
870
///                   '__is_unsigned'
871
///
872
/// [GNU] unary-type-trait:
873
///                   '__has_nothrow_assign'
874
///                   '__has_nothrow_copy'
875
///                   '__has_nothrow_constructor'
876
///                   '__has_trivial_assign'                  [TODO]
877
///                   '__has_trivial_copy'                    [TODO]
878
///                   '__has_trivial_constructor'
879
///                   '__has_trivial_destructor'
880
///                   '__has_virtual_destructor'
881
///                   '__is_abstract'                         [TODO]
882
///                   '__is_class'
883
///                   '__is_empty'                            [TODO]
884
///                   '__is_enum'
885
///                   '__is_final'
886
///                   '__is_pod'
887
///                   '__is_polymorphic'
888
///                   '__is_sealed'                           [MS]
889
///                   '__is_trivial'
890
///                   '__is_union'
891
///                   '__has_unique_object_representations'
892
///
893
/// [Clang] unary-type-trait:
894
///                   '__is_aggregate'
895
///                   '__trivially_copyable'
896
///
897
///       binary-type-trait:
898
/// [GNU]             '__is_base_of'
899
/// [MS]              '__is_convertible_to'
900
///                   '__is_convertible'
901
///                   '__is_same'
902
///
903
/// [Embarcadero] array-type-trait:
904
///                   '__array_rank'
905
///                   '__array_extent'
906
///
907
/// [Embarcadero] expression-trait:
908
///                   '__is_lvalue_expr'
909
///                   '__is_rvalue_expr'
910
/// \endverbatim
911
///
912
ExprResult Parser::ParseCastExpression(CastParseKind ParseKind,
913
                                       bool isAddressOfOperand,
914
                                       bool &NotCastExpr,
915
                                       TypeCastState isTypeCast,
916
                                       bool isVectorLiteral,
917
38.3M
                                       bool *NotPrimaryExpression) {
918
38.3M
  ExprResult Res;
919
38.3M
  tok::TokenKind SavedKind = Tok.getKind();
920
38.3M
  auto SavedType = PreferredType;
921
38.3M
  NotCastExpr = false;
922
38.3M
923
  // Are postfix-expression suffix operators permitted after this
924
  // cast-expression? If not, and we find some, we'll parse them anyway and
925
  // diagnose them.
926
38.3M
  bool AllowSuffix = true;
927
38.3M
928
  // This handles all of cast-expression, unary-expression, postfix-expression,
929
  // and primary-expression.  We handle them together like this for efficiency
930
  // and to simplify handling of an expression starting with a '(' token: which
931
  // may be one of a parenthesized expression, cast-expression, compound literal
932
  // expression, or statement expression.
933
  //
934
  // If the parsed tokens consist of a primary-expression, the cases below
935
  // break out of the switch;  at the end we call ParsePostfixExpressionSuffix
936
  // to handle the postfix expression suffixes.  Cases that cannot be followed
937
  // by postfix exprs should set AllowSuffix to false.
938
38.3M
  switch (SavedKind) {
939
5.42M
  case tok::l_paren: {
940
    // If this expression is limited to being a unary-expression, the paren can
941
    // not start a cast expression.
942
5.42M
    ParenParseOption ParenExprType;
943
5.42M
    switch (ParseKind) {
944
2.84k
      case CastParseKind::UnaryExprOnly:
945
2.84k
        if (!getLangOpts().CPlusPlus)
946
0
          ParenExprType = CompoundLiteral;
947
2.84k
        LLVM_FALLTHROUGH;
948
5.42M
      case CastParseKind::AnyCastExpr:
949
5.42M
        ParenExprType = ParenParseOption::CastExpr;
950
5.42M
        break;
951
121
      case CastParseKind::PrimaryExprOnly:
952
121
        ParenExprType = FoldExpr;
953
121
        break;
954
5.42M
    }
955
5.42M
    ParsedType CastTy;
956
5.42M
    SourceLocation RParenLoc;
957
5.42M
    Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
958
5.42M
                               isTypeCast == IsTypeCast, CastTy, RParenLoc);
959
5.42M
960
    // FIXME: What should we do if a vector literal is followed by a
961
    // postfix-expression suffix? Usually postfix operators are permitted on
962
    // literals.
963
5.42M
    if (isVectorLiteral)
964
145
      return Res;
965
5.42M
966
5.42M
    switch (ParenExprType) {
967
1.07M
    case SimpleExpr:   break;    // Nothing else to do.
968
8.73k
    case CompoundStmt: break;  // Nothing else to do.
969
49.7k
    case CompoundLiteral:
970
      // We parsed '(' type-name ')' '{' ... '}'.  If any suffixes of
971
      // postfix-expression exist, parse them now.
972
49.7k
      break;
973
4.28M
    case CastExpr:
974
      // We have parsed the cast-expression and no postfix-expr pieces are
975
      // following.
976
4.28M
      return Res;
977
170
    case FoldExpr:
978
      // We only parsed a fold-expression. There might be postfix-expr pieces
979
      // afterwards; parse them now.
980
170
      break;
981
1.13M
    }
982
1.13M
983
1.13M
    break;
984
1.13M
  }
985
1.13M
986
    // primary-expression
987
8.54M
  case tok::numeric_constant:
988
    // constant: integer-constant
989
    // constant: floating-constant
990
8.54M
991
8.54M
    Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
992
8.54M
    ConsumeToken();
993
8.54M
    break;
994
1.13M
995
281k
  case tok::kw_true:
996
281k
  case tok::kw_false:
997
281k
    Res = ParseCXXBoolLiteral();
998
281k
    break;
999
281k
1000
1.07k
  case tok::kw___objc_yes:
1001
1.07k
  case tok::kw___objc_no:
1002
1.07k
    Res = ParseObjCBoolLiteral();
1003
1.07k
    break;
1004
1.07k
1005
44.8k
  case tok::kw_nullptr:
1006
44.8k
    Diag(Tok, diag::warn_cxx98_compat_nullptr);
1007
44.8k
    Res = Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
1008
44.8k
    break;
1009
1.07k
1010
610k
  case tok::annot_primary_expr:
1011
610k
  case tok::annot_overload_set:
1012
610k
    Res = getExprAnnotation(Tok);
1013
610k
    if (!Res.isInvalid() && Tok.getKind() == tok::annot_overload_set)
1014
610k
      Res = Actions.ActOnNameClassifiedAsOverloadSet(getCurScope(), Res.get());
1015
610k
    ConsumeAnnotationToken();
1016
610k
    if (!Res.isInvalid() && 
Tok.is(tok::less)610k
)
1017
22
      checkPotentialAngleBracket(Res);
1018
610k
    break;
1019
610k
1020
1.73M
  case tok::annot_non_type:
1021
1.73M
  case tok::annot_non_type_dependent:
1022
1.73M
  case tok::annot_non_type_undeclared: {
1023
1.73M
    CXXScopeSpec SS;
1024
1.73M
    Token Replacement;
1025
1.73M
    Res = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
1026
1.73M
    assert(!Res.isUnset() &&
1027
1.73M
           "should not perform typo correction on annotation token");
1028
1.73M
    break;
1029
1.73M
  }
1030
1.73M
1031
1.00k
  case tok::kw___super:
1032
1.00k
  case tok::kw_decltype:
1033
    // Annotate the token and tail recurse.
1034
1.00k
    if (TryAnnotateTypeOrScopeToken())
1035
0
      return ExprError();
1036
1.00k
    assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
1037
1.00k
    return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1038
1.00k
                               isVectorLiteral, NotPrimaryExpression);
1039
1.00k
1040
13.7M
  case tok::identifier: {      // primary-expression: identifier
1041
                               // unqualified-id: identifier
1042
                               // constant: enumeration-constant
1043
    // Turn a potentially qualified name into a annot_typename or
1044
    // annot_cxxscope if it would be valid.  This handles things like x::y, etc.
1045
13.7M
    if (getLangOpts().CPlusPlus) {
1046
      // Avoid the unnecessary parse-time lookup in the common case
1047
      // where the syntax forbids a type.
1048
6.60M
      const Token &Next = NextToken();
1049
6.60M
1050
      // If this identifier was reverted from a token ID, and the next token
1051
      // is a parenthesis, this is likely to be a use of a type trait. Check
1052
      // those tokens.
1053
6.60M
      if (Next.is(tok::l_paren) &&
1054
848k
          Tok.is(tok::identifier) &&
1055
848k
          Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
1056
104
        IdentifierInfo *II = Tok.getIdentifierInfo();
1057
        // Build up the mapping of revertible type traits, for future use.
1058
104
        if (RevertibleTypeTraits.empty()) {
1059
153
#define RTT_JOIN(X,Y) X##Y
1060
3
#define REVERTIBLE_TYPE_TRAIT(Name)                         \
1061
153
          RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
1062
153
            = RTT_JOIN(tok::kw_,Name)
1063
3
1064
3
          REVERTIBLE_TYPE_TRAIT(__is_abstract);
1065
3
          REVERTIBLE_TYPE_TRAIT(__is_aggregate);
1066
3
          REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
1067
3
          REVERTIBLE_TYPE_TRAIT(__is_array);
1068
3
          REVERTIBLE_TYPE_TRAIT(__is_assignable);
1069
3
          REVERTIBLE_TYPE_TRAIT(__is_base_of);
1070
3
          REVERTIBLE_TYPE_TRAIT(__is_class);
1071
3
          REVERTIBLE_TYPE_TRAIT(__is_complete_type);
1072
3
          REVERTIBLE_TYPE_TRAIT(__is_compound);
1073
3
          REVERTIBLE_TYPE_TRAIT(__is_const);
1074
3
          REVERTIBLE_TYPE_TRAIT(__is_constructible);
1075
3
          REVERTIBLE_TYPE_TRAIT(__is_convertible);
1076
3
          REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
1077
3
          REVERTIBLE_TYPE_TRAIT(__is_destructible);
1078
3
          REVERTIBLE_TYPE_TRAIT(__is_empty);
1079
3
          REVERTIBLE_TYPE_TRAIT(__is_enum);
1080
3
          REVERTIBLE_TYPE_TRAIT(__is_floating_point);
1081
3
          REVERTIBLE_TYPE_TRAIT(__is_final);
1082
3
          REVERTIBLE_TYPE_TRAIT(__is_function);
1083
3
          REVERTIBLE_TYPE_TRAIT(__is_fundamental);
1084
3
          REVERTIBLE_TYPE_TRAIT(__is_integral);
1085
3
          REVERTIBLE_TYPE_TRAIT(__is_interface_class);
1086
3
          REVERTIBLE_TYPE_TRAIT(__is_literal);
1087
3
          REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
1088
3
          REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
1089
3
          REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
1090
3
          REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
1091
3
          REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
1092
3
          REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
1093
3
          REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
1094
3
          REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
1095
3
          REVERTIBLE_TYPE_TRAIT(__is_object);
1096
3
          REVERTIBLE_TYPE_TRAIT(__is_pod);
1097
3
          REVERTIBLE_TYPE_TRAIT(__is_pointer);
1098
3
          REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
1099
3
          REVERTIBLE_TYPE_TRAIT(__is_reference);
1100
3
          REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
1101
3
          REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
1102
3
          REVERTIBLE_TYPE_TRAIT(__is_same);
1103
3
          REVERTIBLE_TYPE_TRAIT(__is_scalar);
1104
3
          REVERTIBLE_TYPE_TRAIT(__is_sealed);
1105
3
          REVERTIBLE_TYPE_TRAIT(__is_signed);
1106
3
          REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
1107
3
          REVERTIBLE_TYPE_TRAIT(__is_trivial);
1108
3
          REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
1109
3
          REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
1110
3
          REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
1111
3
          REVERTIBLE_TYPE_TRAIT(__is_union);
1112
3
          REVERTIBLE_TYPE_TRAIT(__is_unsigned);
1113
3
          REVERTIBLE_TYPE_TRAIT(__is_void);
1114
3
          REVERTIBLE_TYPE_TRAIT(__is_volatile);
1115
3
#undef REVERTIBLE_TYPE_TRAIT
1116
3
#undef RTT_JOIN
1117
3
        }
1118
104
1119
        // If we find that this is in fact the name of a type trait,
1120
        // update the token kind in place and parse again to treat it as
1121
        // the appropriate kind of type trait.
1122
104
        llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
1123
104
          = RevertibleTypeTraits.find(II);
1124
104
        if (Known != RevertibleTypeTraits.end()) {
1125
104
          Tok.setKind(Known->second);
1126
104
          return ParseCastExpression(ParseKind, isAddressOfOperand,
1127
104
                                     NotCastExpr, isTypeCast,
1128
104
                                     isVectorLiteral, NotPrimaryExpression);
1129
104
        }
1130
6.60M
      }
1131
6.60M
1132
6.60M
      if ((!ColonIsSacred && 
Next.is(tok::colon)6.26M
) ||
1133
6.60M
          Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
1134
1.85M
                       tok::l_brace)) {
1135
        // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1136
1.85M
        if (TryAnnotateTypeOrScopeToken())
1137
4
          return ExprError();
1138
1.85M
        if (!Tok.is(tok::identifier))
1139
1.01M
          return ParseCastExpression(ParseKind, isAddressOfOperand,
1140
1.01M
                                     NotCastExpr, isTypeCast,
1141
1.01M
                                     isVectorLiteral,
1142
1.01M
                                     NotPrimaryExpression);
1143
12.7M
      }
1144
6.60M
    }
1145
12.7M
1146
    // Consume the identifier so that we can see if it is followed by a '(' or
1147
    // '.'.
1148
12.7M
    IdentifierInfo &II = *Tok.getIdentifierInfo();
1149
12.7M
    SourceLocation ILoc = ConsumeToken();
1150
12.7M
1151
    // Support 'Class.property' and 'super.property' notation.
1152
12.7M
    if (getLangOpts().ObjC && 
Tok.is(tok::period)1.36M
&&
1153
40.0k
        (Actions.getTypeName(II, ILoc, getCurScope()) ||
1154
         // Allow the base to be 'super' if in an objc-method.
1155
39.8k
         (&II == Ident_super && 
getCurScope()->isInObjcMethodScope()79
))) {
1156
266
      ConsumeToken();
1157
266
1158
266
      if (Tok.is(tok::code_completion) && 
&II != Ident_super4
) {
1159
3
        Actions.CodeCompleteObjCClassPropertyRefExpr(
1160
3
            getCurScope(), II, ILoc, ExprStatementTokLoc == ILoc);
1161
3
        cutOffParsing();
1162
3
        return ExprError();
1163
3
      }
1164
      // Allow either an identifier or the keyword 'class' (in C++).
1165
263
      if (Tok.isNot(tok::identifier) &&
1166
2
          !(getLangOpts().CPlusPlus && 
Tok.is(tok::kw_class)1
)) {
1167
1
        Diag(Tok, diag::err_expected_property_name);
1168
1
        return ExprError();
1169
1
      }
1170
262
      IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
1171
262
      SourceLocation PropertyLoc = ConsumeToken();
1172
262
1173
262
      Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
1174
262
                                              ILoc, PropertyLoc);
1175
262
      break;
1176
262
    }
1177
12.7M
1178
    // In an Objective-C method, if we have "super" followed by an identifier,
1179
    // the token sequence is ill-formed. However, if there's a ':' or ']' after
1180
    // that identifier, this is probably a message send with a missing open
1181
    // bracket. Treat it as such.
1182
12.7M
    if (getLangOpts().ObjC && 
&II == Ident_super1.36M
&&
!InMessageExpression256
&&
1183
34
        getCurScope()->isInObjcMethodScope() &&
1184
31
        ((Tok.is(tok::identifier) &&
1185
28
         (NextToken().is(tok::colon) || 
NextToken().is(tok::r_square)2
)) ||
1186
29
         
Tok.is(tok::code_completion)3
)) {
1187
29
      Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
1188
29
                                           nullptr);
1189
29
      break;
1190
29
    }
1191
12.7M
1192
    // If we have an Objective-C class name followed by an identifier
1193
    // and either ':' or ']', this is an Objective-C class message
1194
    // send that's missing the opening '['. Recovery
1195
    // appropriately. Also take this path if we're performing code
1196
    // completion after an Objective-C class name.
1197
12.7M
    if (getLangOpts().ObjC &&
1198
1.36M
        ((Tok.is(tok::identifier) && 
!InMessageExpression11.7k
) ||
1199
1.36M
         Tok.is(tok::code_completion))) {
1200
159
      const Token& Next = NextToken();
1201
159
      if (Tok.is(tok::code_completion) ||
1202
117
          Next.is(tok::colon) || 
Next.is(tok::r_square)114
)
1203
117
        if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
1204
74
          if (Typ.get()->isObjCObjectOrInterfaceType()) {
1205
            // Fake up a Declarator to use with ActOnTypeName.
1206
74
            DeclSpec DS(AttrFactory);
1207
74
            DS.SetRangeStart(ILoc);
1208
74
            DS.SetRangeEnd(ILoc);
1209
74
            const char *PrevSpec = nullptr;
1210
74
            unsigned DiagID;
1211
74
            DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
1212
74
                               Actions.getASTContext().getPrintingPolicy());
1213
74
1214
74
            Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1215
74
            TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
1216
74
                                                  DeclaratorInfo);
1217
74
            if (Ty.isInvalid())
1218
0
              break;
1219
74
1220
74
            Res = ParseObjCMessageExpressionBody(SourceLocation(),
1221
74
                                                 SourceLocation(),
1222
74
                                                 Ty.get(), nullptr);
1223
74
            break;
1224
74
          }
1225
159
    }
1226
12.7M
1227
    // Make sure to pass down the right value for isAddressOfOperand.
1228
12.7M
    if (isAddressOfOperand && 
isPostfixExpressionSuffixStart()107k
)
1229
25.3k
      isAddressOfOperand = false;
1230
12.7M
1231
    // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
1232
    // need to know whether or not this identifier is a function designator or
1233
    // not.
1234
12.7M
    UnqualifiedId Name;
1235
12.7M
    CXXScopeSpec ScopeSpec;
1236
12.7M
    SourceLocation TemplateKWLoc;
1237
12.7M
    Token Replacement;
1238
12.7M
    CastExpressionIdValidator Validator(
1239
12.7M
        /*Next=*/Tok,
1240
12.7M
        /*AllowTypes=*/isTypeCast != NotTypeCast,
1241
12.7M
        /*AllowNonTypes=*/isTypeCast != IsTypeCast);
1242
12.7M
    Validator.IsAddressOfOperand = isAddressOfOperand;
1243
12.7M
    if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
1244
115
      Validator.WantExpressionKeywords = false;
1245
115
      Validator.WantRemainingKeywords = false;
1246
12.7M
    } else {
1247
12.7M
      Validator.WantRemainingKeywords = Tok.isNot(tok::r_paren);
1248
12.7M
    }
1249
12.7M
    Name.setIdentifier(&II, ILoc);
1250
12.7M
    Res = Actions.ActOnIdExpression(
1251
12.7M
        getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
1252
12.7M
        isAddressOfOperand, &Validator,
1253
12.7M
        /*IsInlineAsmIdentifier=*/false,
1254
9.59M
        Tok.is(tok::r_paren) ? 
nullptr3.15M
: &Replacement);
1255
12.7M
    if (!Res.isInvalid() && 
Res.isUnset()12.7M
) {
1256
2
      UnconsumeToken(Replacement);
1257
2
      return ParseCastExpression(ParseKind, isAddressOfOperand,
1258
2
                                 NotCastExpr, isTypeCast,
1259
2
                                 /*isVectorLiteral=*/false,
1260
2
                                 NotPrimaryExpression);
1261
2
    }
1262
12.7M
    if (!Res.isInvalid() && 
Tok.is(tok::less)12.7M
)
1263
187k
      checkPotentialAngleBracket(Res);
1264
12.7M
    break;
1265
12.7M
  }
1266
710k
  case tok::char_constant:     // constant: character-constant
1267
710k
  case tok::wide_char_constant:
1268
710k
  case tok::utf8_char_constant:
1269
710k
  case tok::utf16_char_constant:
1270
710k
  case tok::utf32_char_constant:
1271
710k
    Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
1272
710k
    ConsumeToken();
1273
710k
    break;
1274
730
  case tok::kw___func__:       // primary-expression: __func__ [C99 6.4.2.2]
1275
730
  case tok::kw___FUNCTION__:   // primary-expression: __FUNCTION__ [GNU]
1276
730
  case tok::kw___FUNCDNAME__:   // primary-expression: __FUNCDNAME__ [MS]
1277
730
  case tok::kw___FUNCSIG__:     // primary-expression: __FUNCSIG__ [MS]
1278
730
  case tok::kw_L__FUNCTION__:   // primary-expression: L__FUNCTION__ [MS]
1279
730
  case tok::kw_L__FUNCSIG__:    // primary-expression: L__FUNCSIG__ [MS]
1280
730
  case tok::kw___PRETTY_FUNCTION__:  // primary-expression: __P..Y_F..N__ [GNU]
1281
730
    Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1282
730
    ConsumeToken();
1283
730
    break;
1284
2.90M
  case tok::string_literal:    // primary-expression: string-literal
1285
2.90M
  case tok::wide_string_literal:
1286
2.90M
  case tok::utf8_string_literal:
1287
2.90M
  case tok::utf16_string_literal:
1288
2.90M
  case tok::utf32_string_literal:
1289
2.90M
    Res = ParseStringLiteralExpression(true);
1290
2.90M
    break;
1291
396
  case tok::kw__Generic:   // primary-expression: generic-selection [C11 6.5.1]
1292
396
    Res = ParseGenericSelectionExpression();
1293
396
    break;
1294
13
  case tok::kw___builtin_available:
1295
13
    Res = ParseAvailabilityCheckExpr(Tok.getLocation());
1296
13
    break;
1297
20.5k
  case tok::kw___builtin_va_arg:
1298
20.5k
  case tok::kw___builtin_offsetof:
1299
20.5k
  case tok::kw___builtin_choose_expr:
1300
20.5k
  case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1301
20.5k
  case tok::kw___builtin_convertvector:
1302
20.5k
  case tok::kw___builtin_COLUMN:
1303
20.5k
  case tok::kw___builtin_FILE:
1304
20.5k
  case tok::kw___builtin_FUNCTION:
1305
20.5k
  case tok::kw___builtin_LINE:
1306
20.5k
    if (NotPrimaryExpression)
1307
0
      *NotPrimaryExpression = true;
1308
    // This parses the complete suffix; we can return early.
1309
20.5k
    return ParseBuiltinPrimaryExpression();
1310
2.37k
  case tok::kw___null:
1311
2.37k
    Res = Actions.ActOnGNUNullExpr(ConsumeToken());
1312
2.37k
    break;
1313
20.5k
1314
327k
  case tok::plusplus:      // unary-expression: '++' unary-expression [C99]
1315
327k
  case tok::minusminus: {  // unary-expression: '--' unary-expression [C99]
1316
327k
    if (NotPrimaryExpression)
1317
0
      *NotPrimaryExpression = true;
1318
    // C++ [expr.unary] has:
1319
    //   unary-expression:
1320
    //     ++ cast-expression
1321
    //     -- cast-expression
1322
327k
    Token SavedTok = Tok;
1323
327k
    ConsumeToken();
1324
327k
1325
327k
    PreferredType.enterUnary(Actions, Tok.getLocation(), SavedTok.getKind(),
1326
327k
                             SavedTok.getLocation());
1327
    // One special case is implicitly handled here: if the preceding tokens are
1328
    // an ambiguous cast expression, such as "(T())++", then we recurse to
1329
    // determine whether the '++' is prefix or postfix.
1330
327k
    Res = ParseCastExpression(getLangOpts().CPlusPlus ?
1331
318k
                                  UnaryExprOnly : 
AnyCastExpr9.30k
,
1332
327k
                              /*isAddressOfOperand*/false, NotCastExpr,
1333
327k
                              NotTypeCast);
1334
327k
    if (NotCastExpr) {
1335
      // If we return with NotCastExpr = true, we must not consume any tokens,
1336
      // so put the token back where we found it.
1337
7
      assert(Res.isInvalid());
1338
7
      UnconsumeToken(SavedTok);
1339
7
      return ExprError();
1340
7
    }
1341
327k
    if (!Res.isInvalid()) {
1342
327k
      Expr *Arg = Res.get();
1343
327k
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1344
327k
                                 SavedKind, Arg);
1345
327k
      if (Res.isInvalid())
1346
67
        Res = Actions.CreateRecoveryExpr(SavedTok.getLocation(),
1347
67
                                         Arg->getEndLoc(), Arg);
1348
327k
    }
1349
327k
    return Res;
1350
327k
  }
1351
120k
  case tok::amp: {         // unary-expression: '&' cast-expression
1352
120k
    if (NotPrimaryExpression)
1353
0
      *NotPrimaryExpression = true;
1354
    // Special treatment because of member pointers
1355
120k
    SourceLocation SavedLoc = ConsumeToken();
1356
120k
    PreferredType.enterUnary(Actions, Tok.getLocation(), tok::amp, SavedLoc);
1357
120k
    Res = ParseCastExpression(AnyCastExpr, true);
1358
120k
    if (!Res.isInvalid()) {
1359
120k
      Expr *Arg = Res.get();
1360
120k
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg);
1361
120k
      if (Res.isInvalid())
1362
191
        Res = Actions.CreateRecoveryExpr(Tok.getLocation(), Arg->getEndLoc(),
1363
191
                                         Arg);
1364
120k
    }
1365
120k
    return Res;
1366
327k
  }
1367
327k
1368
1.89M
  case tok::star:          // unary-expression: '*' cast-expression
1369
1.89M
  case tok::plus:          // unary-expression: '+' cast-expression
1370
1.89M
  case tok::minus:         // unary-expression: '-' cast-expression
1371
1.89M
  case tok::tilde:         // unary-expression: '~' cast-expression
1372
1.89M
  case tok::exclaim:       // unary-expression: '!' cast-expression
1373
1.89M
  case tok::kw___real:     // unary-expression: '__real' cast-expression [GNU]
1374
1.89M
  case tok::kw___imag: {   // unary-expression: '__imag' cast-expression [GNU]
1375
1.89M
    if (NotPrimaryExpression)
1376
0
      *NotPrimaryExpression = true;
1377
1.89M
    SourceLocation SavedLoc = ConsumeToken();
1378
1.89M
    PreferredType.enterUnary(Actions, Tok.getLocation(), SavedKind, SavedLoc);
1379
1.89M
    Res = ParseCastExpression(AnyCastExpr);
1380
1.89M
    if (!Res.isInvalid()) {
1381
1.89M
      Expr *Arg = Res.get();
1382
1.89M
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg);
1383
1.89M
      if (Res.isInvalid())
1384
157
        Res = Actions.CreateRecoveryExpr(SavedLoc, Arg->getEndLoc(), Arg);
1385
1.89M
    }
1386
1.89M
    return Res;
1387
1.89M
  }
1388
1.89M
1389
120
  case tok::kw_co_await: {  // unary-expression: 'co_await' cast-expression
1390
120
    if (NotPrimaryExpression)
1391
0
      *NotPrimaryExpression = true;
1392
120
    SourceLocation CoawaitLoc = ConsumeToken();
1393
120
    Res = ParseCastExpression(AnyCastExpr);
1394
120
    if (!Res.isInvalid())
1395
120
      Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1396
120
    return Res;
1397
1.89M
  }
1398
1.89M
1399
31.2k
  case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1400
    // __extension__ silences extension warnings in the subexpression.
1401
31.2k
    if (NotPrimaryExpression)
1402
0
      *NotPrimaryExpression = true;
1403
31.2k
    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1404
31.2k
    SourceLocation SavedLoc = ConsumeToken();
1405
31.2k
    Res = ParseCastExpression(AnyCastExpr);
1406
31.2k
    if (!Res.isInvalid())
1407
31.2k
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1408
31.2k
    return Res;
1409
1.89M
  }
1410
97
  case tok::kw__Alignof:   // unary-expression: '_Alignof' '(' type-name ')'
1411
97
    if (!getLangOpts().C11)
1412
26
      Diag(Tok, diag::ext_c11_feature) << Tok.getName();
1413
97
    LLVM_FALLTHROUGH;
1414
126k
  case tok::kw_alignof:    // unary-expression: 'alignof' '(' type-id ')'
1415
126k
  case tok::kw___alignof:  // unary-expression: '__alignof' unary-expression
1416
                           // unary-expression: '__alignof' '(' type-name ')'
1417
126k
  case tok::kw_sizeof:     // unary-expression: 'sizeof' unary-expression
1418
                           // unary-expression: 'sizeof' '(' type-name ')'
1419
126k
  case tok::kw_vec_step:   // unary-expression: OpenCL 'vec_step' expression
1420
  // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1421
126k
  case tok::kw___builtin_omp_required_simd_align:
1422
126k
    if (NotPrimaryExpression)
1423
2
      *NotPrimaryExpression = true;
1424
126k
    AllowSuffix = false;
1425
126k
    Res = ParseUnaryExprOrTypeTraitExpression();
1426
126k
    break;
1427
265
  case tok::ampamp: {      // unary-expression: '&&' identifier
1428
265
    if (NotPrimaryExpression)
1429
0
      *NotPrimaryExpression = true;
1430
265
    SourceLocation AmpAmpLoc = ConsumeToken();
1431
265
    if (Tok.isNot(tok::identifier))
1432
0
      return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1433
265
1434
265
    if (getCurScope()->getFnParent() == nullptr)
1435
1
      return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1436
264
1437
264
    Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1438
264
    LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1439
264
                                                Tok.getLocation());
1440
264
    Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1441
264
    ConsumeToken();
1442
264
    AllowSuffix = false;
1443
264
    break;
1444
264
  }
1445
115k
  case tok::kw_const_cast:
1446
115k
  case tok::kw_dynamic_cast:
1447
115k
  case tok::kw_reinterpret_cast:
1448
115k
  case tok::kw_static_cast:
1449
115k
  case tok::kw_addrspace_cast:
1450
115k
    if (NotPrimaryExpression)
1451
0
      *NotPrimaryExpression = true;
1452
115k
    Res = ParseCXXCasts();
1453
115k
    break;
1454
585
  case tok::kw___builtin_bit_cast:
1455
585
    if (NotPrimaryExpression)
1456
0
      *NotPrimaryExpression = true;
1457
585
    Res = ParseBuiltinBitCast();
1458
585
    break;
1459
5.12k
  case tok::kw_typeid:
1460
5.12k
    if (NotPrimaryExpression)
1461
0
      *NotPrimaryExpression = true;
1462
5.12k
    Res = ParseCXXTypeid();
1463
5.12k
    break;
1464
171
  case tok::kw___uuidof:
1465
171
    if (NotPrimaryExpression)
1466
0
      *NotPrimaryExpression = true;
1467
171
    Res = ParseCXXUuidof();
1468
171
    break;
1469
193k
  case tok::kw_this:
1470
193k
    Res = ParseCXXThis();
1471
193k
    break;
1472
23
  case tok::kw___builtin_unique_stable_name:
1473
23
    Res = ParseUniqueStableNameExpression();
1474
23
    break;
1475
273k
  case tok::annot_typename:
1476
273k
    if (isStartOfObjCClassMessageMissingOpenBracket()) {
1477
81
      TypeResult Type = getTypeAnnotation(Tok);
1478
81
1479
      // Fake up a Declarator to use with ActOnTypeName.
1480
81
      DeclSpec DS(AttrFactory);
1481
81
      DS.SetRangeStart(Tok.getLocation());
1482
81
      DS.SetRangeEnd(Tok.getLastLoc());
1483
81
1484
81
      const char *PrevSpec = nullptr;
1485
81
      unsigned DiagID;
1486
81
      DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1487
81
                         PrevSpec, DiagID, Type,
1488
81
                         Actions.getASTContext().getPrintingPolicy());
1489
81
1490
81
      Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1491
81
      TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1492
81
      if (Ty.isInvalid())
1493
0
        break;
1494
81
1495
81
      ConsumeAnnotationToken();
1496
81
      Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1497
81
                                           Ty.get(), nullptr);
1498
81
      break;
1499
81
    }
1500
273k
    LLVM_FALLTHROUGH;
1501
273k
1502
300k
  case tok::annot_decltype:
1503
300k
  case tok::kw_char:
1504
300k
  case tok::kw_wchar_t:
1505
300k
  case tok::kw_char8_t:
1506
300k
  case tok::kw_char16_t:
1507
300k
  case tok::kw_char32_t:
1508
300k
  case tok::kw_bool:
1509
300k
  case tok::kw_short:
1510
300k
  case tok::kw_int:
1511
300k
  case tok::kw_long:
1512
300k
  case tok::kw___int64:
1513
300k
  case tok::kw___int128:
1514
300k
  case tok::kw__ExtInt:
1515
300k
  case tok::kw_signed:
1516
300k
  case tok::kw_unsigned:
1517
300k
  case tok::kw_half:
1518
300k
  case tok::kw_float:
1519
300k
  case tok::kw_double:
1520
300k
  case tok::kw___bf16:
1521
300k
  case tok::kw__Float16:
1522
300k
  case tok::kw___float128:
1523
300k
  case tok::kw_void:
1524
300k
  case tok::kw_typename:
1525
300k
  case tok::kw_typeof:
1526
300k
  case tok::kw___vector:
1527
3.60M
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1528
3.60M
#include 
"clang/Basic/OpenCLImageTypes.def"300k
1529
3.60M
  {
1530
300k
    if (!getLangOpts().CPlusPlus) {
1531
295
      Diag(Tok, diag::err_expected_expression);
1532
295
      return ExprError();
1533
295
    }
1534
300k
1535
    // Everything henceforth is a postfix-expression.
1536
300k
    if (NotPrimaryExpression)
1537
2
      *NotPrimaryExpression = true;
1538
300k
1539
300k
    if (SavedKind == tok::kw_typename) {
1540
      // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1541
      //                     typename-specifier braced-init-list
1542
21.5k
      if (TryAnnotateTypeOrScopeToken())
1543
5
        return ExprError();
1544
21.5k
1545
21.5k
      if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1546
        // We are trying to parse a simple-type-specifier but might not get such
1547
        // a token after error recovery.
1548
0
        return ExprError();
1549
300k
    }
1550
300k
1551
    // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1552
    //                     simple-type-specifier braced-init-list
1553
    //
1554
300k
    DeclSpec DS(AttrFactory);
1555
300k
1556
300k
    ParseCXXSimpleTypeSpecifier(DS);
1557
300k
    if (Tok.isNot(tok::l_paren) &&
1558
5.55k
        (!getLangOpts().CPlusPlus11 || 
Tok.isNot(tok::l_brace)5.55k
))
1559
36
      return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1560
36
                         << DS.getSourceRange());
1561
300k
1562
300k
    if (Tok.is(tok::l_brace))
1563
5.52k
      Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1564
300k
1565
300k
    Res = ParseCXXTypeConstructExpression(DS);
1566
300k
    break;
1567
300k
  }
1568
300k
1569
970k
  case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1570
    // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1571
    // (We can end up in this situation after tentative parsing.)
1572
970k
    if (TryAnnotateTypeOrScopeToken())
1573
0
      return ExprError();
1574
970k
    if (!Tok.is(tok::annot_cxxscope))
1575
4
      return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1576
4
                                 isTypeCast, isVectorLiteral,
1577
4
                                 NotPrimaryExpression);
1578
970k
1579
970k
    Token Next = NextToken();
1580
970k
    if (Next.is(tok::annot_template_id)) {
1581
130k
      TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1582
130k
      if (TemplateId->Kind == TNK_Type_template) {
1583
        // We have a qualified template-id that we know refers to a
1584
        // type, translate it into a type and continue parsing as a
1585
        // cast expression.
1586
0
        CXXScopeSpec SS;
1587
0
        ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1588
0
                                       /*ObjectHadErrors=*/false,
1589
0
                                       /*EnteringContext=*/false);
1590
0
        AnnotateTemplateIdTokenAsType(SS);
1591
0
        return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1592
0
                                   isTypeCast, isVectorLiteral,
1593
0
                                   NotPrimaryExpression);
1594
0
      }
1595
970k
    }
1596
970k
1597
    // Parse as an id-expression.
1598
970k
    Res = ParseCXXIdExpression(isAddressOfOperand);
1599
970k
    break;
1600
970k
  }
1601
970k
1602
87.1k
  case tok::annot_template_id: { // [C++]          template-id
1603
87.1k
    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1604
87.1k
    if (TemplateId->Kind == TNK_Type_template) {
1605
      // We have a template-id that we know refers to a type,
1606
      // translate it into a type and continue parsing as a cast
1607
      // expression.
1608
49
      CXXScopeSpec SS;
1609
49
      AnnotateTemplateIdTokenAsType(SS);
1610
49
      return ParseCastExpression(ParseKind, isAddressOfOperand,
1611
49
                                 NotCastExpr, isTypeCast, isVectorLiteral,
1612
49
                                 NotPrimaryExpression);
1613
49
    }
1614
87.0k
1615
    // Fall through to treat the template-id as an id-expression.
1616
87.0k
    LLVM_FALLTHROUGH;
1617
87.0k
  }
1618
87.0k
1619
89.4k
  case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1620
89.4k
    Res = ParseCXXIdExpression(isAddressOfOperand);
1621
89.4k
    break;
1622
87.0k
1623
28.7k
  case tok::coloncolon: {
1624
    // ::foo::bar -> global qualified name etc.   If TryAnnotateTypeOrScopeToken
1625
    // annotates the token, tail recurse.
1626
28.7k
    if (TryAnnotateTypeOrScopeToken())
1627
4
      return ExprError();
1628
28.6k
    if (!Tok.is(tok::coloncolon))
1629
12.9k
      return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1630
12.9k
                                 isVectorLiteral, NotPrimaryExpression);
1631
15.7k
1632
    // ::new -> [C++] new-expression
1633
    // ::delete -> [C++] delete-expression
1634
15.7k
    SourceLocation CCLoc = ConsumeToken();
1635
15.7k
    if (Tok.is(tok::kw_new)) {
1636
15.6k
      if (NotPrimaryExpression)
1637
0
        *NotPrimaryExpression = true;
1638
15.6k
      Res = ParseCXXNewExpression(true, CCLoc);
1639
15.6k
      AllowSuffix = false;
1640
15.6k
      break;
1641
15.6k
    }
1642
51
    if (Tok.is(tok::kw_delete)) {
1643
51
      if (NotPrimaryExpression)
1644
0
        *NotPrimaryExpression = true;
1645
51
      Res = ParseCXXDeleteExpression(true, CCLoc);
1646
51
      AllowSuffix = false;
1647
51
      break;
1648
51
    }
1649
0
1650
    // This is not a type name or scope specifier, it is an invalid expression.
1651
0
    Diag(CCLoc, diag::err_expected_expression);
1652
0
    return ExprError();
1653
0
  }
1654
0
1655
7.93k
  case tok::kw_new: // [C++] new-expression
1656
7.93k
    if (NotPrimaryExpression)
1657
0
      *NotPrimaryExpression = true;
1658
7.93k
    Res = ParseCXXNewExpression(false, Tok.getLocation());
1659
7.93k
    AllowSuffix = false;
1660
7.93k
    break;
1661
0
1662
3.77k
  case tok::kw_delete: // [C++] delete-expression
1663
3.77k
    if (NotPrimaryExpression)
1664
0
      *NotPrimaryExpression = true;
1665
3.77k
    Res = ParseCXXDeleteExpression(false, Tok.getLocation());
1666
3.77k
    AllowSuffix = false;
1667
3.77k
    break;
1668
0
1669
229
  case tok::kw_requires: // [C++2a] requires-expression
1670
229
    Res = ParseRequiresExpression();
1671
229
    AllowSuffix = false;
1672
229
    break;
1673
0
1674
11.5k
  case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1675
11.5k
    if (NotPrimaryExpression)
1676
0
      *NotPrimaryExpression = true;
1677
11.5k
    Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1678
11.5k
    SourceLocation KeyLoc = ConsumeToken();
1679
11.5k
    BalancedDelimiterTracker T(*this, tok::l_paren);
1680
11.5k
1681
11.5k
    if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1682
0
      return ExprError();
1683
    // C++11 [expr.unary.noexcept]p1:
1684
    //   The noexcept operator determines whether the evaluation of its operand,
1685
    //   which is an unevaluated operand, can throw an exception.
1686
11.5k
    EnterExpressionEvaluationContext Unevaluated(
1687
11.5k
        Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1688
11.5k
    Res = ParseExpression();
1689
11.5k
1690
11.5k
    T.consumeClose();
1691
11.5k
1692
11.5k
    if (!Res.isInvalid())
1693
11.5k
      Res = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), Res.get(),
1694
11.5k
                                      T.getCloseLocation());
1695
11.5k
    AllowSuffix = false;
1696
11.5k
    break;
1697
11.5k
  }
1698
11.5k
1699
11.5k
#define TYPE_TRAIT(N,Spelling,K) \
1700
1.67M
  case tok::kw_##Spelling:
1701
26.2k
#include 
"clang/Basic/TokenKinds.def"11.5k
1702
26.2k
    Res = ParseTypeTrait();
1703
26.2k
    break;
1704
1.65M
1705
465
  case tok::kw___array_rank:
1706
465
  case tok::kw___array_extent:
1707
465
    if (NotPrimaryExpression)
1708
0
      *NotPrimaryExpression = true;
1709
465
    Res = ParseArrayTypeTrait();
1710
465
    break;
1711
465
1712
439
  case tok::kw___is_lvalue_expr:
1713
439
  case tok::kw___is_rvalue_expr:
1714
439
    if (NotPrimaryExpression)
1715
0
      *NotPrimaryExpression = true;
1716
439
    Res = ParseExpressionTrait();
1717
439
    break;
1718
439
1719
8.47k
  case tok::at: {
1720
8.47k
    if (NotPrimaryExpression)
1721
0
      *NotPrimaryExpression = true;
1722
8.47k
    SourceLocation AtLoc = ConsumeToken();
1723
8.47k
    return ParseObjCAtExpression(AtLoc);
1724
439
  }
1725
2.84k
  case tok::caret:
1726
2.84k
    Res = ParseBlockLiteralExpression();
1727
2.84k
    break;
1728
92
  case tok::code_completion: {
1729
92
    Actions.CodeCompleteExpression(getCurScope(),
1730
92
                                   PreferredType.get(Tok.getLocation()));
1731
92
    cutOffParsing();
1732
92
    return ExprError();
1733
439
  }
1734
29.1k
  case tok::l_square:
1735
29.1k
    if (getLangOpts().CPlusPlus11) {
1736
8.72k
      if (getLangOpts().ObjC) {
1737
        // C++11 lambda expressions and Objective-C message sends both start with a
1738
        // square bracket.  There are three possibilities here:
1739
        // we have a valid lambda expression, we have an invalid lambda
1740
        // expression, or we have something that doesn't appear to be a lambda.
1741
        // If we're in the last case, we fall back to ParseObjCMessageExpression.
1742
2.92k
        Res = TryParseLambdaExpression();
1743
2.92k
        if (!Res.isInvalid() && 
!Res.get()2.91k
) {
1744
          // We assume Objective-C++ message expressions are not
1745
          // primary-expressions.
1746
2.72k
          if (NotPrimaryExpression)
1747
0
            *NotPrimaryExpression = true;
1748
2.72k
          Res = ParseObjCMessageExpression();
1749
2.72k
        }
1750
2.92k
        break;
1751
2.92k
      }
1752
5.80k
      Res = ParseLambdaExpression();
1753
5.80k
      break;
1754
5.80k
    }
1755
20.4k
    if (getLangOpts().ObjC) {
1756
20.4k
      Res = ParseObjCMessageExpression();
1757
20.4k
      break;
1758
20.4k
    }
1759
11
    LLVM_FALLTHROUGH;
1760
14.6k
  default:
1761
14.6k
    NotCastExpr = true;
1762
14.6k
    return ExprError();
1763
30.6M
  }
1764
30.6M
1765
  // Check to see whether Res is a function designator only. If it is and we
1766
  // are compiling for OpenCL, we need to return an error as this implies
1767
  // that the address of the function is being taken, which is illegal in CL.
1768
30.6M
1769
30.6M
  if (ParseKind == PrimaryExprOnly)
1770
    // This is strictly a primary-expression - no postfix-expr pieces should be
1771
    // parsed.
1772
422
    return Res;
1773
30.6M
1774
30.6M
  if (!AllowSuffix) {
1775
    // FIXME: Don't parse a primary-expression suffix if we encountered a parse
1776
    // error already.
1777
165k
    if (Res.isInvalid())
1778
647
      return Res;
1779
165k
1780
165k
    switch (Tok.getKind()) {
1781
6
    case tok::l_square:
1782
6
    case tok::l_paren:
1783
6
    case tok::plusplus:
1784
6
    case tok::minusminus:
1785
      // "expected ';'" or similar is probably the right diagnostic here. Let
1786
      // the caller decide what to do.
1787
6
      if (Tok.isAtStartOfLine())
1788
1
        return Res;
1789
5
1790
5
      LLVM_FALLTHROUGH;
1791
7
    case tok::period:
1792
7
    case tok::arrow:
1793
7
      break;
1794
7
1795
164k
    default:
1796
164k
      return Res;
1797
7
    }
1798
7
1799
    // This was a unary-expression for which a postfix-expression suffix is
1800
    // not permitted by the grammar (eg, a sizeof expression or
1801
    // new-expression or similar). Diagnose but parse the suffix anyway.
1802
7
    Diag(Tok.getLocation(), diag::err_postfix_after_unary_requires_parens)
1803
7
        << Tok.getKind() << Res.get()->getSourceRange()
1804
7
        << FixItHint::CreateInsertion(Res.get()->getBeginLoc(), "(")
1805
7
        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(PrevTokLocation),
1806
7
                                      ")");
1807
7
  }
1808
30.6M
1809
  // These can be followed by postfix-expr pieces.
1810
30.4M
  PreferredType = SavedType;
1811
30.4M
  Res = ParsePostfixExpressionSuffix(Res);
1812
30.4M
  if (getLangOpts().OpenCL)
1813
20.3k
    if (Expr *PostfixExpr = Res.get()) {
1814
19.8k
      QualType Ty = PostfixExpr->getType();
1815
19.8k
      if (!Ty.isNull() && 
Ty->isFunctionType()19.6k
) {
1816
6
        Diag(PostfixExpr->getExprLoc(),
1817
6
             diag::err_opencl_taking_function_address_parser);
1818
6
        return ExprError();
1819
6
      }
1820
30.4M
    }
1821
30.4M
1822
30.4M
  return Res;
1823
30.4M
}
1824
1825
/// Once the leading part of a postfix-expression is parsed, this
1826
/// method parses any suffixes that apply.
1827
///
1828
/// \verbatim
1829
///       postfix-expression: [C99 6.5.2]
1830
///         primary-expression
1831
///         postfix-expression '[' expression ']'
1832
///         postfix-expression '[' braced-init-list ']'
1833
///         postfix-expression '(' argument-expression-list[opt] ')'
1834
///         postfix-expression '.' identifier
1835
///         postfix-expression '->' identifier
1836
///         postfix-expression '++'
1837
///         postfix-expression '--'
1838
///         '(' type-name ')' '{' initializer-list '}'
1839
///         '(' type-name ')' '{' initializer-list ',' '}'
1840
///
1841
///       argument-expression-list: [C99 6.5.2]
1842
///         argument-expression ...[opt]
1843
///         argument-expression-list ',' assignment-expression ...[opt]
1844
/// \endverbatim
1845
ExprResult
1846
30.5M
Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1847
  // Now that the primary-expression piece of the postfix-expression has been
1848
  // parsed, see if there are any postfix-expression pieces here.
1849
30.5M
  SourceLocation Loc;
1850
30.5M
  auto SavedType = PreferredType;
1851
36.3M
  while (1) {
1852
    // Each iteration relies on preferred type for the whole expression.
1853
36.3M
    PreferredType = SavedType;
1854
36.3M
    switch (Tok.getKind()) {
1855
67
    case tok::code_completion:
1856
67
      if (InMessageExpression)
1857
57
        return LHS;
1858
10
1859
10
      Actions.CodeCompletePostfixExpression(
1860
10
          getCurScope(), LHS, PreferredType.get(Tok.getLocation()));
1861
10
      cutOffParsing();
1862
10
      return ExprError();
1863
10
1864
21.0k
    case tok::identifier:
1865
      // If we see identifier: after an expression, and we're not already in a
1866
      // message send, then this is probably a message send with a missing
1867
      // opening bracket '['.
1868
21.0k
      if (getLangOpts().ObjC && 
!InMessageExpression19.4k
&&
1869
281
          (NextToken().is(tok::colon) || 
NextToken().is(tok::r_square)195
)) {
1870
173
        LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1871
173
                                             nullptr, LHS.get());
1872
173
        break;
1873
173
      }
1874
      // Fall through; this isn't a message send.
1875
20.8k
      LLVM_FALLTHROUGH;
1876
20.8k
1877
30.5M
    default:  // Not a postfix-expression suffix.
1878
30.5M
      return LHS;
1879
269k
    case tok::l_square: {  // postfix-expression: p-e '[' expression ']'
1880
      // If we have a array postfix expression that starts on a new line and
1881
      // Objective-C is enabled, it is highly likely that the user forgot a
1882
      // semicolon after the base expression and that the array postfix-expr is
1883
      // actually another message send.  In this case, do some look-ahead to see
1884
      // if the contents of the square brackets are obviously not a valid
1885
      // expression and recover by pretending there is no suffix.
1886
269k
      if (getLangOpts().ObjC && 
Tok.isAtStartOfLine()39.4k
&&
1887
5
          isSimpleObjCMessageExpression())
1888
4
        return LHS;
1889
269k
1890
      // Reject array indices starting with a lambda-expression. '[[' is
1891
      // reserved for attributes.
1892
269k
      if (CheckProhibitedCXX11Attribute()) {
1893
2
        (void)Actions.CorrectDelayedTyposInExpr(LHS);
1894
2
        return ExprError();
1895
2
      }
1896
269k
1897
269k
      BalancedDelimiterTracker T(*this, tok::l_square);
1898
269k
      T.consumeOpen();
1899
269k
      Loc = T.getOpenLocation();
1900
269k
      ExprResult Idx, Length, Stride;
1901
269k
      SourceLocation ColonLocFirst, ColonLocSecond;
1902
269k
      PreferredType.enterSubscript(Actions, Tok.getLocation(), LHS.get());
1903
269k
      if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)156k
) {
1904
4
        Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1905
4
        Idx = ParseBraceInitializer();
1906
269k
      } else if (getLangOpts().OpenMP) {
1907
100k
        ColonProtectionRAIIObject RAII(*this);
1908
        // Parse [: or [ expr or [ expr :
1909
100k
        if (!Tok.is(tok::colon)) {
1910
          // [ expr
1911
94.7k
          Idx = ParseExpression();
1912
94.7k
        }
1913
100k
        if (Tok.is(tok::colon)) {
1914
          // Consume ':'
1915
9.13k
          ColonLocFirst = ConsumeToken();
1916
9.13k
          if (Tok.isNot(tok::r_square) &&
1917
6.93k
              (getLangOpts().OpenMP < 50 ||
1918
4.76k
               ((Tok.isNot(tok::colon) && getLangOpts().OpenMP >= 50))))
1919
6.93k
            Length = ParseExpression();
1920
9.13k
        }
1921
100k
        if (getLangOpts().OpenMP >= 50 &&
1922
80.4k
            (OMPClauseKind == llvm::omp::Clause::OMPC_to ||
1923
80.2k
             OMPClauseKind == llvm::omp::Clause::OMPC_from) &&
1924
485
            Tok.is(tok::colon)) {
1925
          // Consume ':'
1926
56
          ColonLocSecond = ConsumeToken();
1927
56
          if (Tok.isNot(tok::r_square)) {
1928
56
            Stride = ParseExpression();
1929
56
          }
1930
56
        }
1931
100k
      } else
1932
169k
        Idx = ParseExpression();
1933
269k
1934
269k
      SourceLocation RLoc = Tok.getLocation();
1935
269k
1936
269k
      LHS = Actions.CorrectDelayedTyposInExpr(LHS);
1937
269k
      Idx = Actions.CorrectDelayedTyposInExpr(Idx);
1938
269k
      Length = Actions.CorrectDelayedTyposInExpr(Length);
1939
269k
      if (!LHS.isInvalid() && 
!Idx.isInvalid()269k
&&
!Length.isInvalid()268k
&&
1940
268k
          !Stride.isInvalid() && Tok.is(tok::r_square)) {
1941
268k
        if (ColonLocFirst.isValid() || 
ColonLocSecond.isValid()259k
) {
1942
8.74k
          LHS = Actions.ActOnOMPArraySectionExpr(
1943
8.74k
              LHS.get(), Loc, Idx.get(), ColonLocFirst, ColonLocSecond,
1944
8.74k
              Length.get(), Stride.get(), RLoc);
1945
259k
        } else {
1946
259k
          LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1947
259k
                                                Idx.get(), RLoc);
1948
259k
        }
1949
786
      } else {
1950
786
        LHS = ExprError();
1951
786
        Idx = ExprError();
1952
786
      }
1953
269k
1954
      // Match the ']'.
1955
269k
      T.consumeClose();
1956
269k
      break;
1957
269k
    }
1958
269k
1959
4.44M
    case tok::l_paren:         // p-e: p-e '(' argument-expression-list[opt] ')'
1960
4.44M
    case tok::lesslessless: {  // p-e: p-e '<<<' argument-expression-list '>>>'
1961
                               //   '(' argument-expression-list[opt] ')'
1962
4.44M
      tok::TokenKind OpKind = Tok.getKind();
1963
4.44M
      InMessageExpressionRAIIObject InMessage(*this, false);
1964
4.44M
1965
4.44M
      Expr *ExecConfig = nullptr;
1966
4.44M
1967
4.44M
      BalancedDelimiterTracker PT(*this, tok::l_paren);
1968
4.44M
1969
4.44M
      if (OpKind == tok::lesslessless) {
1970
105
        ExprVector ExecConfigExprs;
1971
105
        CommaLocsTy ExecConfigCommaLocs;
1972
105
        SourceLocation OpenLoc = ConsumeToken();
1973
105
1974
105
        if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1975
1
          (void)Actions.CorrectDelayedTyposInExpr(LHS);
1976
1
          LHS = ExprError();
1977
1
        }
1978
105
1979
105
        SourceLocation CloseLoc;
1980
105
        if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1981
1
        } else if (LHS.isInvalid()) {
1982
0
          SkipUntil(tok::greatergreatergreater, StopAtSemi);
1983
1
        } else {
1984
          // There was an error closing the brackets
1985
1
          Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1986
1
          Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1987
1
          SkipUntil(tok::greatergreatergreater, StopAtSemi);
1988
1
          LHS = ExprError();
1989
1
        }
1990
105
1991
105
        if (!LHS.isInvalid()) {
1992
98
          if (ExpectAndConsume(tok::l_paren))
1993
1
            LHS = ExprError();
1994
97
          else
1995
97
            Loc = PrevTokLocation;
1996
98
        }
1997
105
1998
105
        if (!LHS.isInvalid()) {
1999
97
          ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
2000
97
                                    OpenLoc,
2001
97
                                    ExecConfigExprs,
2002
97
                                    CloseLoc);
2003
97
          if (ECResult.isInvalid())
2004
2
            LHS = ExprError();
2005
95
          else
2006
95
            ExecConfig = ECResult.get();
2007
97
        }
2008
4.44M
      } else {
2009
4.44M
        PT.consumeOpen();
2010
4.44M
        Loc = PT.getOpenLocation();
2011
4.44M
      }
2012
4.44M
2013
4.44M
      ExprVector ArgExprs;
2014
4.44M
      CommaLocsTy CommaLocs;
2015
173
      auto RunSignatureHelp = [&]() -> QualType {
2016
173
        QualType PreferredType = Actions.ProduceCallSignatureHelp(
2017
173
            getCurScope(), LHS.get(), ArgExprs, PT.getOpenLocation());
2018
173
        CalledSignatureHelp = true;
2019
173
        return PreferredType;
2020
173
      };
2021
4.44M
      if (OpKind == tok::l_paren || 
!LHS.isInvalid()105
) {
2022
4.44M
        if (Tok.isNot(tok::r_paren)) {
2023
8.26M
          if (
ParseExpressionList(ArgExprs, CommaLocs, [&] 3.36M
{
2024
8.26M
                PreferredType.enterFunctionArgument(Tok.getLocation(),
2025
8.26M
                                                    RunSignatureHelp);
2026
4.67k
              })) {
2027
4.67k
            (void)Actions.CorrectDelayedTyposInExpr(LHS);
2028
            // If we got an error when parsing expression list, we don't call
2029
            // the CodeCompleteCall handler inside the parser. So call it here
2030
            // to make sure we get overload suggestions even when we are in the
2031
            // middle of a parameter.
2032
4.67k
            if (PP.isCodeCompletionReached() && 
!CalledSignatureHelp173
)
2033
5
              RunSignatureHelp();
2034
4.67k
            LHS = ExprError();
2035
3.36M
          } else if (LHS.isInvalid()) {
2036
108
            for (auto &E : ArgExprs)
2037
126
              Actions.CorrectDelayedTyposInExpr(E);
2038
108
          }
2039
3.36M
        }
2040
4.44M
      }
2041
4.44M
2042
      // Match the ')'.
2043
4.44M
      if (LHS.isInvalid()) {
2044
4.96k
        SkipUntil(tok::r_paren, StopAtSemi);
2045
4.44M
      } else if (Tok.isNot(tok::r_paren)) {
2046
1.14k
        bool HadDelayedTypo = false;
2047
1.14k
        if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
2048
0
          HadDelayedTypo = true;
2049
1.14k
        for (auto &E : ArgExprs)
2050
1.14k
          if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
2051
11
            HadDelayedTypo = true;
2052
        // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
2053
        // instead of PT.consumeClose() to avoid emitting extra diagnostics for
2054
        // the unmatched l_paren.
2055
1.14k
        if (HadDelayedTypo)
2056
11
          SkipUntil(tok::r_paren, StopAtSemi);
2057
1.13k
        else
2058
1.13k
          PT.consumeClose();
2059
1.14k
        LHS = ExprError();
2060
4.44M
      } else {
2061
4.44M
        assert(
2062
4.44M
            (ArgExprs.size() == 0 || ArgExprs.size() - 1 == CommaLocs.size()) &&
2063
4.44M
            "Unexpected number of commas!");
2064
4.44M
        Expr *Fn = LHS.get();
2065
4.44M
        SourceLocation RParLoc = Tok.getLocation();
2066
4.44M
        LHS = Actions.ActOnCallExpr(getCurScope(), Fn, Loc, ArgExprs, RParLoc,
2067
4.44M
                                    ExecConfig);
2068
4.44M
        if (LHS.isInvalid()) {
2069
5.08k
          ArgExprs.insert(ArgExprs.begin(), Fn);
2070
5.08k
          LHS =
2071
5.08k
              Actions.CreateRecoveryExpr(Fn->getBeginLoc(), RParLoc, ArgExprs);
2072
5.08k
        }
2073
4.44M
        PT.consumeClose();
2074
4.44M
      }
2075
4.44M
2076
4.44M
      break;
2077
4.44M
    }
2078
1.13M
    case tok::arrow:
2079
1.13M
    case tok::period: {
2080
      // postfix-expression: p-e '->' template[opt] id-expression
2081
      // postfix-expression: p-e '.' template[opt] id-expression
2082
1.13M
      tok::TokenKind OpKind = Tok.getKind();
2083
1.13M
      SourceLocation OpLoc = ConsumeToken();  // Eat the "." or "->" token.
2084
1.13M
2085
1.13M
      CXXScopeSpec SS;
2086
1.13M
      ParsedType ObjectType;
2087
1.13M
      bool MayBePseudoDestructor = false;
2088
1.13M
      Expr* OrigLHS = !LHS.isInvalid() ? LHS.get() : 
nullptr310
;
2089
1.13M
2090
1.13M
      PreferredType.enterMemAccess(Actions, Tok.getLocation(), OrigLHS);
2091
1.13M
2092
1.13M
      if (getLangOpts().CPlusPlus && 
!LHS.isInvalid()1.00M
) {
2093
1.00M
        Expr *Base = OrigLHS;
2094
1.00M
        const Type* BaseType = Base->getType().getTypePtrOrNull();
2095
1.00M
        if (BaseType && 
Tok.is(tok::l_paren)1.00M
&&
2096
13
            (BaseType->isFunctionType() ||
2097
10
             
BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember)8
)) {
2098
10
          Diag(OpLoc, diag::err_function_is_not_record)
2099
10
              << OpKind << Base->getSourceRange()
2100
10
              << FixItHint::CreateRemoval(OpLoc);
2101
10
          return ParsePostfixExpressionSuffix(Base);
2102
10
        }
2103
1.00M
2104
1.00M
        LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base, OpLoc,
2105
1.00M
                                                   OpKind, ObjectType,
2106
1.00M
                                                   MayBePseudoDestructor);
2107
1.00M
        if (LHS.isInvalid()) {
2108
          // Clang will try to perform expression based completion as a
2109
          // fallback, which is confusing in case of member references. So we
2110
          // stop here without any completions.
2111
155
          if (Tok.is(tok::code_completion)) {
2112
1
            cutOffParsing();
2113
1
            return ExprError();
2114
1
          }
2115
154
          break;
2116
154
        }
2117
1.00M
        ParseOptionalCXXScopeSpecifier(
2118
1.00M
            SS, ObjectType, LHS.get() && LHS.get()->containsErrors(),
2119
1.00M
            /*EnteringContext=*/false, &MayBePseudoDestructor);
2120
1.00M
        if (SS.isNotEmpty())
2121
700
          ObjectType = nullptr;
2122
1.00M
      }
2123
1.13M
2124
1.13M
      if (Tok.is(tok::code_completion)) {
2125
155
        tok::TokenKind CorrectedOpKind =
2126
114
            OpKind == tok::arrow ? 
tok::period41
: tok::arrow;
2127
155
        ExprResult CorrectedLHS(/*Invalid=*/true);
2128
155
        if (getLangOpts().CPlusPlus && 
OrigLHS108
) {
2129
          // FIXME: Creating a TentativeAnalysisScope from outside Sema is a
2130
          // hack.
2131
107
          Sema::TentativeAnalysisScope Trap(Actions);
2132
107
          CorrectedLHS = Actions.ActOnStartCXXMemberReference(
2133
107
              getCurScope(), OrigLHS, OpLoc, CorrectedOpKind, ObjectType,
2134
107
              MayBePseudoDestructor);
2135
107
        }
2136
155
2137
155
        Expr *Base = LHS.get();
2138
155
        Expr *CorrectedBase = CorrectedLHS.get();
2139
155
        if (!CorrectedBase && 
!getLangOpts().CPlusPlus48
)
2140
47
          CorrectedBase = Base;
2141
155
2142
        // Code completion for a member access expression.
2143
155
        Actions.CodeCompleteMemberReferenceExpr(
2144
155
            getCurScope(), Base, CorrectedBase, OpLoc, OpKind == tok::arrow,
2145
155
            Base && 
ExprStatementTokLoc == Base->getBeginLoc()154
,
2146
155
            PreferredType.get(Tok.getLocation()));
2147
155
2148
155
        cutOffParsing();
2149
155
        return ExprError();
2150
155
      }
2151
1.13M
2152
1.13M
      if (MayBePseudoDestructor && 
!LHS.isInvalid()6.75k
) {
2153
6.75k
        LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
2154
6.75k
                                       ObjectType);
2155
6.75k
        break;
2156
6.75k
      }
2157
1.12M
2158
      // Either the action has told us that this cannot be a
2159
      // pseudo-destructor expression (based on the type of base
2160
      // expression), or we didn't see a '~' in the right place. We
2161
      // can still parse a destructor name here, but in that case it
2162
      // names a real destructor.
2163
      // Allow explicit constructor calls in Microsoft mode.
2164
      // FIXME: Add support for explicit call of template constructor.
2165
1.12M
      SourceLocation TemplateKWLoc;
2166
1.12M
      UnqualifiedId Name;
2167
1.12M
      if (getLangOpts().ObjC && 
OpKind == tok::period165k
&&
2168
95.9k
          Tok.is(tok::kw_class)) {
2169
        // Objective-C++:
2170
        //   After a '.' in a member access expression, treat the keyword
2171
        //   'class' as if it were an identifier.
2172
        //
2173
        // This hack allows property access to the 'class' method because it is
2174
        // such a common method name. For other C++ keywords that are
2175
        // Objective-C method names, one must use the message send syntax.
2176
2
        IdentifierInfo *Id = Tok.getIdentifierInfo();
2177
2
        SourceLocation Loc = ConsumeToken();
2178
2
        Name.setIdentifier(Id, Loc);
2179
1.12M
      } else if (ParseUnqualifiedId(
2180
1.12M
                     SS, ObjectType, LHS.get() && 
LHS.get()->containsErrors()1.12M
,
2181
1.12M
                     /*EnteringContext=*/false,
2182
1.12M
                     /*AllowDestructorName=*/true,
2183
                     /*AllowConstructorName=*/
2184
1.12M
                     getLangOpts().MicrosoftExt && 
SS.isNotEmpty()2.97k
,
2185
314
                     /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name)) {
2186
314
        (void)Actions.CorrectDelayedTyposInExpr(LHS);
2187
314
        LHS = ExprError();
2188
314
      }
2189
1.12M
2190
1.12M
      if (!LHS.isInvalid())
2191
1.12M
        LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
2192
1.12M
                                            OpKind, SS, TemplateKWLoc, Name,
2193
2.22k
                                 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
2194
1.12M
                                                   : nullptr);
2195
1.12M
      if (!LHS.isInvalid()) {
2196
1.12M
        if (Tok.is(tok::less))
2197
3.04k
          checkPotentialAngleBracket(LHS);
2198
978
      } else if (OrigLHS && 
Name.isValid()669
) {
2199
        // Preserve the LHS if the RHS is an invalid member.
2200
366
        LHS = Actions.CreateRecoveryExpr(OrigLHS->getBeginLoc(),
2201
366
                                         Name.getEndLoc(), {OrigLHS});
2202
366
      }
2203
1.12M
      break;
2204
1.12M
    }
2205
41.7k
    case tok::plusplus:    // postfix-expression: postfix-expression '++'
2206
41.7k
    case tok::minusminus:  // postfix-expression: postfix-expression '--'
2207
41.7k
      if (!LHS.isInvalid()) {
2208
41.7k
        Expr *Arg = LHS.get();
2209
41.7k
        LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
2210
41.7k
                                          Tok.getKind(), Arg);
2211
41.7k
        if (LHS.isInvalid())
2212
81
          LHS = Actions.CreateRecoveryExpr(Arg->getBeginLoc(),
2213
81
                                           Tok.getLocation(), Arg);
2214
41.7k
      }
2215
41.7k
      ConsumeToken();
2216
41.7k
      break;
2217
36.3M
    }
2218
36.3M
  }
2219
30.5M
}
2220
2221
/// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
2222
/// vec_step and we are at the start of an expression or a parenthesized
2223
/// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
2224
/// expression (isCastExpr == false) or the type (isCastExpr == true).
2225
///
2226
/// \verbatim
2227
///       unary-expression:  [C99 6.5.3]
2228
///         'sizeof' unary-expression
2229
///         'sizeof' '(' type-name ')'
2230
/// [GNU]   '__alignof' unary-expression
2231
/// [GNU]   '__alignof' '(' type-name ')'
2232
/// [C11]   '_Alignof' '(' type-name ')'
2233
/// [C++0x] 'alignof' '(' type-id ')'
2234
///
2235
/// [GNU]   typeof-specifier:
2236
///           typeof ( expressions )
2237
///           typeof ( type-name )
2238
/// [GNU/C++] typeof unary-expression
2239
///
2240
/// [OpenCL 1.1 6.11.12] vec_step built-in function:
2241
///           vec_step ( expressions )
2242
///           vec_step ( type-name )
2243
/// \endverbatim
2244
ExprResult
2245
Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
2246
                                           bool &isCastExpr,
2247
                                           ParsedType &CastTy,
2248
84.7k
                                           SourceRange &CastRange) {
2249
84.7k
2250
84.7k
  assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
2251
84.7k
                       tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
2252
84.7k
                       tok::kw___builtin_omp_required_simd_align) &&
2253
84.7k
         "Not a typeof/sizeof/alignof/vec_step expression!");
2254
84.7k
2255
84.7k
  ExprResult Operand;
2256
84.7k
2257
  // If the operand doesn't start with an '(', it must be an expression.
2258
84.7k
  if (Tok.isNot(tok::l_paren)) {
2259
    // If construct allows a form without parenthesis, user may forget to put
2260
    // pathenthesis around type name.
2261
874
    if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
2262
868
                      tok::kw__Alignof)) {
2263
868
      if (isTypeIdUnambiguously()) {
2264
7
        DeclSpec DS(AttrFactory);
2265
7
        ParseSpecifierQualifierList(DS);
2266
7
        Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
2267
7
        ParseDeclarator(DeclaratorInfo);
2268
7
2269
7
        SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
2270
7
        SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
2271
7
        Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
2272
7
          << OpTok.getName()
2273
7
          << FixItHint::CreateInsertion(LParenLoc, "(")
2274
7
          << FixItHint::CreateInsertion(RParenLoc, ")");
2275
7
        isCastExpr = true;
2276
7
        return ExprEmpty();
2277
7
      }
2278
867
    }
2279
867
2280
867
    isCastExpr = false;
2281
867
    if (OpTok.is(tok::kw_typeof) && 
!getLangOpts().CPlusPlus6
) {
2282
0
      Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
2283
0
                                          << tok::l_paren;
2284
0
      return ExprError();
2285
0
    }
2286
867
2287
867
    Operand = ParseCastExpression(UnaryExprOnly);
2288
83.8k
  } else {
2289
    // If it starts with a '(', we know that it is either a parenthesized
2290
    // type-name, or it is a unary-expression that starts with a compound
2291
    // literal, or starts with a primary-expression that is a parenthesized
2292
    // expression.
2293
83.8k
    ParenParseOption ExprType = CastExpr;
2294
83.8k
    SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
2295
83.8k
2296
83.8k
    Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
2297
83.8k
                                   false, CastTy, RParenLoc);
2298
83.8k
    CastRange = SourceRange(LParenLoc, RParenLoc);
2299
83.8k
2300
    // If ParseParenExpression parsed a '(typename)' sequence only, then this is
2301
    // a type.
2302
83.8k
    if (ExprType == CastExpr) {
2303
68.1k
      isCastExpr = true;
2304
68.1k
      return ExprEmpty();
2305
68.1k
    }
2306
15.7k
2307
15.7k
    if (getLangOpts().CPlusPlus || 
OpTok.isNot(tok::kw_typeof)1.91k
) {
2308
      // GNU typeof in C requires the expression to be parenthesized. Not so for
2309
      // sizeof/alignof or in C++. Therefore, the parenthesized expression is
2310
      // the start of a unary-expression, but doesn't include any postfix
2311
      // pieces. Parse these now if present.
2312
14.8k
      if (!Operand.isInvalid())
2313
14.8k
        Operand = ParsePostfixExpressionSuffix(Operand.get());
2314
14.8k
    }
2315
15.7k
  }
2316
84.7k
2317
  // If we get here, the operand to the typeof/sizeof/alignof was an expression.
2318
16.6k
  isCastExpr = false;
2319
16.6k
  return Operand;
2320
84.7k
}
2321
2322
2323
23
ExprResult Parser::ParseUniqueStableNameExpression() {
2324
23
  assert(Tok.is(tok::kw___builtin_unique_stable_name) &&
2325
23
         "Not __bulitin_unique_stable_name");
2326
23
2327
23
  SourceLocation OpLoc = ConsumeToken();
2328
23
  BalancedDelimiterTracker T(*this, tok::l_paren);
2329
23
2330
  // typeid expressions are always parenthesized.
2331
23
  if (T.expectAndConsume(diag::err_expected_lparen_after,
2332
23
                         "__builtin_unique_stable_name"))
2333
2
    return ExprError();
2334
21
2335
21
  if (isTypeIdInParens()) {
2336
4
    TypeResult Ty = ParseTypeName();
2337
4
    T.consumeClose();
2338
4
2339
4
    if (Ty.isInvalid())
2340
0
      return ExprError();
2341
4
2342
4
    return Actions.ActOnUniqueStableNameExpr(OpLoc, T.getOpenLocation(),
2343
4
                                             T.getCloseLocation(), Ty.get());
2344
4
  }
2345
17
2346
17
  EnterExpressionEvaluationContext Unevaluated(
2347
17
      Actions, Sema::ExpressionEvaluationContext::Unevaluated);
2348
17
  ExprResult Result = ParseExpression();
2349
17
2350
17
  if (Result.isInvalid()) {
2351
2
    SkipUntil(tok::r_paren, StopAtSemi);
2352
2
    return Result;
2353
2
  }
2354
15
2355
15
  T.consumeClose();
2356
15
  return Actions.ActOnUniqueStableNameExpr(OpLoc, T.getOpenLocation(),
2357
15
                                           T.getCloseLocation(), Result.get());
2358
15
}
2359
2360
/// Parse a sizeof or alignof expression.
2361
///
2362
/// \verbatim
2363
///       unary-expression:  [C99 6.5.3]
2364
///         'sizeof' unary-expression
2365
///         'sizeof' '(' type-name ')'
2366
/// [C++11] 'sizeof' '...' '(' identifier ')'
2367
/// [GNU]   '__alignof' unary-expression
2368
/// [GNU]   '__alignof' '(' type-name ')'
2369
/// [C11]   '_Alignof' '(' type-name ')'
2370
/// [C++11] 'alignof' '(' type-id ')'
2371
/// \endverbatim
2372
126k
ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
2373
126k
  assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
2374
126k
                     tok::kw__Alignof, tok::kw_vec_step,
2375
126k
                     tok::kw___builtin_omp_required_simd_align) &&
2376
126k
         "Not a sizeof/alignof/vec_step expression!");
2377
126k
  Token OpTok = Tok;
2378
126k
  ConsumeToken();
2379
126k
2380
  // [C++11] 'sizeof' '...' '(' identifier ')'
2381
126k
  if (Tok.is(tok::ellipsis) && 
OpTok.is(tok::kw_sizeof)44.5k
) {
2382
44.5k
    SourceLocation EllipsisLoc = ConsumeToken();
2383
44.5k
    SourceLocation LParenLoc, RParenLoc;
2384
44.5k
    IdentifierInfo *Name = nullptr;
2385
44.5k
    SourceLocation NameLoc;
2386
44.5k
    if (Tok.is(tok::l_paren)) {
2387
44.5k
      BalancedDelimiterTracker T(*this, tok::l_paren);
2388
44.5k
      T.consumeOpen();
2389
44.5k
      LParenLoc = T.getOpenLocation();
2390
44.5k
      if (Tok.is(tok::identifier)) {
2391
44.5k
        Name = Tok.getIdentifierInfo();
2392
44.5k
        NameLoc = ConsumeToken();
2393
44.5k
        T.consumeClose();
2394
44.5k
        RParenLoc = T.getCloseLocation();
2395
44.5k
        if (RParenLoc.isInvalid())
2396
0
          RParenLoc = PP.getLocForEndOfToken(NameLoc);
2397
0
      } else {
2398
0
        Diag(Tok, diag::err_expected_parameter_pack);
2399
0
        SkipUntil(tok::r_paren, StopAtSemi);
2400
0
      }
2401
1
    } else if (Tok.is(tok::identifier)) {
2402
1
      Name = Tok.getIdentifierInfo();
2403
1
      NameLoc = ConsumeToken();
2404
1
      LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
2405
1
      RParenLoc = PP.getLocForEndOfToken(NameLoc);
2406
1
      Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
2407
1
        << Name
2408
1
        << FixItHint::CreateInsertion(LParenLoc, "(")
2409
1
        << FixItHint::CreateInsertion(RParenLoc, ")");
2410
0
    } else {
2411
0
      Diag(Tok, diag::err_sizeof_parameter_pack);
2412
0
    }
2413
44.5k
2414
44.5k
    if (!Name)
2415
0
      return ExprError();
2416
44.5k
2417
44.5k
    EnterExpressionEvaluationContext Unevaluated(
2418
44.5k
        Actions, Sema::ExpressionEvaluationContext::Unevaluated,
2419
44.5k
        Sema::ReuseLambdaContextDecl);
2420
44.5k
2421
44.5k
    return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
2422
44.5k
                                                OpTok.getLocation(),
2423
44.5k
                                                *Name, NameLoc,
2424
44.5k
                                                RParenLoc);
2425
44.5k
  }
2426
81.7k
2427
81.7k
  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2428
5.22k
    Diag(OpTok, diag::warn_cxx98_compat_alignof);
2429
81.7k
2430
81.7k
  EnterExpressionEvaluationContext Unevaluated(
2431
81.7k
      Actions, Sema::ExpressionEvaluationContext::Unevaluated,
2432
81.7k
      Sema::ReuseLambdaContextDecl);
2433
81.7k
2434
81.7k
  bool isCastExpr;
2435
81.7k
  ParsedType CastTy;
2436
81.7k
  SourceRange CastRange;
2437
81.7k
  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
2438
81.7k
                                                          isCastExpr,
2439
81.7k
                                                          CastTy,
2440
81.7k
                                                          CastRange);
2441
81.7k
2442
81.7k
  UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
2443
81.7k
  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2444
5.22k
    ExprKind = UETT_AlignOf;
2445
76.5k
  else if (OpTok.is(tok::kw___alignof))
2446
2.50k
    ExprKind = UETT_PreferredAlignOf;
2447
74.0k
  else if (OpTok.is(tok::kw_vec_step))
2448
42
    ExprKind = UETT_VecStep;
2449
74.0k
  else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
2450
29
    ExprKind = UETT_OpenMPRequiredSimdAlign;
2451
81.7k
2452
81.7k
  if (isCastExpr)
2453
68.0k
    return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2454
68.0k
                                                 ExprKind,
2455
68.0k
                                                 /*IsType=*/true,
2456
68.0k
                                                 CastTy.getAsOpaquePtr(),
2457
68.0k
                                                 CastRange);
2458
13.7k
2459
13.7k
  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2460
37
    Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
2461
13.7k
2462
  // If we get here, the operand to the sizeof/alignof was an expression.
2463
13.7k
  if (!Operand.isInvalid())
2464
13.7k
    Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2465
13.7k
                                                    ExprKind,
2466
13.7k
                                                    /*IsType=*/false,
2467
13.7k
                                                    Operand.get(),
2468
13.7k
                                                    CastRange);
2469
13.7k
  return Operand;
2470
13.7k
}
2471
2472
/// ParseBuiltinPrimaryExpression
2473
///
2474
/// \verbatim
2475
///       primary-expression: [C99 6.5.1]
2476
/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
2477
/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
2478
/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
2479
///                                     assign-expr ')'
2480
/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
2481
/// [GNU]   '__builtin_FILE' '(' ')'
2482
/// [GNU]   '__builtin_FUNCTION' '(' ')'
2483
/// [GNU]   '__builtin_LINE' '(' ')'
2484
/// [CLANG] '__builtin_COLUMN' '(' ')'
2485
/// [OCL]   '__builtin_astype' '(' assignment-expression ',' type-name ')'
2486
///
2487
/// [GNU] offsetof-member-designator:
2488
/// [GNU]   identifier
2489
/// [GNU]   offsetof-member-designator '.' identifier
2490
/// [GNU]   offsetof-member-designator '[' expression ']'
2491
/// \endverbatim
2492
20.5k
ExprResult Parser::ParseBuiltinPrimaryExpression() {
2493
20.5k
  ExprResult Res;
2494
20.5k
  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
2495
20.5k
2496
20.5k
  tok::TokenKind T = Tok.getKind();
2497
20.5k
  SourceLocation StartLoc = ConsumeToken();   // Eat the builtin identifier.
2498
20.5k
2499
  // All of these start with an open paren.
2500
20.5k
  if (Tok.isNot(tok::l_paren))
2501
0
    return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
2502
0
                                                         << tok::l_paren);
2503
20.5k
2504
20.5k
  BalancedDelimiterTracker PT(*this, tok::l_paren);
2505
20.5k
  PT.consumeOpen();
2506
20.5k
2507
  // TODO: Build AST.
2508
20.5k
2509
20.5k
  switch (T) {
2510
0
  default: llvm_unreachable("Not a builtin primary expression!");
2511
977
  case tok::kw___builtin_va_arg: {
2512
977
    ExprResult Expr(ParseAssignmentExpression());
2513
977
2514
977
    if (ExpectAndConsume(tok::comma)) {
2515
0
      SkipUntil(tok::r_paren, StopAtSemi);
2516
0
      Expr = ExprError();
2517
0
    }
2518
977
2519
977
    TypeResult Ty = ParseTypeName();
2520
977
2521
977
    if (Tok.isNot(tok::r_paren)) {
2522
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2523
0
      Expr = ExprError();
2524
0
    }
2525
977
2526
977
    if (Expr.isInvalid() || Ty.isInvalid())
2527
0
      Res = ExprError();
2528
977
    else
2529
977
      Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
2530
977
    break;
2531
0
  }
2532
332
  case tok::kw___builtin_offsetof: {
2533
332
    SourceLocation TypeLoc = Tok.getLocation();
2534
332
    TypeResult Ty = ParseTypeName();
2535
332
    if (Ty.isInvalid()) {
2536
1
      SkipUntil(tok::r_paren, StopAtSemi);
2537
1
      return ExprError();
2538
1
    }
2539
331
2540
331
    if (ExpectAndConsume(tok::comma)) {
2541
0
      SkipUntil(tok::r_paren, StopAtSemi);
2542
0
      return ExprError();
2543
0
    }
2544
331
2545
    // We must have at least one identifier here.
2546
331
    if (Tok.isNot(tok::identifier)) {
2547
0
      Diag(Tok, diag::err_expected) << tok::identifier;
2548
0
      SkipUntil(tok::r_paren, StopAtSemi);
2549
0
      return ExprError();
2550
0
    }
2551
331
2552
    // Keep track of the various subcomponents we see.
2553
331
    SmallVector<Sema::OffsetOfComponent, 4> Comps;
2554
331
2555
331
    Comps.push_back(Sema::OffsetOfComponent());
2556
331
    Comps.back().isBrackets = false;
2557
331
    Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2558
331
    Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2559
331
2560
    // FIXME: This loop leaks the index expressions on error.
2561
392
    while (1) {
2562
392
      if (Tok.is(tok::period)) {
2563
        // offsetof-member-designator: offsetof-member-designator '.' identifier
2564
19
        Comps.push_back(Sema::OffsetOfComponent());
2565
19
        Comps.back().isBrackets = false;
2566
19
        Comps.back().LocStart = ConsumeToken();
2567
19
2568
19
        if (Tok.isNot(tok::identifier)) {
2569
0
          Diag(Tok, diag::err_expected) << tok::identifier;
2570
0
          SkipUntil(tok::r_paren, StopAtSemi);
2571
0
          return ExprError();
2572
0
        }
2573
19
        Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2574
19
        Comps.back().LocEnd = ConsumeToken();
2575
19
2576
373
      } else if (Tok.is(tok::l_square)) {
2577
42
        if (CheckProhibitedCXX11Attribute())
2578
0
          return ExprError();
2579
42
2580
        // offsetof-member-designator: offsetof-member-design '[' expression ']'
2581
42
        Comps.push_back(Sema::OffsetOfComponent());
2582
42
        Comps.back().isBrackets = true;
2583
42
        BalancedDelimiterTracker ST(*this, tok::l_square);
2584
42
        ST.consumeOpen();
2585
42
        Comps.back().LocStart = ST.getOpenLocation();
2586
42
        Res = ParseExpression();
2587
42
        if (Res.isInvalid()) {
2588
0
          SkipUntil(tok::r_paren, StopAtSemi);
2589
0
          return Res;
2590
0
        }
2591
42
        Comps.back().U.E = Res.get();
2592
42
2593
42
        ST.consumeClose();
2594
42
        Comps.back().LocEnd = ST.getCloseLocation();
2595
331
      } else {
2596
331
        if (Tok.isNot(tok::r_paren)) {
2597
2
          PT.consumeClose();
2598
2
          Res = ExprError();
2599
329
        } else if (Ty.isInvalid()) {
2600
0
          Res = ExprError();
2601
329
        } else {
2602
329
          PT.consumeClose();
2603
329
          Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2604
329
                                             Ty.get(), Comps,
2605
329
                                             PT.getCloseLocation());
2606
329
        }
2607
331
        break;
2608
331
      }
2609
392
    }
2610
331
    break;
2611
331
  }
2612
61
  case tok::kw___builtin_choose_expr: {
2613
61
    ExprResult Cond(ParseAssignmentExpression());
2614
61
    if (Cond.isInvalid()) {
2615
0
      SkipUntil(tok::r_paren, StopAtSemi);
2616
0
      return Cond;
2617
0
    }
2618
61
    if (ExpectAndConsume(tok::comma)) {
2619
0
      SkipUntil(tok::r_paren, StopAtSemi);
2620
0
      return ExprError();
2621
0
    }
2622
61
2623
61
    ExprResult Expr1(ParseAssignmentExpression());
2624
61
    if (Expr1.isInvalid()) {
2625
0
      SkipUntil(tok::r_paren, StopAtSemi);
2626
0
      return Expr1;
2627
0
    }
2628
61
    if (ExpectAndConsume(tok::comma)) {
2629
0
      SkipUntil(tok::r_paren, StopAtSemi);
2630
0
      return ExprError();
2631
0
    }
2632
61
2633
61
    ExprResult Expr2(ParseAssignmentExpression());
2634
61
    if (Expr2.isInvalid()) {
2635
0
      SkipUntil(tok::r_paren, StopAtSemi);
2636
0
      return Expr2;
2637
0
    }
2638
61
    if (Tok.isNot(tok::r_paren)) {
2639
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2640
0
      return ExprError();
2641
0
    }
2642
61
    Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2643
61
                                  Expr2.get(), ConsumeParen());
2644
61
    break;
2645
61
  }
2646
30
  case tok::kw___builtin_astype: {
2647
    // The first argument is an expression to be converted, followed by a comma.
2648
30
    ExprResult Expr(ParseAssignmentExpression());
2649
30
    if (Expr.isInvalid()) {
2650
0
      SkipUntil(tok::r_paren, StopAtSemi);
2651
0
      return ExprError();
2652
0
    }
2653
30
2654
30
    if (ExpectAndConsume(tok::comma)) {
2655
0
      SkipUntil(tok::r_paren, StopAtSemi);
2656
0
      return ExprError();
2657
0
    }
2658
30
2659
    // Second argument is the type to bitcast to.
2660
30
    TypeResult DestTy = ParseTypeName();
2661
30
    if (DestTy.isInvalid())
2662
0
      return ExprError();
2663
30
2664
    // Attempt to consume the r-paren.
2665
30
    if (Tok.isNot(tok::r_paren)) {
2666
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2667
0
      SkipUntil(tok::r_paren, StopAtSemi);
2668
0
      return ExprError();
2669
0
    }
2670
30
2671
30
    Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2672
30
                                  ConsumeParen());
2673
30
    break;
2674
30
  }
2675
19.0k
  case tok::kw___builtin_convertvector: {
2676
    // The first argument is an expression to be converted, followed by a comma.
2677
19.0k
    ExprResult Expr(ParseAssignmentExpression());
2678
19.0k
    if (Expr.isInvalid()) {
2679
0
      SkipUntil(tok::r_paren, StopAtSemi);
2680
0
      return ExprError();
2681
0
    }
2682
19.0k
2683
19.0k
    if (ExpectAndConsume(tok::comma)) {
2684
0
      SkipUntil(tok::r_paren, StopAtSemi);
2685
0
      return ExprError();
2686
0
    }
2687
19.0k
2688
    // Second argument is the type to bitcast to.
2689
19.0k
    TypeResult DestTy = ParseTypeName();
2690
19.0k
    if (DestTy.isInvalid())
2691
0
      return ExprError();
2692
19.0k
2693
    // Attempt to consume the r-paren.
2694
19.0k
    if (Tok.isNot(tok::r_paren)) {
2695
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2696
0
      SkipUntil(tok::r_paren, StopAtSemi);
2697
0
      return ExprError();
2698
0
    }
2699
19.0k
2700
19.0k
    Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2701
19.0k
                                         ConsumeParen());
2702
19.0k
    break;
2703
19.0k
  }
2704
110
  case tok::kw___builtin_COLUMN:
2705
110
  case tok::kw___builtin_FILE:
2706
110
  case tok::kw___builtin_FUNCTION:
2707
110
  case tok::kw___builtin_LINE: {
2708
    // Attempt to consume the r-paren.
2709
110
    if (Tok.isNot(tok::r_paren)) {
2710
8
      Diag(Tok, diag::err_expected) << tok::r_paren;
2711
8
      SkipUntil(tok::r_paren, StopAtSemi);
2712
8
      return ExprError();
2713
8
    }
2714
102
    SourceLocExpr::IdentKind Kind = [&] {
2715
102
      switch (T) {
2716
17
      case tok::kw___builtin_FILE:
2717
17
        return SourceLocExpr::File;
2718
19
      case tok::kw___builtin_FUNCTION:
2719
19
        return SourceLocExpr::Function;
2720
52
      case tok::kw___builtin_LINE:
2721
52
        return SourceLocExpr::Line;
2722
14
      case tok::kw___builtin_COLUMN:
2723
14
        return SourceLocExpr::Column;
2724
0
      default:
2725
0
        llvm_unreachable("invalid keyword");
2726
102
      }
2727
102
    }();
2728
102
    Res = Actions.ActOnSourceLocExpr(Kind, StartLoc, ConsumeParen());
2729
102
    break;
2730
102
  }
2731
20.5k
  }
2732
20.5k
2733
20.5k
  if (Res.isInvalid())
2734
33
    return ExprError();
2735
20.4k
2736
  // These can be followed by postfix-expr pieces because they are
2737
  // primary-expressions.
2738
20.4k
  return ParsePostfixExpressionSuffix(Res.get());
2739
20.4k
}
2740
2741
127
bool Parser::tryParseOpenMPArrayShapingCastPart() {
2742
127
  assert(Tok.is(tok::l_square) && "Expected open bracket");
2743
127
  bool ErrorFound = true;
2744
127
  TentativeParsingAction TPA(*this);
2745
265
  do {
2746
265
    if (Tok.isNot(tok::l_square))
2747
0
      break;
2748
    // Consume '['
2749
265
    ConsumeBracket();
2750
    // Skip inner expression.
2751
265
    while (!SkipUntil(tok::r_square, tok::annot_pragma_openmp_end,
2752
265
                      StopAtSemi | StopBeforeMatch))
2753
0
      ;
2754
265
    if (Tok.isNot(tok::r_square))
2755
4
      break;
2756
    // Consume ']'
2757
261
    ConsumeBracket();
2758
    // Found ')' - done.
2759
261
    if (Tok.is(tok::r_paren)) {
2760
119
      ErrorFound = false;
2761
119
      break;
2762
119
    }
2763
142
  } while (Tok.isNot(tok::annot_pragma_openmp_end));
2764
127
  TPA.Revert();
2765
127
  return !ErrorFound;
2766
127
}
2767
2768
/// ParseParenExpression - This parses the unit that starts with a '(' token,
2769
/// based on what is allowed by ExprType.  The actual thing parsed is returned
2770
/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2771
/// not the parsed cast-expression.
2772
///
2773
/// \verbatim
2774
///       primary-expression: [C99 6.5.1]
2775
///         '(' expression ')'
2776
/// [GNU]   '(' compound-statement ')'      (if !ParenExprOnly)
2777
///       postfix-expression: [C99 6.5.2]
2778
///         '(' type-name ')' '{' initializer-list '}'
2779
///         '(' type-name ')' '{' initializer-list ',' '}'
2780
///       cast-expression: [C99 6.5.4]
2781
///         '(' type-name ')' cast-expression
2782
/// [ARC]   bridged-cast-expression
2783
/// [ARC] bridged-cast-expression:
2784
///         (__bridge type-name) cast-expression
2785
///         (__bridge_transfer type-name) cast-expression
2786
///         (__bridge_retained type-name) cast-expression
2787
///       fold-expression: [C++1z]
2788
///         '(' cast-expression fold-operator '...' ')'
2789
///         '(' '...' fold-operator cast-expression ')'
2790
///         '(' cast-expression fold-operator '...'
2791
///                 fold-operator cast-expression ')'
2792
/// [OPENMP] Array shaping operation
2793
///       '(' '[' expression ']' { '[' expression ']' } cast-expression
2794
/// \endverbatim
2795
ExprResult
2796
Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2797
                             bool isTypeCast, ParsedType &CastTy,
2798
5.51M
                             SourceLocation &RParenLoc) {
2799
5.51M
  assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2800
5.51M
  ColonProtectionRAIIObject ColonProtection(*this, false);
2801
5.51M
  BalancedDelimiterTracker T(*this, tok::l_paren);
2802
5.51M
  if (T.consumeOpen())
2803
0
    return ExprError();
2804
5.51M
  SourceLocation OpenLoc = T.getOpenLocation();
2805
5.51M
2806
5.51M
  PreferredType.enterParenExpr(Tok.getLocation(), OpenLoc);
2807
5.51M
2808
5.51M
  ExprResult Result(true);
2809
5.51M
  bool isAmbiguousTypeId;
2810
5.51M
  CastTy = nullptr;
2811
5.51M
2812
5.51M
  if (Tok.is(tok::code_completion)) {
2813
30
    Actions.CodeCompleteExpression(
2814
30
        getCurScope(), PreferredType.get(Tok.getLocation()),
2815
30
        /*IsParenthesized=*/ExprType >= CompoundLiteral);
2816
30
    cutOffParsing();
2817
30
    return ExprError();
2818
30
  }
2819
5.51M
2820
  // Diagnose use of bridge casts in non-arc mode.
2821
5.51M
  bool BridgeCast = (getLangOpts().ObjC &&
2822
852k
                     Tok.isOneOf(tok::kw___bridge,
2823
852k
                                 tok::kw___bridge_transfer,
2824
852k
                                 tok::kw___bridge_retained,
2825
852k
                                 tok::kw___bridge_retain));
2826
5.51M
  if (BridgeCast && 
!getLangOpts().ObjCAutoRefCount414
) {
2827
85
    if (!TryConsumeToken(tok::kw___bridge)) {
2828
8
      StringRef BridgeCastName = Tok.getName();
2829
8
      SourceLocation BridgeKeywordLoc = ConsumeToken();
2830
8
      if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2831
8
        Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2832
8
          << BridgeCastName
2833
8
          << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2834
8
    }
2835
85
    BridgeCast = false;
2836
85
  }
2837
5.51M
2838
  // None of these cases should fall through with an invalid Result
2839
  // unless they've already reported an error.
2840
5.51M
  if (ExprType >= CompoundStmt && 
Tok.is(tok::l_brace)5.51M
) {
2841
8.73k
    Diag(Tok, diag::ext_gnu_statement_expr);
2842
8.73k
2843
8.73k
    checkCompoundToken(OpenLoc, tok::l_paren, CompoundToken::StmtExprBegin);
2844
8.73k
2845
8.73k
    if (!getCurScope()->getFnParent() && 
!getCurScope()->getBlockParent()2
) {
2846
2
      Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2847
8.73k
    } else {
2848
      // Find the nearest non-record decl context. Variables declared in a
2849
      // statement expression behave as if they were declared in the enclosing
2850
      // function, block, or other code construct.
2851
8.73k
      DeclContext *CodeDC = Actions.CurContext;
2852
8.73k
      while (CodeDC->isRecord() || 
isa<EnumDecl>(CodeDC)8.73k
) {
2853
3
        CodeDC = CodeDC->getParent();
2854
3
        assert(CodeDC && !CodeDC->isFileContext() &&
2855
3
               "statement expr not in code context");
2856
3
      }
2857
8.73k
      Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2858
8.73k
2859
8.73k
      Actions.ActOnStartStmtExpr();
2860
8.73k
2861
8.73k
      StmtResult Stmt(ParseCompoundStatement(true));
2862
8.73k
      ExprType = CompoundStmt;
2863
8.73k
2864
      // If the substmt parsed correctly, build the AST node.
2865
8.73k
      if (!Stmt.isInvalid()) {
2866
8.73k
        Result = Actions.ActOnStmtExpr(getCurScope(), OpenLoc, Stmt.get(),
2867
8.73k
                                       Tok.getLocation());
2868
0
      } else {
2869
0
        Actions.ActOnStmtExprError();
2870
0
      }
2871
8.73k
    }
2872
5.50M
  } else if (ExprType >= CompoundLiteral && 
BridgeCast5.50M
) {
2873
329
    tok::TokenKind tokenKind = Tok.getKind();
2874
329
    SourceLocation BridgeKeywordLoc = ConsumeToken();
2875
329
2876
    // Parse an Objective-C ARC ownership cast expression.
2877
329
    ObjCBridgeCastKind Kind;
2878
329
    if (tokenKind == tok::kw___bridge)
2879
122
      Kind = OBC_Bridge;
2880
207
    else if (tokenKind == tok::kw___bridge_transfer)
2881
105
      Kind = OBC_BridgeTransfer;
2882
102
    else if (tokenKind == tok::kw___bridge_retained)
2883
98
      Kind = OBC_BridgeRetained;
2884
4
    else {
2885
      // As a hopefully temporary workaround, allow __bridge_retain as
2886
      // a synonym for __bridge_retained, but only in system headers.
2887
4
      assert(tokenKind == tok::kw___bridge_retain);
2888
4
      Kind = OBC_BridgeRetained;
2889
4
      if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2890
2
        Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2891
2
          << FixItHint::CreateReplacement(BridgeKeywordLoc,
2892
2
                                          "__bridge_retained");
2893
4
    }
2894
329
2895
329
    TypeResult Ty = ParseTypeName();
2896
329
    T.consumeClose();
2897
329
    ColonProtection.restore();
2898
329
    RParenLoc = T.getCloseLocation();
2899
329
2900
329
    PreferredType.enterTypeCast(Tok.getLocation(), Ty.get().get());
2901
329
    ExprResult SubExpr = ParseCastExpression(AnyCastExpr);
2902
329
2903
329
    if (Ty.isInvalid() || SubExpr.isInvalid())
2904
0
      return ExprError();
2905
329
2906
329
    return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2907
329
                                        BridgeKeywordLoc, Ty.get(),
2908
329
                                        RParenLoc, SubExpr.get());
2909
5.50M
  } else if (ExprType >= CompoundLiteral &&
2910
5.50M
             isTypeIdInParens(isAmbiguousTypeId)) {
2911
4.40M
2912
    // Otherwise, this is a compound literal expression or cast expression.
2913
4.40M
2914
    // In C++, if the type-id is ambiguous we disambiguate based on context.
2915
    // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2916
    // in which case we should treat it as type-id.
2917
    // if stopIfCastExpr is false, we need to determine the context past the
2918
    // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2919
4.40M
    if (isAmbiguousTypeId && 
!stopIfCastExpr995
) {
2920
918
      ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2921
918
                                                        ColonProtection);
2922
918
      RParenLoc = T.getCloseLocation();
2923
918
      return res;
2924
918
    }
2925
4.40M
2926
    // Parse the type declarator.
2927
4.40M
    DeclSpec DS(AttrFactory);
2928
4.40M
    ParseSpecifierQualifierList(DS);
2929
4.40M
    Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
2930
4.40M
    ParseDeclarator(DeclaratorInfo);
2931
4.40M
2932
    // If our type is followed by an identifier and either ':' or ']', then
2933
    // this is probably an Objective-C message send where the leading '[' is
2934
    // missing. Recover as if that were the case.
2935
4.40M
    if (!DeclaratorInfo.isInvalidType() && 
Tok.is(tok::identifier)4.40M
&&
2936
77
        !InMessageExpression && getLangOpts().ObjC &&
2937
75
        (NextToken().is(tok::colon) || 
NextToken().is(tok::r_square)0
)) {
2938
75
      TypeResult Ty;
2939
75
      {
2940
75
        InMessageExpressionRAIIObject InMessage(*this, false);
2941
75
        Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2942
75
      }
2943
75
      Result = ParseObjCMessageExpressionBody(SourceLocation(),
2944
75
                                              SourceLocation(),
2945
75
                                              Ty.get(), nullptr);
2946
4.40M
    } else {
2947
      // Match the ')'.
2948
4.40M
      T.consumeClose();
2949
4.40M
      ColonProtection.restore();
2950
4.40M
      RParenLoc = T.getCloseLocation();
2951
4.40M
      if (Tok.is(tok::l_brace)) {
2952
49.7k
        ExprType = CompoundLiteral;
2953
49.7k
        TypeResult Ty;
2954
49.7k
        {
2955
49.7k
          InMessageExpressionRAIIObject InMessage(*this, false);
2956
49.7k
          Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2957
49.7k
        }
2958
49.7k
        return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2959
49.7k
      }
2960
4.35M
2961
4.35M
      if (Tok.is(tok::l_paren)) {
2962
        // This could be OpenCL vector Literals
2963
483k
        if (getLangOpts().OpenCL)
2964
449
        {
2965
449
          TypeResult Ty;
2966
449
          {
2967
449
            InMessageExpressionRAIIObject InMessage(*this, false);
2968
449
            Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2969
449
          }
2970
449
          if(Ty.isInvalid())
2971
0
          {
2972
0
             return ExprError();
2973
0
          }
2974
449
          QualType QT = Ty.get().get().getCanonicalType();
2975
449
          if (QT->isVectorType())
2976
145
          {
2977
            // We parsed '(' vector-type-name ')' followed by '('
2978
145
2979
            // Parse the cast-expression that follows it next.
2980
            // isVectorLiteral = true will make sure we don't parse any
2981
            // Postfix expression yet
2982
145
            Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
2983
145
                                         /*isAddressOfOperand=*/false,
2984
145
                                         /*isTypeCast=*/IsTypeCast,
2985
145
                                         /*isVectorLiteral=*/true);
2986
145
2987
145
            if (!Result.isInvalid()) {
2988
145
              Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2989
145
                                             DeclaratorInfo, CastTy,
2990
145
                                             RParenLoc, Result.get());
2991
145
            }
2992
145
2993
            // After we performed the cast we can check for postfix-expr pieces.
2994
145
            if (!Result.isInvalid()) {
2995
142
              Result = ParsePostfixExpressionSuffix(Result);
2996
142
            }
2997
145
2998
145
            return Result;
2999
145
          }
3000
4.35M
        }
3001
483k
      }
3002
4.35M
3003
4.35M
      if (ExprType == CastExpr) {
3004
        // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
3005
4.35M
3006
4.35M
        if (DeclaratorInfo.isInvalidType())
3007
92
          return ExprError();
3008
4.35M
3009
        // Note that this doesn't parse the subsequent cast-expression, it just
3010
        // returns the parsed type to the callee.
3011
4.35M
        if (stopIfCastExpr) {
3012
68.1k
          TypeResult Ty;
3013
68.1k
          {
3014
68.1k
            InMessageExpressionRAIIObject InMessage(*this, false);
3015
68.1k
            Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3016
68.1k
          }
3017
68.1k
          CastTy = Ty.get();
3018
68.1k
          return ExprResult();
3019
68.1k
        }
3020
4.28M
3021
        // Reject the cast of super idiom in ObjC.
3022
4.28M
        if (Tok.is(tok::identifier) && 
getLangOpts().ObjC3.62M
&&
3023
334k
            Tok.getIdentifierInfo() == Ident_super &&
3024
10
            getCurScope()->isInObjcMethodScope() &&
3025
8
            GetLookAheadToken(1).isNot(tok::period)) {
3026
7
          Diag(Tok.getLocation(), diag::err_illegal_super_cast)
3027
7
            << SourceRange(OpenLoc, RParenLoc);
3028
7
          return ExprError();
3029
7
        }
3030
4.28M
3031
4.28M
        PreferredType.enterTypeCast(Tok.getLocation(), CastTy.get());
3032
        // Parse the cast-expression that follows it next.
3033
        // TODO: For cast expression with CastTy.
3034
4.28M
        Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
3035
4.28M
                                     /*isAddressOfOperand=*/false,
3036
4.28M
                                     /*isTypeCast=*/IsTypeCast);
3037
4.28M
        if (!Result.isInvalid()) {
3038
4.28M
          Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
3039
4.28M
                                         DeclaratorInfo, CastTy,
3040
4.28M
                                         RParenLoc, Result.get());
3041
4.28M
        }
3042
4.28M
        return Result;
3043
4.28M
      }
3044
0
3045
0
      Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
3046
0
      return ExprError();
3047
0
    }
3048
1.09M
  } else if (ExprType >= FoldExpr && Tok.is(tok::ellipsis) &&
3049
16
             isFoldOperator(NextToken().getKind())) {
3050
12
    ExprType = FoldExpr;
3051
12
    return ParseFoldExpression(ExprResult(), T);
3052
1.09M
  } else if (isTypeCast) {
3053
    // Parse the expression-list.
3054
363k
    InMessageExpressionRAIIObject InMessage(*this, false);
3055
363k
3056
363k
    ExprVector ArgExprs;
3057
363k
    CommaLocsTy CommaLocs;
3058
363k
3059
363k
    if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
3060
      // FIXME: If we ever support comma expressions as operands to
3061
      // fold-expressions, we'll need to allow multiple ArgExprs here.
3062
363k
      if (ExprType >= FoldExpr && ArgExprs.size() == 1 &&
3063
355k
          isFoldOperator(Tok.getKind()) && 
NextToken().is(tok::ellipsis)18
) {
3064
18
        ExprType = FoldExpr;
3065
18
        return ParseFoldExpression(ArgExprs[0], T);
3066
18
      }
3067
363k
3068
363k
      ExprType = SimpleExpr;
3069
363k
      Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
3070
363k
                                          ArgExprs);
3071
363k
    }
3072
732k
  } else if (getLangOpts().OpenMP >= 50 && 
OpenMPDirectiveParsing3.67k
&&
3073
1.10k
             ExprType == CastExpr && Tok.is(tok::l_square) &&
3074
127
             tryParseOpenMPArrayShapingCastPart()) {
3075
119
    bool ErrorFound = false;
3076
119
    SmallVector<Expr *, 4> OMPDimensions;
3077
119
    SmallVector<SourceRange, 4> OMPBracketsRanges;
3078
257
    do {
3079
257
      BalancedDelimiterTracker TS(*this, tok::l_square);
3080
257
      TS.consumeOpen();
3081
257
      ExprResult NumElements =
3082
257
          Actions.CorrectDelayedTyposInExpr(ParseExpression());
3083
257
      if (!NumElements.isUsable()) {
3084
12
        ErrorFound = true;
3085
12
        while (!SkipUntil(tok::r_square, tok::r_paren,
3086
12
                          StopAtSemi | StopBeforeMatch))
3087
0
          ;
3088
12
      }
3089
257
      TS.consumeClose();
3090
257
      OMPDimensions.push_back(NumElements.get());
3091
257
      OMPBracketsRanges.push_back(TS.getRange());
3092
257
    } while (Tok.isNot(tok::r_paren));
3093
    // Match the ')'.
3094
119
    T.consumeClose();
3095
119
    RParenLoc = T.getCloseLocation();
3096
119
    Result = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3097
119
    if (ErrorFound) {
3098
12
      Result = ExprError();
3099
107
    } else if (!Result.isInvalid()) {
3100
107
      Result = Actions.ActOnOMPArrayShapingExpr(
3101
107
          Result.get(), OpenLoc, RParenLoc, OMPDimensions, OMPBracketsRanges);
3102
107
    }
3103
119
    return Result;
3104
732k
  } else {
3105
732k
    InMessageExpressionRAIIObject InMessage(*this, false);
3106
732k
3107
732k
    Result = ParseExpression(MaybeTypeCast);
3108
732k
    if (!getLangOpts().CPlusPlus && 
MaybeTypeCast0
&&
Result.isUsable()353k
) {
3109
      // Correct typos in non-C++ code earlier so that implicit-cast-like
3110
      // expressions are parsed correctly.
3111
353k
      Result = Actions.CorrectDelayedTyposInExpr(Result);
3112
353k
    }
3113
732k
3114
732k
    if (ExprType >= FoldExpr && isFoldOperator(Tok.getKind()) &&
3115
140
        NextToken().is(tok::ellipsis)) {
3116
140
      ExprType = FoldExpr;
3117
140
      return ParseFoldExpression(Result, T);
3118
140
    }
3119
731k
    ExprType = SimpleExpr;
3120
731k
3121
    // Don't build a paren expression unless we actually match a ')'.
3122
731k
    if (!Result.isInvalid() && 
Tok.is(tok::r_paren)731k
)
3123
731k
      Result =
3124
731k
          Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
3125
731k
  }
3126
5.51M
3127
  // Match the ')'.
3128
1.10M
  if (Result.isInvalid()) {
3129
726
    SkipUntil(tok::r_paren, StopAtSemi);
3130
726
    return ExprError();
3131
726
  }
3132
1.10M
3133
1.10M
  T.consumeClose();
3134
1.10M
  RParenLoc = T.getCloseLocation();
3135
1.10M
  return Result;
3136
1.10M
}
3137
3138
/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
3139
/// and we are at the left brace.
3140
///
3141
/// \verbatim
3142
///       postfix-expression: [C99 6.5.2]
3143
///         '(' type-name ')' '{' initializer-list '}'
3144
///         '(' type-name ')' '{' initializer-list ',' '}'
3145
/// \endverbatim
3146
ExprResult
3147
Parser::ParseCompoundLiteralExpression(ParsedType Ty,
3148
                                       SourceLocation LParenLoc,
3149
49.7k
                                       SourceLocation RParenLoc) {
3150
49.7k
  assert(Tok.is(tok::l_brace) && "Not a compound literal!");
3151
49.7k
  if (!getLangOpts().C99)   // Compound literals don't exist in C90.
3152
6.16k
    Diag(LParenLoc, diag::ext_c99_compound_literal);
3153
49.7k
  ExprResult Result = ParseInitializer();
3154
49.7k
  if (!Result.isInvalid() && Ty)
3155
49.7k
    return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
3156
3
  return Result;
3157
3
}
3158
3159
/// ParseStringLiteralExpression - This handles the various token types that
3160
/// form string literals, and also handles string concatenation [C99 5.1.1.2,
3161
/// translation phase #6].
3162
///
3163
/// \verbatim
3164
///       primary-expression: [C99 6.5.1]
3165
///         string-literal
3166
/// \verbatim
3167
3.96M
ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
3168
3.96M
  assert(isTokenStringLiteral() && "Not a string literal!");
3169
3.96M
3170
  // String concat.  Note that keywords like __func__ and __FUNCTION__ are not
3171
  // considered to be strings for concatenation purposes.
3172
3.96M
  SmallVector<Token, 4> StringToks;
3173
3.96M
3174
4.17M
  do {
3175
4.17M
    StringToks.push_back(Tok);
3176
4.17M
    ConsumeStringToken();
3177
4.17M
  } while (isTokenStringLiteral());
3178
3.96M
3179
  // Pass the set of string tokens, ready for concatenation, to the actions.
3180
3.96M
  return Actions.ActOnStringLiteral(StringToks,
3181
2.90M
                                    AllowUserDefinedLiteral ? getCurScope()
3182
1.06M
                                                            : nullptr);
3183
3.96M
}
3184
3185
/// ParseGenericSelectionExpression - Parse a C11 generic-selection
3186
/// [C11 6.5.1.1].
3187
///
3188
/// \verbatim
3189
///    generic-selection:
3190
///           _Generic ( assignment-expression , generic-assoc-list )
3191
///    generic-assoc-list:
3192
///           generic-association
3193
///           generic-assoc-list , generic-association
3194
///    generic-association:
3195
///           type-name : assignment-expression
3196
///           default : assignment-expression
3197
/// \endverbatim
3198
396
ExprResult Parser::ParseGenericSelectionExpression() {
3199
396
  assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
3200
396
  if (!getLangOpts().C11)
3201
30
    Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3202
396
3203
396
  SourceLocation KeyLoc = ConsumeToken();
3204
396
  BalancedDelimiterTracker T(*this, tok::l_paren);
3205
396
  if (T.expectAndConsume())
3206
1
    return ExprError();
3207
395
3208
395
  ExprResult ControllingExpr;
3209
395
  {
3210
    // C11 6.5.1.1p3 "The controlling expression of a generic selection is
3211
    // not evaluated."
3212
395
    EnterExpressionEvaluationContext Unevaluated(
3213
395
        Actions, Sema::ExpressionEvaluationContext::Unevaluated);
3214
395
    ControllingExpr =
3215
395
        Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3216
395
    if (ControllingExpr.isInvalid()) {
3217
1
      SkipUntil(tok::r_paren, StopAtSemi);
3218
1
      return ExprError();
3219
1
    }
3220
394
  }
3221
394
3222
394
  if (ExpectAndConsume(tok::comma)) {
3223
1
    SkipUntil(tok::r_paren, StopAtSemi);
3224
1
    return ExprError();
3225
1
  }
3226
393
3227
393
  SourceLocation DefaultLoc;
3228
393
  TypeVector Types;
3229
393
  ExprVector Exprs;
3230
1.12k
  do {
3231
1.12k
    ParsedType Ty;
3232
1.12k
    if (Tok.is(tok::kw_default)) {
3233
      // C11 6.5.1.1p2 "A generic selection shall have no more than one default
3234
      // generic association."
3235
58
      if (!DefaultLoc.isInvalid()) {
3236
1
        Diag(Tok, diag::err_duplicate_default_assoc);
3237
1
        Diag(DefaultLoc, diag::note_previous_default_assoc);
3238
1
        SkipUntil(tok::r_paren, StopAtSemi);
3239
1
        return ExprError();
3240
1
      }
3241
57
      DefaultLoc = ConsumeToken();
3242
57
      Ty = nullptr;
3243
1.06k
    } else {
3244
1.06k
      ColonProtectionRAIIObject X(*this);
3245
1.06k
      TypeResult TR = ParseTypeName();
3246
1.06k
      if (TR.isInvalid()) {
3247
0
        SkipUntil(tok::r_paren, StopAtSemi);
3248
0
        return ExprError();
3249
0
      }
3250
1.06k
      Ty = TR.get();
3251
1.06k
    }
3252
1.12k
    Types.push_back(Ty);
3253
1.12k
3254
1.12k
    if (ExpectAndConsume(tok::colon)) {
3255
1
      SkipUntil(tok::r_paren, StopAtSemi);
3256
1
      return ExprError();
3257
1
    }
3258
1.12k
3259
    // FIXME: These expressions should be parsed in a potentially potentially
3260
    // evaluated context.
3261
1.12k
    ExprResult ER(
3262
1.12k
        Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
3263
1.12k
    if (ER.isInvalid()) {
3264
12
      SkipUntil(tok::r_paren, StopAtSemi);
3265
12
      return ExprError();
3266
12
    }
3267
1.11k
    Exprs.push_back(ER.get());
3268
1.11k
  } while (TryConsumeToken(tok::comma));
3269
393
3270
379
  T.consumeClose();
3271
379
  if (T.getCloseLocation().isInvalid())
3272
0
    return ExprError();
3273
379
3274
379
  return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
3275
379
                                           T.getCloseLocation(),
3276
379
                                           ControllingExpr.get(),
3277
379
                                           Types, Exprs);
3278
379
}
3279
3280
/// Parse A C++1z fold-expression after the opening paren and optional
3281
/// left-hand-side expression.
3282
///
3283
/// \verbatim
3284
///   fold-expression:
3285
///       ( cast-expression fold-operator ... )
3286
///       ( ... fold-operator cast-expression )
3287
///       ( cast-expression fold-operator ... fold-operator cast-expression )
3288
ExprResult Parser::ParseFoldExpression(ExprResult LHS,
3289
170
                                       BalancedDelimiterTracker &T) {
3290
170
  if (LHS.isInvalid()) {
3291
1
    T.skipToEnd();
3292
1
    return true;
3293
1
  }
3294
169
3295
169
  tok::TokenKind Kind = tok::unknown;
3296
169
  SourceLocation FirstOpLoc;
3297
169
  if (LHS.isUsable()) {
3298
157
    Kind = Tok.getKind();
3299
157
    assert(isFoldOperator(Kind) && "missing fold-operator");
3300
157
    FirstOpLoc = ConsumeToken();
3301
157
  }
3302
169
3303
169
  assert(Tok.is(tok::ellipsis) && "not a fold-expression");
3304
169
  SourceLocation EllipsisLoc = ConsumeToken();
3305
169
3306
169
  ExprResult RHS;
3307
169
  if (Tok.isNot(tok::r_paren)) {
3308
61
    if (!isFoldOperator(Tok.getKind()))
3309
1
      return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
3310
60
3311
60
    if (Kind != tok::unknown && 
Tok.getKind() != Kind48
)
3312
2
      Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
3313
2
        << SourceRange(FirstOpLoc);
3314
60
    Kind = Tok.getKind();
3315
60
    ConsumeToken();
3316
60
3317
60
    RHS = ParseExpression();
3318
60
    if (RHS.isInvalid()) {
3319
0
      T.skipToEnd();
3320
0
      return true;
3321
0
    }
3322
168
  }
3323
168
3324
168
  Diag(EllipsisLoc, getLangOpts().CPlusPlus17
3325
145
                        ? diag::warn_cxx14_compat_fold_expression
3326
23
                        : diag::ext_fold_expression);
3327
168
3328
168
  T.consumeClose();
3329
168
  return Actions.ActOnCXXFoldExpr(getCurScope(), T.getOpenLocation(), LHS.get(),
3330
168
                                  Kind, EllipsisLoc, RHS.get(),
3331
168
                                  T.getCloseLocation());
3332
168
}
3333
3334
/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
3335
///
3336
/// \verbatim
3337
///       argument-expression-list:
3338
///         assignment-expression
3339
///         argument-expression-list , assignment-expression
3340
///
3341
/// [C++] expression-list:
3342
/// [C++]   assignment-expression
3343
/// [C++]   expression-list , assignment-expression
3344
///
3345
/// [C++0x] expression-list:
3346
/// [C++0x]   initializer-list
3347
///
3348
/// [C++0x] initializer-list
3349
/// [C++0x]   initializer-clause ...[opt]
3350
/// [C++0x]   initializer-list , initializer-clause ...[opt]
3351
///
3352
/// [C++0x] initializer-clause:
3353
/// [C++0x]   assignment-expression
3354
/// [C++0x]   braced-init-list
3355
/// \endverbatim
3356
bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
3357
                                 SmallVectorImpl<SourceLocation> &CommaLocs,
3358
3.80M
                                 llvm::function_ref<void()> ExpressionStarts) {
3359
3.80M
  bool SawError = false;
3360
8.83M
  while (1) {
3361
8.83M
    if (ExpressionStarts)
3362
8.81M
      ExpressionStarts();
3363
8.83M
3364
8.83M
    ExprResult Expr;
3365
8.83M
    if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)3.48M
) {
3366
1.50k
      Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3367
1.50k
      Expr = ParseBraceInitializer();
3368
1.50k
    } else
3369
8.83M
      Expr = ParseAssignmentExpression();
3370
8.83M
3371
8.83M
    if (Tok.is(tok::ellipsis))
3372
40.5k
      Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
3373
8.79M
    else if (Tok.is(tok::code_completion)) {
3374
      // There's nothing to suggest in here as we parsed a full expression.
3375
      // Instead fail and propogate the error since caller might have something
3376
      // the suggest, e.g. signature help in function call. Note that this is
3377
      // performed before pushing the \p Expr, so that signature help can report
3378
      // current argument correctly.
3379
1
      SawError = true;
3380
1
      cutOffParsing();
3381
1
      break;
3382
1
    }
3383
8.83M
    if (Expr.isInvalid()) {
3384
5.63k
      SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
3385
5.63k
      SawError = true;
3386
8.82M
    } else {
3387
8.82M
      Exprs.push_back(Expr.get());
3388
8.82M
    }
3389
8.83M
3390
8.83M
    if (Tok.isNot(tok::comma))
3391
3.80M
      break;
3392
    // Move to the next argument, remember where the comma was.
3393
5.02M
    Token Comma = Tok;
3394
5.02M
    CommaLocs.push_back(ConsumeToken());
3395
5.02M
3396
5.02M
    checkPotentialAngleBracketDelimiter(Comma);
3397
5.02M
  }
3398
3.80M
  if (SawError) {
3399
    // Ensure typos get diagnosed when errors were encountered while parsing the
3400
    // expression list.
3401
3.83k
    for (auto &E : Exprs) {
3402
3.83k
      ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
3403
3.83k
      if (Expr.isUsable()) 
E = Expr.get()3.09k
;
3404
3.83k
    }
3405
4.81k
  }
3406
3.80M
  return SawError;
3407
3.80M
}
3408
3409
/// ParseSimpleExpressionList - A simple comma-separated list of expressions,
3410
/// used for misc language extensions.
3411
///
3412
/// \verbatim
3413
///       simple-expression-list:
3414
///         assignment-expression
3415
///         simple-expression-list , assignment-expression
3416
/// \endverbatim
3417
bool
3418
Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
3419
363k
                                  SmallVectorImpl<SourceLocation> &CommaLocs) {
3420
474k
  while (1) {
3421
474k
    ExprResult Expr = ParseAssignmentExpression();
3422
474k
    if (Expr.isInvalid())
3423
61
      return true;
3424
474k
3425
474k
    Exprs.push_back(Expr.get());
3426
474k
3427
474k
    if (Tok.isNot(tok::comma))
3428
363k
      return false;
3429
110k
3430
    // Move to the next argument, remember where the comma was.
3431
110k
    Token Comma = Tok;
3432
110k
    CommaLocs.push_back(ConsumeToken());
3433
110k
3434
110k
    checkPotentialAngleBracketDelimiter(Comma);
3435
110k
  }
3436
363k
}
3437
3438
/// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
3439
///
3440
/// \verbatim
3441
/// [clang] block-id:
3442
/// [clang]   specifier-qualifier-list block-declarator
3443
/// \endverbatim
3444
323
void Parser::ParseBlockId(SourceLocation CaretLoc) {
3445
323
  if (Tok.is(tok::code_completion)) {
3446
1
    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
3447
1
    return cutOffParsing();
3448
1
  }
3449
322
3450
  // Parse the specifier-qualifier-list piece.
3451
322
  DeclSpec DS(AttrFactory);
3452
322
  ParseSpecifierQualifierList(DS);
3453
322
3454
  // Parse the block-declarator.
3455
322
  Declarator DeclaratorInfo(DS, DeclaratorContext::BlockLiteralContext);
3456
322
  DeclaratorInfo.setFunctionDefinitionKind(FDK_Definition);
3457
322
  ParseDeclarator(DeclaratorInfo);
3458
322
3459
322
  MaybeParseGNUAttributes(DeclaratorInfo);
3460
322
3461
  // Inform sema that we are starting a block.
3462
322
  Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
3463
322
}
3464
3465
/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
3466
/// like ^(int x){ return x+1; }
3467
///
3468
/// \verbatim
3469
///         block-literal:
3470
/// [clang]   '^' block-args[opt] compound-statement
3471
/// [clang]   '^' block-id compound-statement
3472
/// [clang] block-args:
3473
/// [clang]   '(' parameter-list ')'
3474
/// \endverbatim
3475
2.84k
ExprResult Parser::ParseBlockLiteralExpression() {
3476
2.84k
  assert(Tok.is(tok::caret) && "block literal starts with ^");
3477
2.84k
  SourceLocation CaretLoc = ConsumeToken();
3478
2.84k
3479
2.84k
  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
3480
2.84k
                                "block literal parsing");
3481
2.84k
3482
  // Enter a scope to hold everything within the block.  This includes the
3483
  // argument decls, decls within the compound expression, etc.  This also
3484
  // allows determining whether a variable reference inside the block is
3485
  // within or outside of the block.
3486
2.84k
  ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
3487
2.84k
                                  Scope::CompoundStmtScope | Scope::DeclScope);
3488
2.84k
3489
  // Inform sema that we are starting a block.
3490
2.84k
  Actions.ActOnBlockStart(CaretLoc, getCurScope());
3491
2.84k
3492
  // Parse the return type if present.
3493
2.84k
  DeclSpec DS(AttrFactory);
3494
2.84k
  Declarator ParamInfo(DS, DeclaratorContext::BlockLiteralContext);
3495
2.84k
  ParamInfo.setFunctionDefinitionKind(FDK_Definition);
3496
  // FIXME: Since the return type isn't actually parsed, it can't be used to
3497
  // fill ParamInfo with an initial valid range, so do it manually.
3498
2.84k
  ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
3499
2.84k
3500
  // If this block has arguments, parse them.  There is no ambiguity here with
3501
  // the expression case, because the expression case requires a parameter list.
3502
2.84k
  if (Tok.is(tok::l_paren)) {
3503
959
    ParseParenDeclarator(ParamInfo);
3504
    // Parse the pieces after the identifier as if we had "int(...)".
3505
    // SetIdentifier sets the source range end, but in this case we're past
3506
    // that location.
3507
959
    SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
3508
959
    ParamInfo.SetIdentifier(nullptr, CaretLoc);
3509
959
    ParamInfo.SetRangeEnd(Tmp);
3510
959
    if (ParamInfo.isInvalidType()) {
3511
      // If there was an error parsing the arguments, they may have
3512
      // tried to use ^(x+y) which requires an argument list.  Just
3513
      // skip the whole block literal.
3514
0
      Actions.ActOnBlockError(CaretLoc, getCurScope());
3515
0
      return ExprError();
3516
0
    }
3517
959
3518
959
    MaybeParseGNUAttributes(ParamInfo);
3519
959
3520
    // Inform sema that we are starting a block.
3521
959
    Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3522
1.88k
  } else if (!Tok.is(tok::l_brace)) {
3523
323
    ParseBlockId(CaretLoc);
3524
1.56k
  } else {
3525
    // Otherwise, pretend we saw (void).
3526
1.56k
    SourceLocation NoLoc;
3527
1.56k
    ParamInfo.AddTypeInfo(
3528
1.56k
        DeclaratorChunk::getFunction(/*HasProto=*/true,
3529
1.56k
                                     /*IsAmbiguous=*/false,
3530
1.56k
                                     /*RParenLoc=*/NoLoc,
3531
1.56k
                                     /*ArgInfo=*/nullptr,
3532
1.56k
                                     /*NumParams=*/0,
3533
1.56k
                                     /*EllipsisLoc=*/NoLoc,
3534
1.56k
                                     /*RParenLoc=*/NoLoc,
3535
1.56k
                                     /*RefQualifierIsLvalueRef=*/true,
3536
1.56k
                                     /*RefQualifierLoc=*/NoLoc,
3537
1.56k
                                     /*MutableLoc=*/NoLoc, EST_None,
3538
1.56k
                                     /*ESpecRange=*/SourceRange(),
3539
1.56k
                                     /*Exceptions=*/nullptr,
3540
1.56k
                                     /*ExceptionRanges=*/nullptr,
3541
1.56k
                                     /*NumExceptions=*/0,
3542
1.56k
                                     /*NoexceptExpr=*/nullptr,
3543
1.56k
                                     /*ExceptionSpecTokens=*/nullptr,
3544
1.56k
                                     /*DeclsInPrototype=*/None, CaretLoc,
3545
1.56k
                                     CaretLoc, ParamInfo),
3546
1.56k
        CaretLoc);
3547
1.56k
3548
1.56k
    MaybeParseGNUAttributes(ParamInfo);
3549
1.56k
3550
    // Inform sema that we are starting a block.
3551
1.56k
    Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3552
1.56k
  }
3553
2.84k
3554
2.84k
3555
2.84k
  ExprResult Result(true);
3556
2.84k
  if (!Tok.is(tok::l_brace)) {
3557
    // Saw something like: ^expr
3558
131
    Diag(Tok, diag::err_expected_expression);
3559
131
    Actions.ActOnBlockError(CaretLoc, getCurScope());
3560
131
    return ExprError();
3561
131
  }
3562
2.71k
3563
2.71k
  StmtResult Stmt(ParseCompoundStatementBody());
3564
2.71k
  BlockScope.Exit();
3565
2.71k
  if (!Stmt.isInvalid())
3566
2.71k
    Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
3567
0
  else
3568
0
    Actions.ActOnBlockError(CaretLoc, getCurScope());
3569
2.71k
  return Result;
3570
2.71k
}
3571
3572
/// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
3573
///
3574
///         '__objc_yes'
3575
///         '__objc_no'
3576
1.07k
ExprResult Parser::ParseObjCBoolLiteral() {
3577
1.07k
  tok::TokenKind Kind = Tok.getKind();
3578
1.07k
  return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
3579
1.07k
}
3580
3581
/// Validate availability spec list, emitting diagnostics if necessary. Returns
3582
/// true if invalid.
3583
static bool CheckAvailabilitySpecList(Parser &P,
3584
77
                                      ArrayRef<AvailabilitySpec> AvailSpecs) {
3585
77
  llvm::SmallSet<StringRef, 4> Platforms;
3586
77
  bool HasOtherPlatformSpec = false;
3587
77
  bool Valid = true;
3588
161
  for (const auto &Spec : AvailSpecs) {
3589
161
    if (Spec.isOtherPlatformSpec()) {
3590
76
      if (HasOtherPlatformSpec) {
3591
0
        P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
3592
0
        Valid = false;
3593
0
      }
3594
76
3595
76
      HasOtherPlatformSpec = true;
3596
76
      continue;
3597
76
    }
3598
85
3599
85
    bool Inserted = Platforms.insert(Spec.getPlatform()).second;
3600
85
    if (!Inserted) {
3601
      // Rule out multiple version specs referring to the same platform.
3602
      // For example, we emit an error for:
3603
      // @available(macos 10.10, macos 10.11, *)
3604
1
      StringRef Platform = Spec.getPlatform();
3605
1
      P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
3606
1
          << Spec.getEndLoc() << Platform;
3607
1
      Valid = false;
3608
1
    }
3609
85
  }
3610
77
3611
77
  if (!HasOtherPlatformSpec) {
3612
1
    SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
3613
1
    P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
3614
1
        << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
3615
1
    return true;
3616
1
  }
3617
76
3618
76
  return !Valid;
3619
76
}
3620
3621
/// Parse availability query specification.
3622
///
3623
///  availability-spec:
3624
///     '*'
3625
///     identifier version-tuple
3626
172
Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
3627
172
  if (Tok.is(tok::star)) {
3628
78
    return AvailabilitySpec(ConsumeToken());
3629
94
  } else {
3630
    // Parse the platform name.
3631
94
    if (Tok.is(tok::code_completion)) {
3632
2
      Actions.CodeCompleteAvailabilityPlatformName();
3633
2
      cutOffParsing();
3634
2
      return None;
3635
2
    }
3636
92
    if (Tok.isNot(tok::identifier)) {
3637
2
      Diag(Tok, diag::err_avail_query_expected_platform_name);
3638
2
      return None;
3639
2
    }
3640
90
3641
90
    IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
3642
90
    SourceRange VersionRange;
3643
90
    VersionTuple Version = ParseVersionTuple(VersionRange);
3644
90
3645
90
    if (Version.empty())
3646
1
      return None;
3647
89
3648
89
    StringRef GivenPlatform = PlatformIdentifier->Ident->getName();
3649
89
    StringRef Platform =
3650
89
        AvailabilityAttr::canonicalizePlatformName(GivenPlatform);
3651
89
3652
89
    if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
3653
3
      Diag(PlatformIdentifier->Loc,
3654
3
           diag::err_avail_query_unrecognized_platform_name)
3655
3
          << GivenPlatform;
3656
3
      return None;
3657
3
    }
3658
86
3659
86
    return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
3660
86
                            VersionRange.getEnd());
3661
86
  }
3662
172
}
3663
3664
85
ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
3665
85
  assert(Tok.is(tok::kw___builtin_available) ||
3666
85
         Tok.isObjCAtKeyword(tok::objc_available));
3667
85
3668
  // Eat the available or __builtin_available.
3669
85
  ConsumeToken();
3670
85
3671
85
  BalancedDelimiterTracker Parens(*this, tok::l_paren);
3672
85
  if (Parens.expectAndConsume())
3673
1
    return ExprError();
3674
84
3675
84
  SmallVector<AvailabilitySpec, 4> AvailSpecs;
3676
84
  bool HasError = false;
3677
172
  while (true) {
3678
172
    Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
3679
172
    if (!Spec)
3680
8
      HasError = true;
3681
164
    else
3682
164
      AvailSpecs.push_back(*Spec);
3683
172
3684
172
    if (!TryConsumeToken(tok::comma))
3685
84
      break;
3686
172
  }
3687
84
3688
84
  if (HasError) {
3689
7
    SkipUntil(tok::r_paren, StopAtSemi);
3690
7
    return ExprError();
3691
7
  }
3692
77
3693
77
  CheckAvailabilitySpecList(*this, AvailSpecs);
3694
77
3695
77
  if (Parens.consumeClose())
3696
0
    return ExprError();
3697
77
3698
77
  return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
3699
77
                                                Parens.getCloseLocation());
3700
77
}