Coverage Report

Created: 2022-01-25 06:29

/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
7.32M
ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
124
7.32M
  ExprResult LHS(ParseAssignmentExpression(isTypeCast));
125
7.32M
  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
126
7.32M
}
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.60k
Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
144
3.60k
  ExprResult LHS(true);
145
3.60k
  {
146
    // Silence extension warnings in the sub-expression
147
3.60k
    ExtensionRAIIObject O(Diags);
148
149
3.60k
    LHS = ParseCastExpression(AnyCastExpr);
150
3.60k
  }
151
152
3.60k
  if (!LHS.isInvalid())
153
3.60k
    LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
154
3.60k
                               LHS.get());
155
156
3.60k
  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
157
3.60k
}
158
159
/// Parse an expr that doesn't include (top-level) commas.
160
23.5M
ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
161
23.5M
  if (Tok.is(tok::code_completion)) {
162
220
    cutOffParsing();
163
220
    Actions.CodeCompleteExpression(getCurScope(),
164
220
                                   PreferredType.get(Tok.getLocation()));
165
220
    return ExprError();
166
220
  }
167
168
23.5M
  if (Tok.is(tok::kw_throw))
169
15.1k
    return ParseThrowExpression();
170
23.5M
  if (Tok.is(tok::kw_co_yield))
171
288
    return ParseCoyieldExpression();
172
173
23.5M
  ExprResult LHS = ParseCastExpression(AnyCastExpr,
174
23.5M
                                       /*isAddressOfOperand=*/false,
175
23.5M
                                       isTypeCast);
176
23.5M
  return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
177
23.5M
}
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
4.56M
Parser::ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast) {
202
4.56M
  assert(Actions.ExprEvalContexts.back().Context ==
203
4.56M
             Sema::ExpressionEvaluationContext::ConstantEvaluated &&
204
4.56M
         "Call this function only if your ExpressionEvaluationContext is "
205
4.56M
         "already ConstantEvaluated");
206
0
  ExprResult LHS(ParseCastExpression(AnyCastExpr, false, isTypeCast));
207
4.56M
  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
208
4.56M
  return Actions.ActOnConstantExpression(Res);
209
4.56M
}
210
211
160k
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
160k
  EnterExpressionEvaluationContext ConstantEvaluated(
217
160k
      Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
218
160k
  return ParseConstantExpressionInExprEvalContext(isTypeCast);
219
160k
}
220
221
22.1k
ExprResult Parser::ParseCaseExpression(SourceLocation CaseLoc) {
222
22.1k
  EnterExpressionEvaluationContext ConstantEvaluated(
223
22.1k
      Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
224
22.1k
  ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast));
225
22.1k
  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
226
22.1k
  return Actions.ActOnCaseExpr(CaseLoc, Res);
227
22.1k
}
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
330
ExprResult Parser::ParseConstraintExpression() {
236
330
  EnterExpressionEvaluationContext ConstantEvaluated(
237
330
      Actions, Sema::ExpressionEvaluationContext::Unevaluated);
238
330
  ExprResult LHS(ParseCastExpression(AnyCastExpr));
239
330
  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
240
330
  if (Res.isUsable() && 
!Actions.CheckConstraintExpression(Res.get())327
) {
241
6
    Actions.CorrectDelayedTyposInExpr(Res);
242
6
    return ExprError();
243
6
  }
244
324
  return Res;
245
330
}
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
496
Parser::ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause) {
258
496
  EnterExpressionEvaluationContext ConstantEvaluated(
259
496
      Actions, Sema::ExpressionEvaluationContext::Unevaluated);
260
496
  bool NotPrimaryExpression = false;
261
527
  auto ParsePrimary = [&] () {
262
527
    ExprResult E = ParseCastExpression(PrimaryExprOnly,
263
527
                                       /*isAddressOfOperand=*/false,
264
527
                                       /*isTypeCast=*/NotTypeCast,
265
527
                                       /*isVectorLiteral=*/false,
266
527
                                       &NotPrimaryExpression);
267
527
    if (E.isInvalid())
268
6
      return ExprError();
269
521
    auto RecoverFromNonPrimary = [&] (ExprResult E, bool Note) {
270
22
        E = ParsePostfixExpressionSuffix(E);
271
        // Use InclusiveOr, the precedence just after '&&' to not parse the
272
        // next arguments to the logical and.
273
22
        E = ParseRHSOfBinaryExpression(E, prec::InclusiveOr);
274
22
        if (!E.isInvalid())
275
20
          Diag(E.get()->getExprLoc(),
276
20
               Note
277
20
               ? 
diag::note_unparenthesized_non_primary_expr_in_requires_clause4
278
20
               : 
diag::err_unparenthesized_non_primary_expr_in_requires_clause16
)
279
20
               << FixItHint::CreateInsertion(E.get()->getBeginLoc(), "(")
280
20
               << FixItHint::CreateInsertion(
281
20
                   PP.getLocForEndOfToken(E.get()->getEndLoc()), ")")
282
20
               << E.get()->getSourceRange();
283
22
        return E;
284
22
    };
285
286
521
    if (NotPrimaryExpression ||
287
        // Check if the following tokens must be a part of a non-primary
288
        // expression
289
521
        getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
290
513
                           /*CPlusPlus11=*/true) > prec::LogicalAnd ||
291
        // Postfix operators other than '(' (which will be checked for in
292
        // CheckConstraintExpression).
293
521
        
Tok.isOneOf(tok::period, tok::plusplus, tok::minusminus)509
||
294
521
        
(509
Tok.is(tok::l_square)509
&&
!NextToken().is(tok::l_square)0
)) {
295
12
      E = RecoverFromNonPrimary(E, /*Note=*/false);
296
12
      if (E.isInvalid())
297
0
        return ExprError();
298
12
      NotPrimaryExpression = false;
299
12
    }
300
521
    bool PossibleNonPrimary;
301
521
    bool IsConstraintExpr =
302
521
        Actions.CheckConstraintExpression(E.get(), Tok, &PossibleNonPrimary,
303
521
                                          IsTrailingRequiresClause);
304
521
    if (!IsConstraintExpr || 
PossibleNonPrimary515
) {
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
12
      if (PossibleNonPrimary)
310
10
        E = RecoverFromNonPrimary(E, /*Note=*/!IsConstraintExpr);
311
12
      Actions.CorrectDelayedTyposInExpr(E);
312
12
      return ExprError();
313
12
    }
314
509
    return E;
315
521
  };
316
496
  ExprResult LHS = ParsePrimary();
317
496
  if (LHS.isInvalid())
318
18
    return ExprError();
319
509
  
while (478
Tok.is(tok::ampamp)) {
320
31
    SourceLocation LogicalAndLoc = ConsumeToken();
321
31
    ExprResult RHS = ParsePrimary();
322
31
    if (RHS.isInvalid()) {
323
0
      Actions.CorrectDelayedTyposInExpr(LHS);
324
0
      return ExprError();
325
0
    }
326
31
    ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalAndLoc,
327
31
                                       tok::ampamp, LHS.get(), RHS.get());
328
31
    if (!Op.isUsable()) {
329
0
      Actions.CorrectDelayedTyposInExpr(RHS);
330
0
      Actions.CorrectDelayedTyposInExpr(LHS);
331
0
      return ExprError();
332
0
    }
333
31
    LHS = Op;
334
31
  }
335
478
  return LHS;
336
478
}
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
488
Parser::ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause) {
350
488
  ExprResult LHS(ParseConstraintLogicalAndExpression(IsTrailingRequiresClause));
351
488
  if (!LHS.isUsable())
352
18
    return ExprError();
353
478
  
while (470
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
470
  return LHS;
371
470
}
372
373
42.2k
bool Parser::isNotExpressionStart() {
374
42.2k
  tok::TokenKind K = Tok.getKind();
375
42.2k
  if (K == tok::l_brace || 
K == tok::r_brace42.2k
||
376
42.2k
      
K == tok::kw_for42.2k
||
K == tok::kw_while42.2k
||
377
42.2k
      
K == tok::kw_if42.2k
||
K == tok::kw_else42.2k
||
378
42.2k
      
K == tok::kw_goto42.2k
||
K == tok::kw_try42.2k
)
379
5
    return true;
380
  // If this is a decl-specifier, we can't be at the start of an expression.
381
42.2k
  return isKnownToBeDeclarationSpecifier();
382
42.2k
}
383
384
4.56M
bool Parser::isFoldOperator(prec::Level Level) const {
385
4.56M
  return Level > prec::Unknown && 
Level != prec::Conditional3.53M
&&
386
4.56M
         
Level != prec::Spaceship3.48M
;
387
4.56M
}
388
389
1.02M
bool Parser::isFoldOperator(tok::TokenKind Kind) const {
390
1.02M
  return isFoldOperator(getBinOpPrecedence(Kind, GreaterThanIsOperator, true));
391
1.02M
}
392
393
/// Parse a binary expression that starts with \p LHS and has a
394
/// precedence of at least \p MinPrec.
395
ExprResult
396
35.6M
Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
397
35.6M
  prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
398
35.6M
                                               GreaterThanIsOperator,
399
35.6M
                                               getLangOpts().CPlusPlus11);
400
35.6M
  SourceLocation ColonLoc;
401
402
35.6M
  auto SavedType = PreferredType;
403
39.1M
  while (true) {
404
    // Every iteration may rely on a preferred type for the whole expression.
405
39.1M
    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
39.1M
    if (NextTokPrec < MinPrec)
410
35.6M
      return LHS;
411
412
    // Consume the operator, saving the operator token for error reporting.
413
3.53M
    Token OpToken = Tok;
414
3.53M
    ConsumeToken();
415
416
3.53M
    if (OpToken.is(tok::caretcaret)) {
417
2
      return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
418
2
    }
419
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.53M
    if (OpToken.isOneOf(tok::comma, tok::greater, tok::greatergreater,
423
3.53M
                        tok::greatergreatergreater) &&
424
3.53M
        
checkPotentialAngleBracketDelimiter(OpToken)167k
)
425
18
      return ExprError();
426
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.53M
    if (OpToken.is(tok::comma) && 
isNotExpressionStart()42.2k
) {
433
21
      PP.EnterToken(Tok, /*IsReinject*/true);
434
21
      Tok = OpToken;
435
21
      return LHS;
436
21
    }
437
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.53M
    if (isFoldOperator(NextTokPrec) && 
Tok.is(tok::ellipsis)3.48M
) {
441
      // FIXME: We can't check this via lookahead before we consume the token
442
      // because that tickles a lexer bug.
443
343
      PP.EnterToken(Tok, /*IsReinject*/true);
444
343
      Tok = OpToken;
445
343
      return LHS;
446
343
    }
447
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.53M
    if (getLangOpts().ObjC && 
getLangOpts().CPlusPlus664k
&&
454
3.53M
        
Tok.isOneOf(tok::colon, tok::r_square)231k
&&
455
3.53M
        
OpToken.getIdentifierInfo() != nullptr31
) {
456
16
      PP.EnterToken(Tok, /*IsReinject*/true);
457
16
      Tok = OpToken;
458
16
      return LHS;
459
16
    }
460
461
    // Special case handling for the ternary operator.
462
3.53M
    ExprResult TernaryMiddle(true);
463
3.53M
    if (NextTokPrec == prec::Conditional) {
464
55.1k
      if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)46.8k
) {
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.1k
      } else if (Tok.isNot(tok::colon)) {
475
        // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
476
54.8k
        ColonProtectionRAIIObject X(*this);
477
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
54.8k
        TernaryMiddle = ParseExpression();
483
54.8k
      } else {
484
        // Special case handling of "X ? Y : Z" where Y is empty:
485
        //   logical-OR-expression '?' ':' conditional-expression   [GNU]
486
274
        TernaryMiddle = nullptr;
487
274
        Diag(Tok, diag::ext_gnu_conditional_expr);
488
274
      }
489
490
55.1k
      if (TernaryMiddle.isInvalid()) {
491
26
        Actions.CorrectDelayedTyposInExpr(LHS);
492
26
        LHS = ExprError();
493
26
        TernaryMiddle = nullptr;
494
26
      }
495
496
55.1k
      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
0
          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
519
0
        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.1k
    }
525
526
0
    PreferredType.enterBinary(Actions, Tok.getLocation(), LHS.get(),
527
3.53M
                              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.53M
    ExprResult RHS;
539
3.53M
    bool RHSIsInitList = false;
540
3.53M
    if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)2.39M
) {
541
86
      RHS = ParseBraceInitializer();
542
86
      RHSIsInitList = true;
543
3.53M
    } else if (getLangOpts().CPlusPlus && 
NextTokPrec <= prec::Conditional2.43M
)
544
713k
      RHS = ParseAssignmentExpression();
545
2.82M
    else
546
2.82M
      RHS = ParseCastExpression(AnyCastExpr);
547
548
3.53M
    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
1.04k
      Actions.CorrectDelayedTyposInExpr(LHS);
552
1.04k
      if (TernaryMiddle.isUsable())
553
4
        TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
554
1.04k
      LHS = ExprError();
555
1.04k
    }
556
557
    // Remember the precedence of this operator and get the precedence of the
558
    // operator immediately to the right of the RHS.
559
3.53M
    prec::Level ThisPrec = NextTokPrec;
560
3.53M
    NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
561
3.53M
                                     getLangOpts().CPlusPlus11);
562
563
    // Assignment and conditional expressions are right-associative.
564
3.53M
    bool isRightAssoc = ThisPrec == prec::Conditional ||
565
3.53M
                        
ThisPrec == prec::Assignment3.48M
;
566
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.53M
    if (ThisPrec < NextTokPrec ||
570
3.53M
        
(3.39M
ThisPrec == NextTokPrec3.39M
&&
isRightAssoc112k
)) {
571
143k
      if (!RHS.isInvalid() && 
RHSIsInitList143k
) {
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
143k
      RHS = ParseRHSOfBinaryExpression(RHS,
582
143k
                            static_cast<prec::Level>(ThisPrec + !isRightAssoc));
583
143k
      RHSIsInitList = false;
584
585
143k
      if (RHS.isInvalid()) {
586
        // FIXME: Errors generated by the delayed typo correction should be
587
        // printed before errors from ParseRHSOfBinaryExpression, not after.
588
12
        Actions.CorrectDelayedTyposInExpr(LHS);
589
12
        if (TernaryMiddle.isUsable())
590
0
          TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
591
12
        LHS = ExprError();
592
12
      }
593
594
143k
      NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
595
143k
                                       getLangOpts().CPlusPlus11);
596
143k
    }
597
598
3.53M
    if (!RHS.isInvalid() && 
RHSIsInitList3.53M
) {
599
82
      if (ThisPrec == prec::Assignment) {
600
79
        Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
601
79
          << Actions.getExprRange(RHS.get());
602
79
      } else 
if (3
ColonLoc.isValid()3
) {
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
82
    }
614
615
3.53M
    ExprResult OrigLHS = LHS;
616
3.53M
    if (!LHS.isInvalid()) {
617
      // Combine the LHS and RHS into the LHS (e.g. build AST).
618
3.53M
      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.48M
        if (!GreaterThanIsOperator && 
OpToken.is(tok::greatergreater)111k
)
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
628
3.48M
        ExprResult BinOp =
629
3.48M
            Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
630
3.48M
                               OpToken.getKind(), LHS.get(), RHS.get());
631
3.48M
        if (BinOp.isInvalid())
632
3.59k
          BinOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
633
3.59k
                                             RHS.get()->getEndLoc(),
634
3.59k
                                             {LHS.get(), RHS.get()});
635
636
3.48M
        LHS = BinOp;
637
3.48M
      } else {
638
54.9k
        ExprResult CondOp = Actions.ActOnConditionalOp(
639
54.9k
            OpToken.getLocation(), ColonLoc, LHS.get(), TernaryMiddle.get(),
640
54.9k
            RHS.get());
641
54.9k
        if (CondOp.isInvalid()) {
642
352
          std::vector<clang::Expr *> Args;
643
          // TernaryMiddle can be null for the GNU conditional expr extension.
644
352
          if (TernaryMiddle.get())
645
341
            Args = {LHS.get(), TernaryMiddle.get(), RHS.get()};
646
11
          else
647
11
            Args = {LHS.get(), RHS.get()};
648
352
          CondOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
649
352
                                              RHS.get()->getEndLoc(), Args);
650
352
        }
651
652
54.9k
        LHS = CondOp;
653
54.9k
      }
654
      // In this case, ActOnBinOp or ActOnConditionalOp performed the
655
      // CorrectDelayedTyposInExpr check.
656
3.53M
      if (!getLangOpts().CPlusPlus)
657
1.10M
        continue;
658
3.53M
    }
659
660
    // Ensure potential typos aren't left undiagnosed.
661
2.43M
    if (LHS.isInvalid()) {
662
1.78k
      Actions.CorrectDelayedTyposInExpr(OrigLHS);
663
1.78k
      Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
664
1.78k
      Actions.CorrectDelayedTyposInExpr(RHS);
665
1.78k
    }
666
2.43M
  }
667
35.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.2M
                                       bool *NotPrimaryExpression) {
680
37.2M
  bool NotCastExpr;
681
37.2M
  ExprResult Res = ParseCastExpression(ParseKind,
682
37.2M
                                       isAddressOfOperand,
683
37.2M
                                       NotCastExpr,
684
37.2M
                                       isTypeCast,
685
37.2M
                                       isVectorLiteral,
686
37.2M
                                       NotPrimaryExpression);
687
37.2M
  if (NotCastExpr)
688
14.7k
    Diag(Tok, diag::err_expected_expression);
689
37.2M
  return Res;
690
37.2M
}
691
692
namespace {
693
class CastExpressionIdValidator final : public CorrectionCandidateCallback {
694
 public:
695
  CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
696
13.4M
      : NextToken(Next), AllowNonTypes(AllowNonTypes) {
697
13.4M
    WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
698
13.4M
  }
699
700
437
  bool ValidateCandidate(const TypoCorrection &candidate) override {
701
437
    NamedDecl *ND = candidate.getCorrectionDecl();
702
437
    if (!ND)
703
14
      return candidate.isKeyword();
704
705
423
    if (isa<TypeDecl>(ND))
706
57
      return WantTypeSpecifiers;
707
708
366
    if (!AllowNonTypes || 
!CorrectionCandidateCallback::ValidateCandidate(candidate)358
)
709
8
      return false;
710
711
358
    if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
712
305
      return true;
713
714
53
    for (auto *C : candidate) {
715
53
      NamedDecl *ND = C->getUnderlyingDecl();
716
53
      if (isa<ValueDecl>(ND) && 
!isa<FunctionDecl>(ND)50
)
717
44
        return true;
718
53
    }
719
9
    return false;
720
53
  }
721
722
2.90k
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
723
2.90k
    return std::make_unique<CastExpressionIdValidator>(*this);
724
2.90k
  }
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.7M
                                       bool *NotPrimaryExpression) {
918
38.7M
  ExprResult Res;
919
38.7M
  tok::TokenKind SavedKind = Tok.getKind();
920
38.7M
  auto SavedType = PreferredType;
921
38.7M
  NotCastExpr = false;
922
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.7M
  bool AllowSuffix = true;
927
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.7M
  switch (SavedKind) {
939
5.41M
  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.41M
    ParenParseOption ParenExprType;
943
5.41M
    switch (ParseKind) {
944
2.76k
      case CastParseKind::UnaryExprOnly:
945
2.76k
        if (!getLangOpts().CPlusPlus)
946
0
          ParenExprType = CompoundLiteral;
947
2.76k
        LLVM_FALLTHROUGH;
948
5.41M
      case CastParseKind::AnyCastExpr:
949
5.41M
        ParenExprType = ParenParseOption::CastExpr;
950
5.41M
        break;
951
144
      case CastParseKind::PrimaryExprOnly:
952
144
        ParenExprType = FoldExpr;
953
144
        break;
954
5.41M
    }
955
5.41M
    ParsedType CastTy;
956
5.41M
    SourceLocation RParenLoc;
957
5.41M
    Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
958
5.41M
                               isTypeCast == IsTypeCast, CastTy, RParenLoc);
959
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.41M
    if (isVectorLiteral)
964
164
      return Res;
965
966
5.41M
    switch (ParenExprType) {
967
1.01M
    case SimpleExpr:   break;    // Nothing else to do.
968
8.91k
    case CompoundStmt: break;  // Nothing else to do.
969
51.0k
    case CompoundLiteral:
970
      // We parsed '(' type-name ')' '{' ... '}'.  If any suffixes of
971
      // postfix-expression exist, parse them now.
972
51.0k
      break;
973
4.34M
    case CastExpr:
974
      // We have parsed the cast-expression and no postfix-expr pieces are
975
      // following.
976
4.34M
      return Res;
977
219
    case FoldExpr:
978
      // We only parsed a fold-expression. There might be postfix-expr pieces
979
      // afterwards; parse them now.
980
219
      break;
981
5.41M
    }
982
983
1.07M
    break;
984
5.41M
  }
985
986
    // primary-expression
987
7.54M
  case tok::numeric_constant:
988
    // constant: integer-constant
989
    // constant: floating-constant
990
991
7.54M
    Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
992
7.54M
    ConsumeToken();
993
7.54M
    break;
994
995
160k
  case tok::kw_true:
996
294k
  case tok::kw_false:
997
294k
    Res = ParseCXXBoolLiteral();
998
294k
    break;
999
1000
513
  case tok::kw___objc_yes:
1001
913
  case tok::kw___objc_no:
1002
913
    Res = ParseObjCBoolLiteral();
1003
913
    break;
1004
1005
91.8k
  case tok::kw_nullptr:
1006
91.8k
    Diag(Tok, diag::warn_cxx98_compat_nullptr);
1007
91.8k
    Res = Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
1008
91.8k
    break;
1009
1010
16
  case tok::annot_primary_expr:
1011
704k
  case tok::annot_overload_set:
1012
704k
    Res = getExprAnnotation(Tok);
1013
704k
    if (!Res.isInvalid() && Tok.getKind() == tok::annot_overload_set)
1014
704k
      Res = Actions.ActOnNameClassifiedAsOverloadSet(getCurScope(), Res.get());
1015
704k
    ConsumeAnnotationToken();
1016
704k
    if (!Res.isInvalid() && 
Tok.is(tok::less)704k
)
1017
22
      checkPotentialAngleBracket(Res);
1018
704k
    break;
1019
1020
1.91M
  case tok::annot_non_type:
1021
1.91M
  case tok::annot_non_type_dependent:
1022
1.91M
  case tok::annot_non_type_undeclared: {
1023
1.91M
    CXXScopeSpec SS;
1024
1.91M
    Token Replacement;
1025
1.91M
    Res = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
1026
1.91M
    assert(!Res.isUnset() &&
1027
1.91M
           "should not perform typo correction on annotation token");
1028
0
    break;
1029
1.91M
  }
1030
1031
3
  case tok::kw___super:
1032
206
  case tok::kw_decltype:
1033
    // Annotate the token and tail recurse.
1034
206
    if (TryAnnotateTypeOrScopeToken())
1035
0
      return ExprError();
1036
206
    assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
1037
0
    return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1038
206
                               isVectorLiteral, NotPrimaryExpression);
1039
1040
14.5M
  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
14.5M
    if (getLangOpts().CPlusPlus) {
1046
      // Avoid the unnecessary parse-time lookup in the common case
1047
      // where the syntax forbids a type.
1048
7.66M
      const Token &Next = NextToken();
1049
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
7.66M
      if (Next.is(tok::l_paren) &&
1054
7.66M
          
Tok.is(tok::identifier)1.05M
&&
1055
7.66M
          
Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()1.05M
) {
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
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
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
104
      }
1131
1132
7.66M
      if ((!ColonIsSacred && 
Next.is(tok::colon)7.29M
) ||
1133
7.66M
          Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
1134
7.66M
                       tok::l_brace)) {
1135
        // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1136
2.16M
        if (TryAnnotateTypeOrScopeToken())
1137
8
          return ExprError();
1138
2.16M
        if (!Tok.is(tok::identifier))
1139
1.12M
          return ParseCastExpression(ParseKind, isAddressOfOperand,
1140
1.12M
                                     NotCastExpr, isTypeCast,
1141
1.12M
                                     isVectorLiteral,
1142
1.12M
                                     NotPrimaryExpression);
1143
2.16M
      }
1144
7.66M
    }
1145
1146
    // Consume the identifier so that we can see if it is followed by a '(' or
1147
    // '.'.
1148
13.4M
    IdentifierInfo &II = *Tok.getIdentifierInfo();
1149
13.4M
    SourceLocation ILoc = ConsumeToken();
1150
1151
    // Support 'Class.property' and 'super.property' notation.
1152
13.4M
    if (getLangOpts().ObjC && 
Tok.is(tok::period)1.23M
&&
1153
13.4M
        
(33.8k
Actions.getTypeName(II, ILoc, getCurScope())33.8k
||
1154
         // Allow the base to be 'super' if in an objc-method.
1155
33.8k
         
(33.6k
&II == Ident_super33.6k
&&
getCurScope()->isInObjcMethodScope()79
))) {
1156
274
      ConsumeToken();
1157
1158
274
      if (Tok.is(tok::code_completion) && 
&II != Ident_super4
) {
1159
3
        cutOffParsing();
1160
3
        Actions.CodeCompleteObjCClassPropertyRefExpr(
1161
3
            getCurScope(), II, ILoc, ExprStatementTokLoc == ILoc);
1162
3
        return ExprError();
1163
3
      }
1164
      // Allow either an identifier or the keyword 'class' (in C++).
1165
271
      if (Tok.isNot(tok::identifier) &&
1166
271
          
!(2
getLangOpts().CPlusPlus2
&&
Tok.is(tok::kw_class)1
)) {
1167
1
        Diag(Tok, diag::err_expected_property_name);
1168
1
        return ExprError();
1169
1
      }
1170
270
      IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
1171
270
      SourceLocation PropertyLoc = ConsumeToken();
1172
1173
270
      Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
1174
270
                                              ILoc, PropertyLoc);
1175
270
      break;
1176
271
    }
1177
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
13.4M
    if (getLangOpts().ObjC && 
&II == Ident_super1.23M
&&
!InMessageExpression256
&&
1183
13.4M
        
getCurScope()->isInObjcMethodScope()34
&&
1184
13.4M
        
(31
(31
Tok.is(tok::identifier)31
&&
1185
31
         
(28
NextToken().is(tok::colon)28
||
NextToken().is(tok::r_square)2
)) ||
1186
31
         
Tok.is(tok::code_completion)3
)) {
1187
29
      Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
1188
29
                                           nullptr);
1189
29
      break;
1190
29
    }
1191
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
13.4M
    if (getLangOpts().ObjC &&
1198
13.4M
        
(1.23M
(1.23M
Tok.is(tok::identifier)1.23M
&&
!InMessageExpression11.4k
) ||
1199
1.23M
         
Tok.is(tok::code_completion)1.23M
)) {
1200
161
      const Token& Next = NextToken();
1201
161
      if (Tok.is(tok::code_completion) ||
1202
161
          
Next.is(tok::colon)118
||
Next.is(tok::r_square)115
)
1203
119
        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
1214
74
            Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
1215
74
            TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
1216
74
                                                  DeclaratorInfo);
1217
74
            if (Ty.isInvalid())
1218
0
              break;
1219
1220
74
            Res = ParseObjCMessageExpressionBody(SourceLocation(),
1221
74
                                                 SourceLocation(),
1222
74
                                                 Ty.get(), nullptr);
1223
74
            break;
1224
74
          }
1225
161
    }
1226
1227
    // Make sure to pass down the right value for isAddressOfOperand.
1228
13.4M
    if (isAddressOfOperand && 
isPostfixExpressionSuffixStart()113k
)
1229
30.7k
      isAddressOfOperand = false;
1230
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
13.4M
    UnqualifiedId Name;
1235
13.4M
    CXXScopeSpec ScopeSpec;
1236
13.4M
    SourceLocation TemplateKWLoc;
1237
13.4M
    Token Replacement;
1238
13.4M
    CastExpressionIdValidator Validator(
1239
13.4M
        /*Next=*/Tok,
1240
13.4M
        /*AllowTypes=*/isTypeCast != NotTypeCast,
1241
13.4M
        /*AllowNonTypes=*/isTypeCast != IsTypeCast);
1242
13.4M
    Validator.IsAddressOfOperand = isAddressOfOperand;
1243
13.4M
    if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
1244
122
      Validator.WantExpressionKeywords = false;
1245
122
      Validator.WantRemainingKeywords = false;
1246
13.4M
    } else {
1247
13.4M
      Validator.WantRemainingKeywords = Tok.isNot(tok::r_paren);
1248
13.4M
    }
1249
13.4M
    Name.setIdentifier(&II, ILoc);
1250
13.4M
    Res = Actions.ActOnIdExpression(
1251
13.4M
        getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
1252
13.4M
        isAddressOfOperand, &Validator,
1253
13.4M
        /*IsInlineAsmIdentifier=*/false,
1254
13.4M
        Tok.is(tok::r_paren) ? 
nullptr3.45M
:
&Replacement9.97M
);
1255
13.4M
    if (!Res.isInvalid() && 
Res.isUnset()13.4M
) {
1256
2
      UnconsumeToken(Replacement);
1257
2
      return ParseCastExpression(ParseKind, isAddressOfOperand,
1258
2
                                 NotCastExpr, isTypeCast,
1259
2
                                 /*isVectorLiteral=*/false,
1260
2
                                 NotPrimaryExpression);
1261
2
    }
1262
13.4M
    if (!Res.isInvalid() && 
Tok.is(tok::less)13.4M
)
1263
199k
      checkPotentialAngleBracket(Res);
1264
13.4M
    break;
1265
13.4M
  }
1266
547k
  case tok::char_constant:     // constant: character-constant
1267
548k
  case tok::wide_char_constant:
1268
548k
  case tok::utf8_char_constant:
1269
548k
  case tok::utf16_char_constant:
1270
548k
  case tok::utf32_char_constant:
1271
548k
    Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
1272
548k
    ConsumeToken();
1273
548k
    break;
1274
376
  case tok::kw___func__:       // primary-expression: __func__ [C99 6.4.2.2]
1275
573
  case tok::kw___FUNCTION__:   // primary-expression: __FUNCTION__ [GNU]
1276
582
  case tok::kw___FUNCDNAME__:   // primary-expression: __FUNCDNAME__ [MS]
1277
595
  case tok::kw___FUNCSIG__:     // primary-expression: __FUNCSIG__ [MS]
1278
603
  case tok::kw_L__FUNCTION__:   // primary-expression: L__FUNCTION__ [MS]
1279
609
  case tok::kw_L__FUNCSIG__:    // primary-expression: L__FUNCSIG__ [MS]
1280
808
  case tok::kw___PRETTY_FUNCTION__:  // primary-expression: __P..Y_F..N__ [GNU]
1281
808
    Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1282
808
    ConsumeToken();
1283
808
    break;
1284
3.09M
  case tok::string_literal:    // primary-expression: string-literal
1285
3.09M
  case tok::wide_string_literal:
1286
3.09M
  case tok::utf8_string_literal:
1287
3.09M
  case tok::utf16_string_literal:
1288
3.09M
  case tok::utf32_string_literal:
1289
3.09M
    Res = ParseStringLiteralExpression(true);
1290
3.09M
    break;
1291
188
  case tok::kw__Generic:   // primary-expression: generic-selection [C11 6.5.1]
1292
188
    Res = ParseGenericSelectionExpression();
1293
188
    break;
1294
15
  case tok::kw___builtin_available:
1295
15
    Res = ParseAvailabilityCheckExpr(Tok.getLocation());
1296
15
    break;
1297
1.07k
  case tok::kw___builtin_va_arg:
1298
1.42k
  case tok::kw___builtin_offsetof:
1299
1.48k
  case tok::kw___builtin_choose_expr:
1300
1.52k
  case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1301
21.3k
  case tok::kw___builtin_convertvector:
1302
21.3k
  case tok::kw___builtin_COLUMN:
1303
21.3k
  case tok::kw___builtin_FILE:
1304
21.3k
  case tok::kw___builtin_FUNCTION:
1305
21.4k
  case tok::kw___builtin_LINE:
1306
21.4k
    if (NotPrimaryExpression)
1307
0
      *NotPrimaryExpression = true;
1308
    // This parses the complete suffix; we can return early.
1309
21.4k
    return ParseBuiltinPrimaryExpression();
1310
4.57k
  case tok::kw___null:
1311
4.57k
    Res = Actions.ActOnGNUNullExpr(ConsumeToken());
1312
4.57k
    break;
1313
1314
294k
  case tok::plusplus:      // unary-expression: '++' unary-expression [C99]
1315
354k
  case tok::minusminus: {  // unary-expression: '--' unary-expression [C99]
1316
354k
    if (NotPrimaryExpression)
1317
0
      *NotPrimaryExpression = true;
1318
    // C++ [expr.unary] has:
1319
    //   unary-expression:
1320
    //     ++ cast-expression
1321
    //     -- cast-expression
1322
354k
    Token SavedTok = Tok;
1323
354k
    ConsumeToken();
1324
1325
354k
    PreferredType.enterUnary(Actions, Tok.getLocation(), SavedTok.getKind(),
1326
354k
                             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
354k
    Res = ParseCastExpression(getLangOpts().CPlusPlus ?
1331
345k
                                  UnaryExprOnly : 
AnyCastExpr9.50k
,
1332
354k
                              /*isAddressOfOperand*/false, NotCastExpr,
1333
354k
                              NotTypeCast);
1334
354k
    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
0
      UnconsumeToken(SavedTok);
1339
7
      return ExprError();
1340
7
    }
1341
354k
    if (!Res.isInvalid()) {
1342
354k
      Expr *Arg = Res.get();
1343
354k
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1344
354k
                                 SavedKind, Arg);
1345
354k
      if (Res.isInvalid())
1346
70
        Res = Actions.CreateRecoveryExpr(SavedTok.getLocation(),
1347
70
                                         Arg->getEndLoc(), Arg);
1348
354k
    }
1349
354k
    return Res;
1350
354k
  }
1351
126k
  case tok::amp: {         // unary-expression: '&' cast-expression
1352
126k
    if (NotPrimaryExpression)
1353
0
      *NotPrimaryExpression = true;
1354
    // Special treatment because of member pointers
1355
126k
    SourceLocation SavedLoc = ConsumeToken();
1356
126k
    PreferredType.enterUnary(Actions, Tok.getLocation(), tok::amp, SavedLoc);
1357
126k
    Res = ParseCastExpression(AnyCastExpr, true);
1358
126k
    if (!Res.isInvalid()) {
1359
126k
      Expr *Arg = Res.get();
1360
126k
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg);
1361
126k
      if (Res.isInvalid())
1362
205
        Res = Actions.CreateRecoveryExpr(Tok.getLocation(), Arg->getEndLoc(),
1363
205
                                         Arg);
1364
126k
    }
1365
126k
    return Res;
1366
354k
  }
1367
1368
530k
  case tok::star:          // unary-expression: '*' cast-expression
1369
531k
  case tok::plus:          // unary-expression: '+' cast-expression
1370
1.46M
  case tok::minus:         // unary-expression: '-' cast-expression
1371
1.53M
  case tok::tilde:         // unary-expression: '~' cast-expression
1372
1.68M
  case tok::exclaim:       // unary-expression: '!' cast-expression
1373
1.68M
  case tok::kw___real:     // unary-expression: '__real' cast-expression [GNU]
1374
1.68M
  case tok::kw___imag: {   // unary-expression: '__imag' cast-expression [GNU]
1375
1.68M
    if (NotPrimaryExpression)
1376
0
      *NotPrimaryExpression = true;
1377
1.68M
    SourceLocation SavedLoc = ConsumeToken();
1378
1.68M
    PreferredType.enterUnary(Actions, Tok.getLocation(), SavedKind, SavedLoc);
1379
1.68M
    Res = ParseCastExpression(AnyCastExpr);
1380
1.68M
    if (!Res.isInvalid()) {
1381
1.68M
      Expr *Arg = Res.get();
1382
1.68M
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg);
1383
1.68M
      if (Res.isInvalid())
1384
192
        Res = Actions.CreateRecoveryExpr(SavedLoc, Arg->getEndLoc(), Arg);
1385
1.68M
    }
1386
1.68M
    return Res;
1387
1.68M
  }
1388
1389
468
  case tok::kw_co_await: {  // unary-expression: 'co_await' cast-expression
1390
468
    if (NotPrimaryExpression)
1391
0
      *NotPrimaryExpression = true;
1392
468
    SourceLocation CoawaitLoc = ConsumeToken();
1393
468
    Res = ParseCastExpression(AnyCastExpr);
1394
468
    if (!Res.isInvalid())
1395
468
      Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1396
468
    return Res;
1397
1.68M
  }
1398
1399
30.5k
  case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1400
    // __extension__ silences extension warnings in the subexpression.
1401
30.5k
    if (NotPrimaryExpression)
1402
0
      *NotPrimaryExpression = true;
1403
30.5k
    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1404
30.5k
    SourceLocation SavedLoc = ConsumeToken();
1405
30.5k
    Res = ParseCastExpression(AnyCastExpr);
1406
30.5k
    if (!Res.isInvalid())
1407
30.5k
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1408
30.5k
    return Res;
1409
1.68M
  }
1410
92
  case tok::kw__Alignof:   // unary-expression: '_Alignof' '(' type-name ')'
1411
92
    if (!getLangOpts().C11)
1412
26
      Diag(Tok, diag::ext_c11_feature) << Tok.getName();
1413
92
    LLVM_FALLTHROUGH;
1414
6.43k
  case tok::kw_alignof:    // unary-expression: 'alignof' '(' type-id ')'
1415
9.39k
  case tok::kw___alignof:  // unary-expression: '__alignof' unary-expression
1416
                           // unary-expression: '__alignof' '(' type-name ')'
1417
137k
  case tok::kw_sizeof:     // unary-expression: 'sizeof' unary-expression
1418
                           // unary-expression: 'sizeof' '(' type-name ')'
1419
137k
  case tok::kw_vec_step:   // unary-expression: OpenCL 'vec_step' expression
1420
  // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1421
137k
  case tok::kw___builtin_omp_required_simd_align:
1422
137k
    if (NotPrimaryExpression)
1423
4
      *NotPrimaryExpression = true;
1424
137k
    AllowSuffix = false;
1425
137k
    Res = ParseUnaryExprOrTypeTraitExpression();
1426
137k
    break;
1427
321
  case tok::ampamp: {      // unary-expression: '&&' identifier
1428
321
    if (NotPrimaryExpression)
1429
0
      *NotPrimaryExpression = true;
1430
321
    SourceLocation AmpAmpLoc = ConsumeToken();
1431
321
    if (Tok.isNot(tok::identifier))
1432
0
      return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1433
1434
321
    if (getCurScope()->getFnParent() == nullptr)
1435
1
      return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1436
1437
320
    Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1438
320
    LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1439
320
                                                Tok.getLocation());
1440
320
    Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1441
320
    ConsumeToken();
1442
320
    AllowSuffix = false;
1443
320
    break;
1444
321
  }
1445
5.36k
  case tok::kw_const_cast:
1446
6.65k
  case tok::kw_dynamic_cast:
1447
15.2k
  case tok::kw_reinterpret_cast:
1448
158k
  case tok::kw_static_cast:
1449
158k
  case tok::kw_addrspace_cast:
1450
158k
    if (NotPrimaryExpression)
1451
0
      *NotPrimaryExpression = true;
1452
158k
    Res = ParseCXXCasts();
1453
158k
    break;
1454
663
  case tok::kw___builtin_bit_cast:
1455
663
    if (NotPrimaryExpression)
1456
0
      *NotPrimaryExpression = true;
1457
663
    Res = ParseBuiltinBitCast();
1458
663
    break;
1459
5.72k
  case tok::kw_typeid:
1460
5.72k
    if (NotPrimaryExpression)
1461
0
      *NotPrimaryExpression = true;
1462
5.72k
    Res = ParseCXXTypeid();
1463
5.72k
    break;
1464
178
  case tok::kw___uuidof:
1465
178
    if (NotPrimaryExpression)
1466
0
      *NotPrimaryExpression = true;
1467
178
    Res = ParseCXXUuidof();
1468
178
    break;
1469
214k
  case tok::kw_this:
1470
214k
    Res = ParseCXXThis();
1471
214k
    break;
1472
74
  case tok::kw___builtin_sycl_unique_stable_name:
1473
74
    Res = ParseSYCLUniqueStableNameExpression();
1474
74
    break;
1475
1476
304k
  case tok::annot_typename:
1477
304k
    if (isStartOfObjCClassMessageMissingOpenBracket()) {
1478
81
      TypeResult Type = getTypeAnnotation(Tok);
1479
1480
      // Fake up a Declarator to use with ActOnTypeName.
1481
81
      DeclSpec DS(AttrFactory);
1482
81
      DS.SetRangeStart(Tok.getLocation());
1483
81
      DS.SetRangeEnd(Tok.getLastLoc());
1484
1485
81
      const char *PrevSpec = nullptr;
1486
81
      unsigned DiagID;
1487
81
      DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1488
81
                         PrevSpec, DiagID, Type,
1489
81
                         Actions.getASTContext().getPrintingPolicy());
1490
1491
81
      Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
1492
81
      TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1493
81
      if (Ty.isInvalid())
1494
0
        break;
1495
1496
81
      ConsumeAnnotationToken();
1497
81
      Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1498
81
                                           Ty.get(), nullptr);
1499
81
      break;
1500
81
    }
1501
304k
    
LLVM_FALLTHROUGH304k
;304k
1502
1503
304k
  case tok::annot_decltype:
1504
305k
  case tok::kw_char:
1505
305k
  case tok::kw_wchar_t:
1506
305k
  case tok::kw_char8_t:
1507
305k
  case tok::kw_char16_t:
1508
305k
  case tok::kw_char32_t:
1509
309k
  case tok::kw_bool:
1510
309k
  case tok::kw_short:
1511
310k
  case tok::kw_int:
1512
310k
  case tok::kw_long:
1513
310k
  case tok::kw___int64:
1514
310k
  case tok::kw___int128:
1515
310k
  case tok::kw__ExtInt:
1516
310k
  case tok::kw__BitInt:
1517
310k
  case tok::kw_signed:
1518
310k
  case tok::kw_unsigned:
1519
310k
  case tok::kw_half:
1520
310k
  case tok::kw_float:
1521
310k
  case tok::kw_double:
1522
310k
  case tok::kw___bf16:
1523
310k
  case tok::kw__Float16:
1524
310k
  case tok::kw___float128:
1525
310k
  case tok::kw___ibm128:
1526
311k
  case tok::kw_void:
1527
338k
  case tok::kw_typename:
1528
338k
  case tok::kw_typeof:
1529
338k
  case tok::kw___vector:
1530
4.06M
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1531
4.06M
#include 
"clang/Basic/OpenCLImageTypes.def"338k
1532
4.06M
  {
1533
4.06M
    if (
!getLangOpts().CPlusPlus338k
) {
1534
296
      Diag(Tok, diag::err_expected_expression);
1535
296
      return ExprError();
1536
296
    }
1537
1538
    // Everything henceforth is a postfix-expression.
1539
338k
    if (NotPrimaryExpression)
1540
4
      *NotPrimaryExpression = true;
1541
1542
338k
    if (SavedKind == tok::kw_typename) {
1543
      // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1544
      //                     typename-specifier braced-init-list
1545
26.5k
      if (TryAnnotateTypeOrScopeToken())
1546
7
        return ExprError();
1547
1548
26.5k
      if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1549
        // We are trying to parse a simple-type-specifier but might not get such
1550
        // a token after error recovery.
1551
0
        return ExprError();
1552
26.5k
    }
1553
1554
    // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1555
    //                     simple-type-specifier braced-init-list
1556
    //
1557
338k
    DeclSpec DS(AttrFactory);
1558
1559
338k
    ParseCXXSimpleTypeSpecifier(DS);
1560
338k
    if (Tok.isNot(tok::l_paren) &&
1561
338k
        
(6.76k
!getLangOpts().CPlusPlus116.76k
||
Tok.isNot(tok::l_brace)6.75k
))
1562
50
      return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1563
50
                         << DS.getSourceRange());
1564
1565
338k
    if (Tok.is(tok::l_brace))
1566
6.71k
      Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1567
1568
338k
    Res = ParseCXXTypeConstructExpression(DS);
1569
338k
    break;
1570
338k
  }
1571
1572
1.16M
  case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1573
    // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1574
    // (We can end up in this situation after tentative parsing.)
1575
1.16M
    if (TryAnnotateTypeOrScopeToken())
1576
0
      return ExprError();
1577
1.16M
    if (!Tok.is(tok::annot_cxxscope))
1578
4
      return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1579
4
                                 isTypeCast, isVectorLiteral,
1580
4
                                 NotPrimaryExpression);
1581
1582
1.16M
    Token Next = NextToken();
1583
1.16M
    if (Next.is(tok::annot_template_id)) {
1584
128k
      TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1585
128k
      if (TemplateId->Kind == TNK_Type_template) {
1586
        // We have a qualified template-id that we know refers to a
1587
        // type, translate it into a type and continue parsing as a
1588
        // cast expression.
1589
0
        CXXScopeSpec SS;
1590
0
        ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1591
0
                                       /*ObjectHasErrors=*/false,
1592
0
                                       /*EnteringContext=*/false);
1593
0
        AnnotateTemplateIdTokenAsType(SS);
1594
0
        return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1595
0
                                   isTypeCast, isVectorLiteral,
1596
0
                                   NotPrimaryExpression);
1597
0
      }
1598
128k
    }
1599
1600
    // Parse as an id-expression.
1601
1.16M
    Res = ParseCXXIdExpression(isAddressOfOperand);
1602
1.16M
    break;
1603
1.16M
  }
1604
1605
86.9k
  case tok::annot_template_id: { // [C++]          template-id
1606
86.9k
    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1607
86.9k
    if (TemplateId->Kind == TNK_Type_template) {
1608
      // We have a template-id that we know refers to a type,
1609
      // translate it into a type and continue parsing as a cast
1610
      // expression.
1611
49
      CXXScopeSpec SS;
1612
49
      AnnotateTemplateIdTokenAsType(SS);
1613
49
      return ParseCastExpression(ParseKind, isAddressOfOperand,
1614
49
                                 NotCastExpr, isTypeCast, isVectorLiteral,
1615
49
                                 NotPrimaryExpression);
1616
49
    }
1617
1618
    // Fall through to treat the template-id as an id-expression.
1619
86.9k
    
LLVM_FALLTHROUGH86.9k
;
1620
86.9k
  }
1621
1622
89.0k
  case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1623
89.0k
    Res = ParseCXXIdExpression(isAddressOfOperand);
1624
89.0k
    break;
1625
1626
87.9k
  case tok::coloncolon: {
1627
    // ::foo::bar -> global qualified name etc.   If TryAnnotateTypeOrScopeToken
1628
    // annotates the token, tail recurse.
1629
87.9k
    if (TryAnnotateTypeOrScopeToken())
1630
4
      return ExprError();
1631
87.9k
    if (!Tok.is(tok::coloncolon))
1632
69.9k
      return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1633
69.9k
                                 isVectorLiteral, NotPrimaryExpression);
1634
1635
    // ::new -> [C++] new-expression
1636
    // ::delete -> [C++] delete-expression
1637
17.9k
    SourceLocation CCLoc = ConsumeToken();
1638
17.9k
    if (Tok.is(tok::kw_new)) {
1639
17.8k
      if (NotPrimaryExpression)
1640
0
        *NotPrimaryExpression = true;
1641
17.8k
      Res = ParseCXXNewExpression(true, CCLoc);
1642
17.8k
      AllowSuffix = false;
1643
17.8k
      break;
1644
17.8k
    }
1645
52
    if (Tok.is(tok::kw_delete)) {
1646
52
      if (NotPrimaryExpression)
1647
0
        *NotPrimaryExpression = true;
1648
52
      Res = ParseCXXDeleteExpression(true, CCLoc);
1649
52
      AllowSuffix = false;
1650
52
      break;
1651
52
    }
1652
1653
    // This is not a type name or scope specifier, it is an invalid expression.
1654
0
    Diag(CCLoc, diag::err_expected_expression);
1655
0
    return ExprError();
1656
52
  }
1657
1658
8.93k
  case tok::kw_new: // [C++] new-expression
1659
8.93k
    if (NotPrimaryExpression)
1660
0
      *NotPrimaryExpression = true;
1661
8.93k
    Res = ParseCXXNewExpression(false, Tok.getLocation());
1662
8.93k
    AllowSuffix = false;
1663
8.93k
    break;
1664
1665
5.18k
  case tok::kw_delete: // [C++] delete-expression
1666
5.18k
    if (NotPrimaryExpression)
1667
0
      *NotPrimaryExpression = true;
1668
5.18k
    Res = ParseCXXDeleteExpression(false, Tok.getLocation());
1669
5.18k
    AllowSuffix = false;
1670
5.18k
    break;
1671
1672
249
  case tok::kw_requires: // [C++2a] requires-expression
1673
249
    Res = ParseRequiresExpression();
1674
249
    AllowSuffix = false;
1675
249
    break;
1676
1677
11.9k
  case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1678
11.9k
    if (NotPrimaryExpression)
1679
0
      *NotPrimaryExpression = true;
1680
11.9k
    Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1681
11.9k
    SourceLocation KeyLoc = ConsumeToken();
1682
11.9k
    BalancedDelimiterTracker T(*this, tok::l_paren);
1683
1684
11.9k
    if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1685
0
      return ExprError();
1686
    // C++11 [expr.unary.noexcept]p1:
1687
    //   The noexcept operator determines whether the evaluation of its operand,
1688
    //   which is an unevaluated operand, can throw an exception.
1689
11.9k
    EnterExpressionEvaluationContext Unevaluated(
1690
11.9k
        Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1691
11.9k
    Res = ParseExpression();
1692
1693
11.9k
    T.consumeClose();
1694
1695
11.9k
    if (!Res.isInvalid())
1696
11.9k
      Res = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), Res.get(),
1697
11.9k
                                      T.getCloseLocation());
1698
11.9k
    AllowSuffix = false;
1699
11.9k
    break;
1700
11.9k
  }
1701
1702
0
#define TYPE_TRAIT(N,Spelling,K) \
1703
743k
  case tok::kw_##Spelling:
1704
28.0k
#include 
"clang/Basic/TokenKinds.def"11.9k
1705
28.0k
    Res = ParseTypeTrait();
1706
28.0k
    break;
1707
1708
10
  case tok::kw___array_rank:
1709
503
  case tok::kw___array_extent:
1710
503
    if (NotPrimaryExpression)
1711
0
      *NotPrimaryExpression = true;
1712
503
    Res = ParseArrayTypeTrait();
1713
503
    break;
1714
1715
224
  case tok::kw___is_lvalue_expr:
1716
439
  case tok::kw___is_rvalue_expr:
1717
439
    if (NotPrimaryExpression)
1718
0
      *NotPrimaryExpression = true;
1719
439
    Res = ParseExpressionTrait();
1720
439
    break;
1721
1722
8.46k
  case tok::at: {
1723
8.46k
    if (NotPrimaryExpression)
1724
0
      *NotPrimaryExpression = true;
1725
8.46k
    SourceLocation AtLoc = ConsumeToken();
1726
8.46k
    return ParseObjCAtExpression(AtLoc);
1727
224
  }
1728
3.05k
  case tok::caret:
1729
3.05k
    Res = ParseBlockLiteralExpression();
1730
3.05k
    break;
1731
98
  case tok::code_completion: {
1732
98
    cutOffParsing();
1733
98
    Actions.CodeCompleteExpression(getCurScope(),
1734
98
                                   PreferredType.get(Tok.getLocation()));
1735
98
    return ExprError();
1736
224
  }
1737
30.7k
  case tok::l_square:
1738
30.7k
    if (getLangOpts().CPlusPlus11) {
1739
10.9k
      if (getLangOpts().ObjC) {
1740
        // C++11 lambda expressions and Objective-C message sends both start with a
1741
        // square bracket.  There are three possibilities here:
1742
        // we have a valid lambda expression, we have an invalid lambda
1743
        // expression, or we have something that doesn't appear to be a lambda.
1744
        // If we're in the last case, we fall back to ParseObjCMessageExpression.
1745
2.96k
        Res = TryParseLambdaExpression();
1746
2.96k
        if (!Res.isInvalid() && 
!Res.get()2.95k
) {
1747
          // We assume Objective-C++ message expressions are not
1748
          // primary-expressions.
1749
2.75k
          if (NotPrimaryExpression)
1750
0
            *NotPrimaryExpression = true;
1751
2.75k
          Res = ParseObjCMessageExpression();
1752
2.75k
        }
1753
2.96k
        break;
1754
2.96k
      }
1755
7.98k
      Res = ParseLambdaExpression();
1756
7.98k
      break;
1757
10.9k
    }
1758
19.7k
    if (getLangOpts().ObjC) {
1759
19.7k
      Res = ParseObjCMessageExpression();
1760
19.7k
      break;
1761
19.7k
    }
1762
19.7k
    
LLVM_FALLTHROUGH13
;13
1763
15.4k
  default:
1764
15.4k
    NotCastExpr = true;
1765
15.4k
    return ExprError();
1766
38.7M
  }
1767
1768
  // Check to see whether Res is a function designator only. If it is and we
1769
  // are compiling for OpenCL, we need to return an error as this implies
1770
  // that the address of the function is being taken, which is illegal in CL.
1771
1772
30.9M
  if (ParseKind == PrimaryExprOnly)
1773
    // This is strictly a primary-expression - no postfix-expr pieces should be
1774
    // parsed.
1775
525
    return Res;
1776
1777
30.9M
  if (!AllowSuffix) {
1778
    // FIXME: Don't parse a primary-expression suffix if we encountered a parse
1779
    // error already.
1780
181k
    if (Res.isInvalid())
1781
740
      return Res;
1782
1783
181k
    switch (Tok.getKind()) {
1784
5
    case tok::l_square:
1785
6
    case tok::l_paren:
1786
6
    case tok::plusplus:
1787
6
    case tok::minusminus:
1788
      // "expected ';'" or similar is probably the right diagnostic here. Let
1789
      // the caller decide what to do.
1790
6
      if (Tok.isAtStartOfLine())
1791
1
        return Res;
1792
1793
6
      
LLVM_FALLTHROUGH5
;5
1794
5
    case tok::period:
1795
7
    case tok::arrow:
1796
7
      break;
1797
1798
181k
    default:
1799
181k
      return Res;
1800
181k
    }
1801
1802
    // This was a unary-expression for which a postfix-expression suffix is
1803
    // not permitted by the grammar (eg, a sizeof expression or
1804
    // new-expression or similar). Diagnose but parse the suffix anyway.
1805
7
    Diag(Tok.getLocation(), diag::err_postfix_after_unary_requires_parens)
1806
7
        << Tok.getKind() << Res.get()->getSourceRange()
1807
7
        << FixItHint::CreateInsertion(Res.get()->getBeginLoc(), "(")
1808
7
        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(PrevTokLocation),
1809
7
                                      ")");
1810
7
  }
1811
1812
  // These can be followed by postfix-expr pieces.
1813
30.7M
  PreferredType = SavedType;
1814
30.7M
  Res = ParsePostfixExpressionSuffix(Res);
1815
30.7M
  if (getLangOpts().OpenCL &&
1816
30.7M
      !getActions().getOpenCLOptions().isAvailableOption(
1817
84.2k
          "__cl_clang_function_pointers", getLangOpts()))
1818
84.2k
    if (Expr *PostfixExpr = Res.get()) {
1819
84.1k
      QualType Ty = PostfixExpr->getType();
1820
84.1k
      if (!Ty.isNull() && 
Ty->isFunctionType()83.8k
) {
1821
10
        Diag(PostfixExpr->getExprLoc(),
1822
10
             diag::err_opencl_taking_function_address_parser);
1823
10
        return ExprError();
1824
10
      }
1825
84.1k
    }
1826
1827
30.7M
  return Res;
1828
30.7M
}
1829
1830
/// Once the leading part of a postfix-expression is parsed, this
1831
/// method parses any suffixes that apply.
1832
///
1833
/// \verbatim
1834
///       postfix-expression: [C99 6.5.2]
1835
///         primary-expression
1836
///         postfix-expression '[' expression ']'
1837
///         postfix-expression '[' braced-init-list ']'
1838
///         postfix-expression '(' argument-expression-list[opt] ')'
1839
///         postfix-expression '.' identifier
1840
///         postfix-expression '->' identifier
1841
///         postfix-expression '++'
1842
///         postfix-expression '--'
1843
///         '(' type-name ')' '{' initializer-list '}'
1844
///         '(' type-name ')' '{' initializer-list ',' '}'
1845
///
1846
///       argument-expression-list: [C99 6.5.2]
1847
///         argument-expression ...[opt]
1848
///         argument-expression-list ',' assignment-expression ...[opt]
1849
/// \endverbatim
1850
ExprResult
1851
30.7M
Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1852
  // Now that the primary-expression piece of the postfix-expression has been
1853
  // parsed, see if there are any postfix-expression pieces here.
1854
30.7M
  SourceLocation Loc;
1855
30.7M
  auto SavedType = PreferredType;
1856
37.1M
  while (true) {
1857
    // Each iteration relies on preferred type for the whole expression.
1858
37.1M
    PreferredType = SavedType;
1859
37.1M
    switch (Tok.getKind()) {
1860
69
    case tok::code_completion:
1861
69
      if (InMessageExpression)
1862
58
        return LHS;
1863
1864
11
      cutOffParsing();
1865
11
      Actions.CodeCompletePostfixExpression(
1866
11
          getCurScope(), LHS, PreferredType.get(Tok.getLocation()));
1867
11
      return ExprError();
1868
1869
20.6k
    case tok::identifier:
1870
      // If we see identifier: after an expression, and we're not already in a
1871
      // message send, then this is probably a message send with a missing
1872
      // opening bracket '['.
1873
20.6k
      if (getLangOpts().ObjC && 
!InMessageExpression18.8k
&&
1874
20.6k
          
(282
NextToken().is(tok::colon)282
||
NextToken().is(tok::r_square)196
)) {
1875
174
        LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1876
174
                                             nullptr, LHS.get());
1877
174
        break;
1878
174
      }
1879
      // Fall through; this isn't a message send.
1880
20.6k
      
LLVM_FALLTHROUGH20.4k
;20.4k
1881
1882
30.7M
    default:  // Not a postfix-expression suffix.
1883
30.7M
      return LHS;
1884
272k
    case tok::l_square: {  // postfix-expression: p-e '[' expression ']'
1885
      // If we have a array postfix expression that starts on a new line and
1886
      // Objective-C is enabled, it is highly likely that the user forgot a
1887
      // semicolon after the base expression and that the array postfix-expr is
1888
      // actually another message send.  In this case, do some look-ahead to see
1889
      // if the contents of the square brackets are obviously not a valid
1890
      // expression and recover by pretending there is no suffix.
1891
272k
      if (getLangOpts().ObjC && 
Tok.isAtStartOfLine()58.8k
&&
1892
272k
          
isSimpleObjCMessageExpression()5
)
1893
4
        return LHS;
1894
1895
      // Reject array indices starting with a lambda-expression. '[[' is
1896
      // reserved for attributes.
1897
272k
      if (CheckProhibitedCXX11Attribute()) {
1898
2
        (void)Actions.CorrectDelayedTyposInExpr(LHS);
1899
2
        return ExprError();
1900
2
      }
1901
1902
272k
      BalancedDelimiterTracker T(*this, tok::l_square);
1903
272k
      T.consumeOpen();
1904
272k
      Loc = T.getOpenLocation();
1905
272k
      ExprResult Idx, Length, Stride;
1906
272k
      SourceLocation ColonLocFirst, ColonLocSecond;
1907
272k
      PreferredType.enterSubscript(Actions, Tok.getLocation(), LHS.get());
1908
272k
      if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)182k
) {
1909
4
        Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1910
4
        Idx = ParseBraceInitializer();
1911
272k
      } else if (getLangOpts().OpenMP) {
1912
104k
        ColonProtectionRAIIObject RAII(*this);
1913
        // Parse [: or [ expr or [ expr :
1914
104k
        if (!Tok.is(tok::colon)) {
1915
          // [ expr
1916
97.2k
          Idx = ParseExpression();
1917
97.2k
        }
1918
104k
        if (Tok.is(tok::colon)) {
1919
          // Consume ':'
1920
12.2k
          ColonLocFirst = ConsumeToken();
1921
12.2k
          if (Tok.isNot(tok::r_square) &&
1922
12.2k
              
(9.33k
getLangOpts().OpenMP < 509.33k
||
1923
9.33k
               
((6.55k
Tok.isNot(tok::colon)6.55k
&&
getLangOpts().OpenMP >= 506.53k
))))
1924
9.31k
            Length = ParseExpression();
1925
12.2k
        }
1926
104k
        if (getLangOpts().OpenMP >= 50 &&
1927
104k
            
(83.9k
OMPClauseKind == llvm::omp::Clause::OMPC_to83.9k
||
1928
83.9k
             
OMPClauseKind == llvm::omp::Clause::OMPC_from83.1k
) &&
1929
104k
            
Tok.is(tok::colon)1.49k
) {
1930
          // Consume ':'
1931
208
          ColonLocSecond = ConsumeToken();
1932
208
          if (Tok.isNot(tok::r_square)) {
1933
160
            Stride = ParseExpression();
1934
160
          }
1935
208
        }
1936
104k
      } else
1937
167k
        Idx = ParseExpression();
1938
1939
272k
      SourceLocation RLoc = Tok.getLocation();
1940
1941
272k
      LHS = Actions.CorrectDelayedTyposInExpr(LHS);
1942
272k
      Idx = Actions.CorrectDelayedTyposInExpr(Idx);
1943
272k
      Length = Actions.CorrectDelayedTyposInExpr(Length);
1944
272k
      if (!LHS.isInvalid() && 
!Idx.isInvalid()271k
&&
!Length.isInvalid()271k
&&
1945
272k
          
!Stride.isInvalid()271k
&&
Tok.is(tok::r_square)271k
) {
1946
271k
        if (ColonLocFirst.isValid() || 
ColonLocSecond.isValid()259k
) {
1947
11.7k
          LHS = Actions.ActOnOMPArraySectionExpr(
1948
11.7k
              LHS.get(), Loc, Idx.get(), ColonLocFirst, ColonLocSecond,
1949
11.7k
              Length.get(), Stride.get(), RLoc);
1950
259k
        } else {
1951
259k
          LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1952
259k
                                                Idx.get(), RLoc);
1953
259k
        }
1954
271k
      } else {
1955
647
        LHS = ExprError();
1956
647
        Idx = ExprError();
1957
647
      }
1958
1959
      // Match the ']'.
1960
272k
      T.consumeClose();
1961
272k
      break;
1962
272k
    }
1963
1964
4.82M
    case tok::l_paren:         // p-e: p-e '(' argument-expression-list[opt] ')'
1965
4.82M
    case tok::lesslessless: {  // p-e: p-e '<<<' argument-expression-list '>>>'
1966
                               //   '(' argument-expression-list[opt] ')'
1967
4.82M
      tok::TokenKind OpKind = Tok.getKind();
1968
4.82M
      InMessageExpressionRAIIObject InMessage(*this, false);
1969
1970
4.82M
      Expr *ExecConfig = nullptr;
1971
1972
4.82M
      BalancedDelimiterTracker PT(*this, tok::l_paren);
1973
1974
4.82M
      if (OpKind == tok::lesslessless) {
1975
164
        ExprVector ExecConfigExprs;
1976
164
        CommaLocsTy ExecConfigCommaLocs;
1977
164
        SourceLocation OpenLoc = ConsumeToken();
1978
1979
164
        if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1980
1
          (void)Actions.CorrectDelayedTyposInExpr(LHS);
1981
1
          LHS = ExprError();
1982
1
        }
1983
1984
164
        SourceLocation CloseLoc;
1985
164
        if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1986
163
        } else 
if (1
LHS.isInvalid()1
) {
1987
0
          SkipUntil(tok::greatergreatergreater, StopAtSemi);
1988
1
        } else {
1989
          // There was an error closing the brackets
1990
1
          Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1991
1
          Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1992
1
          SkipUntil(tok::greatergreatergreater, StopAtSemi);
1993
1
          LHS = ExprError();
1994
1
        }
1995
1996
164
        if (!LHS.isInvalid()) {
1997
160
          if (ExpectAndConsume(tok::l_paren))
1998
1
            LHS = ExprError();
1999
159
          else
2000
159
            Loc = PrevTokLocation;
2001
160
        }
2002
2003
164
        if (!LHS.isInvalid()) {
2004
159
          ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
2005
159
                                    OpenLoc,
2006
159
                                    ExecConfigExprs,
2007
159
                                    CloseLoc);
2008
159
          if (ECResult.isInvalid())
2009
2
            LHS = ExprError();
2010
157
          else
2011
157
            ExecConfig = ECResult.get();
2012
159
        }
2013
4.82M
      } else {
2014
4.82M
        PT.consumeOpen();
2015
4.82M
        Loc = PT.getOpenLocation();
2016
4.82M
      }
2017
2018
4.82M
      ExprVector ArgExprs;
2019
4.82M
      CommaLocsTy CommaLocs;
2020
4.82M
      auto RunSignatureHelp = [&]() -> QualType {
2021
188
        QualType PreferredType = Actions.ProduceCallSignatureHelp(
2022
188
            LHS.get(), ArgExprs, PT.getOpenLocation());
2023
188
        CalledSignatureHelp = true;
2024
188
        return PreferredType;
2025
188
      };
2026
4.82M
      if (OpKind == tok::l_paren || 
!LHS.isInvalid()164
) {
2027
4.82M
        if (Tok.isNot(tok::r_paren)) {
2028
8.71M
          if (
ParseExpressionList(ArgExprs, CommaLocs, [&] 3.68M
{
2029
8.71M
                PreferredType.enterFunctionArgument(Tok.getLocation(),
2030
8.71M
                                                    RunSignatureHelp);
2031
8.71M
              })) {
2032
3.36k
            (void)Actions.CorrectDelayedTyposInExpr(LHS);
2033
            // If we got an error when parsing expression list, we don't call
2034
            // the CodeCompleteCall handler inside the parser. So call it here
2035
            // to make sure we get overload suggestions even when we are in the
2036
            // middle of a parameter.
2037
3.36k
            if (PP.isCodeCompletionReached() && 
!CalledSignatureHelp183
)
2038
4
              RunSignatureHelp();
2039
3.36k
            LHS = ExprError();
2040
3.67M
          } else if (LHS.isInvalid()) {
2041
205
            for (auto &E : ArgExprs)
2042
272
              Actions.CorrectDelayedTyposInExpr(E);
2043
205
          }
2044
3.68M
        }
2045
4.82M
      }
2046
2047
      // Match the ')'.
2048
4.82M
      if (LHS.isInvalid()) {
2049
3.80k
        SkipUntil(tok::r_paren, StopAtSemi);
2050
4.82M
      } else if (Tok.isNot(tok::r_paren)) {
2051
1.14k
        bool HadDelayedTypo = false;
2052
1.14k
        if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
2053
0
          HadDelayedTypo = true;
2054
1.14k
        for (auto &E : ArgExprs)
2055
1.14k
          if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
2056
11
            HadDelayedTypo = true;
2057
        // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
2058
        // instead of PT.consumeClose() to avoid emitting extra diagnostics for
2059
        // the unmatched l_paren.
2060
1.14k
        if (HadDelayedTypo)
2061
11
          SkipUntil(tok::r_paren, StopAtSemi);
2062
1.13k
        else
2063
1.13k
          PT.consumeClose();
2064
1.14k
        LHS = ExprError();
2065
4.82M
      } else {
2066
4.82M
        assert(
2067
4.82M
            (ArgExprs.size() == 0 || ArgExprs.size() - 1 == CommaLocs.size()) &&
2068
4.82M
            "Unexpected number of commas!");
2069
0
        Expr *Fn = LHS.get();
2070
4.82M
        SourceLocation RParLoc = Tok.getLocation();
2071
4.82M
        LHS = Actions.ActOnCallExpr(getCurScope(), Fn, Loc, ArgExprs, RParLoc,
2072
4.82M
                                    ExecConfig);
2073
4.82M
        if (LHS.isInvalid()) {
2074
4.23k
          ArgExprs.insert(ArgExprs.begin(), Fn);
2075
4.23k
          LHS =
2076
4.23k
              Actions.CreateRecoveryExpr(Fn->getBeginLoc(), RParLoc, ArgExprs);
2077
4.23k
        }
2078
4.82M
        PT.consumeClose();
2079
4.82M
      }
2080
2081
0
      break;
2082
4.82M
    }
2083
324k
    case tok::arrow:
2084
1.23M
    case tok::period: {
2085
      // postfix-expression: p-e '->' template[opt] id-expression
2086
      // postfix-expression: p-e '.' template[opt] id-expression
2087
1.23M
      tok::TokenKind OpKind = Tok.getKind();
2088
1.23M
      SourceLocation OpLoc = ConsumeToken();  // Eat the "." or "->" token.
2089
2090
1.23M
      CXXScopeSpec SS;
2091
1.23M
      ParsedType ObjectType;
2092
1.23M
      bool MayBePseudoDestructor = false;
2093
1.23M
      Expr* OrigLHS = !LHS.isInvalid() ? 
LHS.get()1.23M
:
nullptr452
;
2094
2095
1.23M
      PreferredType.enterMemAccess(Actions, Tok.getLocation(), OrigLHS);
2096
2097
1.23M
      if (getLangOpts().CPlusPlus && 
!LHS.isInvalid()1.11M
) {
2098
1.11M
        Expr *Base = OrigLHS;
2099
1.11M
        const Type* BaseType = Base->getType().getTypePtrOrNull();
2100
1.11M
        if (BaseType && 
Tok.is(tok::l_paren)1.11M
&&
2101
1.11M
            
(13
BaseType->isFunctionType()13
||
2102
13
             
BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember)8
)) {
2103
10
          Diag(OpLoc, diag::err_function_is_not_record)
2104
10
              << OpKind << Base->getSourceRange()
2105
10
              << FixItHint::CreateRemoval(OpLoc);
2106
10
          return ParsePostfixExpressionSuffix(Base);
2107
10
        }
2108
2109
1.11M
        LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base, OpLoc,
2110
1.11M
                                                   OpKind, ObjectType,
2111
1.11M
                                                   MayBePseudoDestructor);
2112
1.11M
        if (LHS.isInvalid()) {
2113
          // Clang will try to perform expression based completion as a
2114
          // fallback, which is confusing in case of member references. So we
2115
          // stop here without any completions.
2116
175
          if (Tok.is(tok::code_completion)) {
2117
0
            cutOffParsing();
2118
0
            return ExprError();
2119
0
          }
2120
175
          break;
2121
175
        }
2122
1.11M
        ParseOptionalCXXScopeSpecifier(
2123
1.11M
            SS, ObjectType, LHS.get() && LHS.get()->containsErrors(),
2124
1.11M
            /*EnteringContext=*/false, &MayBePseudoDestructor);
2125
1.11M
        if (SS.isNotEmpty())
2126
706
          ObjectType = nullptr;
2127
1.11M
      }
2128
2129
1.23M
      if (Tok.is(tok::code_completion)) {
2130
161
        tok::TokenKind CorrectedOpKind =
2131
161
            OpKind == tok::arrow ? 
tok::period44
:
tok::arrow117
;
2132
161
        ExprResult CorrectedLHS(/*Invalid=*/true);
2133
161
        if (getLangOpts().CPlusPlus && 
OrigLHS112
) {
2134
          // FIXME: Creating a TentativeAnalysisScope from outside Sema is a
2135
          // hack.
2136
111
          Sema::TentativeAnalysisScope Trap(Actions);
2137
111
          CorrectedLHS = Actions.ActOnStartCXXMemberReference(
2138
111
              getCurScope(), OrigLHS, OpLoc, CorrectedOpKind, ObjectType,
2139
111
              MayBePseudoDestructor);
2140
111
        }
2141
2142
161
        Expr *Base = LHS.get();
2143
161
        Expr *CorrectedBase = CorrectedLHS.get();
2144
161
        if (!CorrectedBase && 
!getLangOpts().CPlusPlus50
)
2145
49
          CorrectedBase = Base;
2146
2147
        // Code completion for a member access expression.
2148
161
        cutOffParsing();
2149
161
        Actions.CodeCompleteMemberReferenceExpr(
2150
161
            getCurScope(), Base, CorrectedBase, OpLoc, OpKind == tok::arrow,
2151
161
            Base && 
ExprStatementTokLoc == Base->getBeginLoc()160
,
2152
161
            PreferredType.get(Tok.getLocation()));
2153
2154
161
        return ExprError();
2155
161
      }
2156
2157
1.23M
      if (MayBePseudoDestructor && 
!LHS.isInvalid()6.61k
) {
2158
6.61k
        LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
2159
6.61k
                                       ObjectType);
2160
6.61k
        break;
2161
6.61k
      }
2162
2163
      // Either the action has told us that this cannot be a
2164
      // pseudo-destructor expression (based on the type of base
2165
      // expression), or we didn't see a '~' in the right place. We
2166
      // can still parse a destructor name here, but in that case it
2167
      // names a real destructor.
2168
      // Allow explicit constructor calls in Microsoft mode.
2169
      // FIXME: Add support for explicit call of template constructor.
2170
1.22M
      SourceLocation TemplateKWLoc;
2171
1.22M
      UnqualifiedId Name;
2172
1.22M
      if (getLangOpts().ObjC && 
OpKind == tok::period195k
&&
2173
1.22M
          
Tok.is(tok::kw_class)104k
) {
2174
        // Objective-C++:
2175
        //   After a '.' in a member access expression, treat the keyword
2176
        //   'class' as if it were an identifier.
2177
        //
2178
        // This hack allows property access to the 'class' method because it is
2179
        // such a common method name. For other C++ keywords that are
2180
        // Objective-C method names, one must use the message send syntax.
2181
2
        IdentifierInfo *Id = Tok.getIdentifierInfo();
2182
2
        SourceLocation Loc = ConsumeToken();
2183
2
        Name.setIdentifier(Id, Loc);
2184
1.22M
      } else if (ParseUnqualifiedId(
2185
1.22M
                     SS, ObjectType, LHS.get() && 
LHS.get()->containsErrors()1.22M
,
2186
1.22M
                     /*EnteringContext=*/false,
2187
1.22M
                     /*AllowDestructorName=*/true,
2188
                     /*AllowConstructorName=*/
2189
1.22M
                     getLangOpts().MicrosoftExt && 
SS.isNotEmpty()3.69k
,
2190
1.22M
                     /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name)) {
2191
324
        (void)Actions.CorrectDelayedTyposInExpr(LHS);
2192
324
        LHS = ExprError();
2193
324
      }
2194
2195
1.22M
      if (!LHS.isInvalid())
2196
1.22M
        LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
2197
1.22M
                                            OpKind, SS, TemplateKWLoc, Name,
2198
1.22M
                                 CurParsedObjCImpl ? 
CurParsedObjCImpl->Dcl2.21k
2199
1.22M
                                                   : 
nullptr1.22M
);
2200
1.22M
      if (!LHS.isInvalid()) {
2201
1.22M
        if (Tok.is(tok::less))
2202
3.24k
          checkPotentialAngleBracket(LHS);
2203
1.22M
      } else 
if (1.21k
OrigLHS1.21k
&&
Name.isValid()763
) {
2204
        // Preserve the LHS if the RHS is an invalid member.
2205
452
        LHS = Actions.CreateRecoveryExpr(OrigLHS->getBeginLoc(),
2206
452
                                         Name.getEndLoc(), {OrigLHS});
2207
452
      }
2208
1.22M
      break;
2209
1.23M
    }
2210
43.1k
    case tok::plusplus:    // postfix-expression: postfix-expression '++'
2211
44.5k
    case tok::minusminus:  // postfix-expression: postfix-expression '--'
2212
44.5k
      if (!LHS.isInvalid()) {
2213
44.5k
        Expr *Arg = LHS.get();
2214
44.5k
        LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
2215
44.5k
                                          Tok.getKind(), Arg);
2216
44.5k
        if (LHS.isInvalid())
2217
84
          LHS = Actions.CreateRecoveryExpr(Arg->getBeginLoc(),
2218
84
                                           Tok.getLocation(), Arg);
2219
44.5k
      }
2220
44.5k
      ConsumeToken();
2221
44.5k
      break;
2222
37.1M
    }
2223
37.1M
  }
2224
30.7M
}
2225
2226
/// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
2227
/// vec_step and we are at the start of an expression or a parenthesized
2228
/// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
2229
/// expression (isCastExpr == false) or the type (isCastExpr == true).
2230
///
2231
/// \verbatim
2232
///       unary-expression:  [C99 6.5.3]
2233
///         'sizeof' unary-expression
2234
///         'sizeof' '(' type-name ')'
2235
/// [GNU]   '__alignof' unary-expression
2236
/// [GNU]   '__alignof' '(' type-name ')'
2237
/// [C11]   '_Alignof' '(' type-name ')'
2238
/// [C++0x] 'alignof' '(' type-id ')'
2239
///
2240
/// [GNU]   typeof-specifier:
2241
///           typeof ( expressions )
2242
///           typeof ( type-name )
2243
/// [GNU/C++] typeof unary-expression
2244
///
2245
/// [OpenCL 1.1 6.11.12] vec_step built-in function:
2246
///           vec_step ( expressions )
2247
///           vec_step ( type-name )
2248
/// \endverbatim
2249
ExprResult
2250
Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
2251
                                           bool &isCastExpr,
2252
                                           ParsedType &CastTy,
2253
92.5k
                                           SourceRange &CastRange) {
2254
2255
92.5k
  assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
2256
92.5k
                       tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
2257
92.5k
                       tok::kw___builtin_omp_required_simd_align) &&
2258
92.5k
         "Not a typeof/sizeof/alignof/vec_step expression!");
2259
2260
0
  ExprResult Operand;
2261
2262
  // If the operand doesn't start with an '(', it must be an expression.
2263
92.5k
  if (Tok.isNot(tok::l_paren)) {
2264
    // If construct allows a form without parenthesis, user may forget to put
2265
    // pathenthesis around type name.
2266
828
    if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
2267
828
                      tok::kw__Alignof)) {
2268
822
      if (isTypeIdUnambiguously()) {
2269
9
        DeclSpec DS(AttrFactory);
2270
9
        ParseSpecifierQualifierList(DS);
2271
9
        Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
2272
9
        ParseDeclarator(DeclaratorInfo);
2273
2274
9
        SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
2275
9
        SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
2276
9
        if (LParenLoc.isInvalid() || 
RParenLoc.isInvalid()8
) {
2277
1
          Diag(OpTok.getLocation(),
2278
1
               diag::err_expected_parentheses_around_typename)
2279
1
              << OpTok.getName();
2280
8
        } else {
2281
8
          Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
2282
8
              << OpTok.getName() << FixItHint::CreateInsertion(LParenLoc, "(")
2283
8
              << FixItHint::CreateInsertion(RParenLoc, ")");
2284
8
        }
2285
9
        isCastExpr = true;
2286
9
        return ExprEmpty();
2287
9
      }
2288
822
    }
2289
2290
819
    isCastExpr = false;
2291
819
    if (OpTok.is(tok::kw_typeof) && 
!getLangOpts().CPlusPlus6
) {
2292
0
      Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
2293
0
                                          << tok::l_paren;
2294
0
      return ExprError();
2295
0
    }
2296
2297
819
    Operand = ParseCastExpression(UnaryExprOnly);
2298
91.7k
  } else {
2299
    // If it starts with a '(', we know that it is either a parenthesized
2300
    // type-name, or it is a unary-expression that starts with a compound
2301
    // literal, or starts with a primary-expression that is a parenthesized
2302
    // expression.
2303
91.7k
    ParenParseOption ExprType = CastExpr;
2304
91.7k
    SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
2305
2306
91.7k
    Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
2307
91.7k
                                   false, CastTy, RParenLoc);
2308
91.7k
    CastRange = SourceRange(LParenLoc, RParenLoc);
2309
2310
    // If ParseParenExpression parsed a '(typename)' sequence only, then this is
2311
    // a type.
2312
91.7k
    if (ExprType == CastExpr) {
2313
76.1k
      isCastExpr = true;
2314
76.1k
      return ExprEmpty();
2315
76.1k
    }
2316
2317
15.5k
    if (getLangOpts().CPlusPlus || 
OpTok.isNot(tok::kw_typeof)1.53k
) {
2318
      // GNU typeof in C requires the expression to be parenthesized. Not so for
2319
      // sizeof/alignof or in C++. Therefore, the parenthesized expression is
2320
      // the start of a unary-expression, but doesn't include any postfix
2321
      // pieces. Parse these now if present.
2322
15.0k
      if (!Operand.isInvalid())
2323
14.9k
        Operand = ParsePostfixExpressionSuffix(Operand.get());
2324
15.0k
    }
2325
15.5k
  }
2326
2327
  // If we get here, the operand to the typeof/sizeof/alignof was an expression.
2328
16.3k
  isCastExpr = false;
2329
16.3k
  return Operand;
2330
92.5k
}
2331
2332
/// Parse a __builtin_sycl_unique_stable_name expression.  Accepts a type-id as
2333
/// a parameter.
2334
74
ExprResult Parser::ParseSYCLUniqueStableNameExpression() {
2335
74
  assert(Tok.is(tok::kw___builtin_sycl_unique_stable_name) &&
2336
74
         "Not __builtin_sycl_unique_stable_name");
2337
2338
0
  SourceLocation OpLoc = ConsumeToken();
2339
74
  BalancedDelimiterTracker T(*this, tok::l_paren);
2340
2341
  // __builtin_sycl_unique_stable_name expressions are always parenthesized.
2342
74
  if (T.expectAndConsume(diag::err_expected_lparen_after,
2343
74
                         "__builtin_sycl_unique_stable_name"))
2344
2
    return ExprError();
2345
2346
72
  TypeResult Ty = ParseTypeName();
2347
2348
72
  if (Ty.isInvalid()) {
2349
8
    T.skipToEnd();
2350
8
    return ExprError();
2351
8
  }
2352
2353
64
  if (T.consumeClose())
2354
2
    return ExprError();
2355
2356
62
  return Actions.ActOnSYCLUniqueStableNameExpr(OpLoc, T.getOpenLocation(),
2357
62
                                               T.getCloseLocation(), Ty.get());
2358
64
}
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
137k
ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
2373
137k
  assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
2374
137k
                     tok::kw__Alignof, tok::kw_vec_step,
2375
137k
                     tok::kw___builtin_omp_required_simd_align) &&
2376
137k
         "Not a sizeof/alignof/vec_step expression!");
2377
0
  Token OpTok = Tok;
2378
137k
  ConsumeToken();
2379
2380
  // [C++11] 'sizeof' '...' '(' identifier ')'
2381
137k
  if (Tok.is(tok::ellipsis) && 
OpTok.is(tok::kw_sizeof)47.5k
) {
2382
47.5k
    SourceLocation EllipsisLoc = ConsumeToken();
2383
47.5k
    SourceLocation LParenLoc, RParenLoc;
2384
47.5k
    IdentifierInfo *Name = nullptr;
2385
47.5k
    SourceLocation NameLoc;
2386
47.5k
    if (Tok.is(tok::l_paren)) {
2387
47.5k
      BalancedDelimiterTracker T(*this, tok::l_paren);
2388
47.5k
      T.consumeOpen();
2389
47.5k
      LParenLoc = T.getOpenLocation();
2390
47.5k
      if (Tok.is(tok::identifier)) {
2391
47.5k
        Name = Tok.getIdentifierInfo();
2392
47.5k
        NameLoc = ConsumeToken();
2393
47.5k
        T.consumeClose();
2394
47.5k
        RParenLoc = T.getCloseLocation();
2395
47.5k
        if (RParenLoc.isInvalid())
2396
0
          RParenLoc = PP.getLocForEndOfToken(NameLoc);
2397
47.5k
      } else {
2398
0
        Diag(Tok, diag::err_expected_parameter_pack);
2399
0
        SkipUntil(tok::r_paren, StopAtSemi);
2400
0
      }
2401
47.5k
    } else 
if (1
Tok.is(tok::identifier)1
) {
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
1
    } else {
2411
0
      Diag(Tok, diag::err_sizeof_parameter_pack);
2412
0
    }
2413
2414
47.5k
    if (!Name)
2415
0
      return ExprError();
2416
2417
47.5k
    EnterExpressionEvaluationContext Unevaluated(
2418
47.5k
        Actions, Sema::ExpressionEvaluationContext::Unevaluated,
2419
47.5k
        Sema::ReuseLambdaContextDecl);
2420
2421
47.5k
    return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
2422
47.5k
                                                OpTok.getLocation(),
2423
47.5k
                                                *Name, NameLoc,
2424
47.5k
                                                RParenLoc);
2425
47.5k
  }
2426
2427
89.8k
  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2428
6.43k
    Diag(OpTok, diag::warn_cxx98_compat_alignof);
2429
2430
89.8k
  EnterExpressionEvaluationContext Unevaluated(
2431
89.8k
      Actions, Sema::ExpressionEvaluationContext::Unevaluated,
2432
89.8k
      Sema::ReuseLambdaContextDecl);
2433
2434
89.8k
  bool isCastExpr;
2435
89.8k
  ParsedType CastTy;
2436
89.8k
  SourceRange CastRange;
2437
89.8k
  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
2438
89.8k
                                                          isCastExpr,
2439
89.8k
                                                          CastTy,
2440
89.8k
                                                          CastRange);
2441
2442
89.8k
  UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
2443
89.8k
  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2444
6.43k
    ExprKind = UETT_AlignOf;
2445
83.4k
  else if (OpTok.is(tok::kw___alignof))
2446
2.96k
    ExprKind = UETT_PreferredAlignOf;
2447
80.4k
  else if (OpTok.is(tok::kw_vec_step))
2448
45
    ExprKind = UETT_VecStep;
2449
80.3k
  else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
2450
29
    ExprKind = UETT_OpenMPRequiredSimdAlign;
2451
2452
89.8k
  if (isCastExpr)
2453
76.0k
    return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2454
76.0k
                                                 ExprKind,
2455
76.0k
                                                 /*IsType=*/true,
2456
76.0k
                                                 CastTy.getAsOpaquePtr(),
2457
76.0k
                                                 CastRange);
2458
2459
13.7k
  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2460
39
    Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
2461
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
89.8k
}
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
21.4k
ExprResult Parser::ParseBuiltinPrimaryExpression() {
2493
21.4k
  ExprResult Res;
2494
21.4k
  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
2495
2496
21.4k
  tok::TokenKind T = Tok.getKind();
2497
21.4k
  SourceLocation StartLoc = ConsumeToken();   // Eat the builtin identifier.
2498
2499
  // All of these start with an open paren.
2500
21.4k
  if (Tok.isNot(tok::l_paren))
2501
0
    return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
2502
0
                                                         << tok::l_paren);
2503
2504
21.4k
  BalancedDelimiterTracker PT(*this, tok::l_paren);
2505
21.4k
  PT.consumeOpen();
2506
2507
  // TODO: Build AST.
2508
2509
21.4k
  switch (T) {
2510
0
  default: llvm_unreachable("Not a builtin primary expression!");
2511
1.07k
  case tok::kw___builtin_va_arg: {
2512
1.07k
    ExprResult Expr(ParseAssignmentExpression());
2513
2514
1.07k
    if (ExpectAndConsume(tok::comma)) {
2515
0
      SkipUntil(tok::r_paren, StopAtSemi);
2516
0
      Expr = ExprError();
2517
0
    }
2518
2519
1.07k
    TypeResult Ty = ParseTypeName();
2520
2521
1.07k
    if (Tok.isNot(tok::r_paren)) {
2522
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2523
0
      Expr = ExprError();
2524
0
    }
2525
2526
1.07k
    if (Expr.isInvalid() || Ty.isInvalid())
2527
0
      Res = ExprError();
2528
1.07k
    else
2529
1.07k
      Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
2530
1.07k
    break;
2531
0
  }
2532
344
  case tok::kw___builtin_offsetof: {
2533
344
    SourceLocation TypeLoc = Tok.getLocation();
2534
344
    TypeResult Ty = ParseTypeName();
2535
344
    if (Ty.isInvalid()) {
2536
1
      SkipUntil(tok::r_paren, StopAtSemi);
2537
1
      return ExprError();
2538
1
    }
2539
2540
343
    if (ExpectAndConsume(tok::comma)) {
2541
0
      SkipUntil(tok::r_paren, StopAtSemi);
2542
0
      return ExprError();
2543
0
    }
2544
2545
    // We must have at least one identifier here.
2546
343
    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
2552
    // Keep track of the various subcomponents we see.
2553
343
    SmallVector<Sema::OffsetOfComponent, 4> Comps;
2554
2555
343
    Comps.push_back(Sema::OffsetOfComponent());
2556
343
    Comps.back().isBrackets = false;
2557
343
    Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2558
343
    Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2559
2560
    // FIXME: This loop leaks the index expressions on error.
2561
404
    while (true) {
2562
404
      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
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
2576
385
      } else if (Tok.is(tok::l_square)) {
2577
42
        if (CheckProhibitedCXX11Attribute())
2578
0
          return ExprError();
2579
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
2593
42
        ST.consumeClose();
2594
42
        Comps.back().LocEnd = ST.getCloseLocation();
2595
343
      } else {
2596
343
        if (Tok.isNot(tok::r_paren)) {
2597
2
          PT.consumeClose();
2598
2
          Res = ExprError();
2599
341
        } else if (Ty.isInvalid()) {
2600
0
          Res = ExprError();
2601
341
        } else {
2602
341
          PT.consumeClose();
2603
341
          Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2604
341
                                             Ty.get(), Comps,
2605
341
                                             PT.getCloseLocation());
2606
341
        }
2607
343
        break;
2608
343
      }
2609
404
    }
2610
343
    break;
2611
343
  }
2612
343
  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
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
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
45
  case tok::kw___builtin_astype: {
2647
    // The first argument is an expression to be converted, followed by a comma.
2648
45
    ExprResult Expr(ParseAssignmentExpression());
2649
45
    if (Expr.isInvalid()) {
2650
0
      SkipUntil(tok::r_paren, StopAtSemi);
2651
0
      return ExprError();
2652
0
    }
2653
2654
45
    if (ExpectAndConsume(tok::comma)) {
2655
0
      SkipUntil(tok::r_paren, StopAtSemi);
2656
0
      return ExprError();
2657
0
    }
2658
2659
    // Second argument is the type to bitcast to.
2660
45
    TypeResult DestTy = ParseTypeName();
2661
45
    if (DestTy.isInvalid())
2662
0
      return ExprError();
2663
2664
    // Attempt to consume the r-paren.
2665
45
    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
2671
45
    Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2672
45
                                  ConsumeParen());
2673
45
    break;
2674
45
  }
2675
19.7k
  case tok::kw___builtin_convertvector: {
2676
    // The first argument is an expression to be converted, followed by a comma.
2677
19.7k
    ExprResult Expr(ParseAssignmentExpression());
2678
19.7k
    if (Expr.isInvalid()) {
2679
0
      SkipUntil(tok::r_paren, StopAtSemi);
2680
0
      return ExprError();
2681
0
    }
2682
2683
19.7k
    if (ExpectAndConsume(tok::comma)) {
2684
0
      SkipUntil(tok::r_paren, StopAtSemi);
2685
0
      return ExprError();
2686
0
    }
2687
2688
    // Second argument is the type to bitcast to.
2689
19.7k
    TypeResult DestTy = ParseTypeName();
2690
19.7k
    if (DestTy.isInvalid())
2691
0
      return ExprError();
2692
2693
    // Attempt to consume the r-paren.
2694
19.7k
    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
2700
19.7k
    Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2701
19.7k
                                         ConsumeParen());
2702
19.7k
    break;
2703
19.7k
  }
2704
22
  case tok::kw___builtin_COLUMN:
2705
49
  case tok::kw___builtin_FILE:
2706
72
  case tok::kw___builtin_FUNCTION:
2707
128
  case tok::kw___builtin_LINE: {
2708
    // Attempt to consume the r-paren.
2709
128
    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
120
    SourceLocExpr::IdentKind Kind = [&] {
2715
120
      switch (T) {
2716
25
      case tok::kw___builtin_FILE:
2717
25
        return SourceLocExpr::File;
2718
21
      case tok::kw___builtin_FUNCTION:
2719
21
        return SourceLocExpr::Function;
2720
54
      case tok::kw___builtin_LINE:
2721
54
        return SourceLocExpr::Line;
2722
20
      case tok::kw___builtin_COLUMN:
2723
20
        return SourceLocExpr::Column;
2724
0
      default:
2725
0
        llvm_unreachable("invalid keyword");
2726
120
      }
2727
120
    }();
2728
120
    Res = Actions.ActOnSourceLocExpr(Kind, StartLoc, ConsumeParen());
2729
120
    break;
2730
128
  }
2731
21.4k
  }
2732
2733
21.4k
  if (Res.isInvalid())
2734
36
    return ExprError();
2735
2736
  // These can be followed by postfix-expr pieces because they are
2737
  // primary-expressions.
2738
21.3k
  return ParsePostfixExpressionSuffix(Res.get());
2739
21.4k
}
2740
2741
133
bool Parser::tryParseOpenMPArrayShapingCastPart() {
2742
133
  assert(Tok.is(tok::l_square) && "Expected open bracket");
2743
0
  bool ErrorFound = true;
2744
133
  TentativeParsingAction TPA(*this);
2745
277
  do {
2746
277
    if (Tok.isNot(tok::l_square))
2747
0
      break;
2748
    // Consume '['
2749
277
    ConsumeBracket();
2750
    // Skip inner expression.
2751
277
    while (!SkipUntil(tok::r_square, tok::annot_pragma_openmp_end,
2752
277
                      StopAtSemi | StopBeforeMatch))
2753
0
      ;
2754
277
    if (Tok.isNot(tok::r_square))
2755
4
      break;
2756
    // Consume ']'
2757
273
    ConsumeBracket();
2758
    // Found ')' - done.
2759
273
    if (Tok.is(tok::r_paren)) {
2760
125
      ErrorFound = false;
2761
125
      break;
2762
125
    }
2763
273
  } while (
Tok.isNot(tok::annot_pragma_openmp_end)148
);
2764
0
  TPA.Revert();
2765
133
  return !ErrorFound;
2766
133
}
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.50M
                             SourceLocation &RParenLoc) {
2799
5.50M
  assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2800
0
  ColonProtectionRAIIObject ColonProtection(*this, false);
2801
5.50M
  BalancedDelimiterTracker T(*this, tok::l_paren);
2802
5.50M
  if (T.consumeOpen())
2803
0
    return ExprError();
2804
5.50M
  SourceLocation OpenLoc = T.getOpenLocation();
2805
2806
5.50M
  PreferredType.enterParenExpr(Tok.getLocation(), OpenLoc);
2807
2808
5.50M
  ExprResult Result(true);
2809
5.50M
  bool isAmbiguousTypeId;
2810
5.50M
  CastTy = nullptr;
2811
2812
5.50M
  if (Tok.is(tok::code_completion)) {
2813
30
    cutOffParsing();
2814
30
    Actions.CodeCompleteExpression(
2815
30
        getCurScope(), PreferredType.get(Tok.getLocation()),
2816
30
        /*IsParenthesized=*/ExprType >= CompoundLiteral);
2817
30
    return ExprError();
2818
30
  }
2819
2820
  // Diagnose use of bridge casts in non-arc mode.
2821
5.50M
  bool BridgeCast = (getLangOpts().ObjC &&
2822
5.50M
                     Tok.isOneOf(tok::kw___bridge,
2823
694k
                                 tok::kw___bridge_transfer,
2824
694k
                                 tok::kw___bridge_retained,
2825
694k
                                 tok::kw___bridge_retain));
2826
5.50M
  if (BridgeCast && 
!getLangOpts().ObjCAutoRefCount425
) {
2827
86
    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
86
    BridgeCast = false;
2836
86
  }
2837
2838
  // None of these cases should fall through with an invalid Result
2839
  // unless they've already reported an error.
2840
5.50M
  if (ExprType >= CompoundStmt && 
Tok.is(tok::l_brace)5.50M
) {
2841
8.91k
    Diag(Tok, diag::ext_gnu_statement_expr);
2842
2843
8.91k
    checkCompoundToken(OpenLoc, tok::l_paren, CompoundToken::StmtExprBegin);
2844
2845
8.91k
    if (!getCurScope()->getFnParent() && 
!getCurScope()->getBlockParent()2
) {
2846
2
      Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2847
8.91k
    } 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.91k
      DeclContext *CodeDC = Actions.CurContext;
2852
8.91k
      while (CodeDC->isRecord() || 
isa<EnumDecl>(CodeDC)8.91k
) {
2853
3
        CodeDC = CodeDC->getParent();
2854
3
        assert(CodeDC && !CodeDC->isFileContext() &&
2855
3
               "statement expr not in code context");
2856
3
      }
2857
8.91k
      Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2858
2859
8.91k
      Actions.ActOnStartStmtExpr();
2860
2861
8.91k
      StmtResult Stmt(ParseCompoundStatement(true));
2862
8.91k
      ExprType = CompoundStmt;
2863
2864
      // If the substmt parsed correctly, build the AST node.
2865
8.91k
      if (!Stmt.isInvalid()) {
2866
8.91k
        Result = Actions.ActOnStmtExpr(getCurScope(), OpenLoc, Stmt.get(),
2867
8.91k
                                       Tok.getLocation());
2868
8.91k
      } else {
2869
0
        Actions.ActOnStmtExprError();
2870
0
      }
2871
8.91k
    }
2872
5.49M
  } else if (ExprType >= CompoundLiteral && 
BridgeCast5.49M
) {
2873
339
    tok::TokenKind tokenKind = Tok.getKind();
2874
339
    SourceLocation BridgeKeywordLoc = ConsumeToken();
2875
2876
    // Parse an Objective-C ARC ownership cast expression.
2877
339
    ObjCBridgeCastKind Kind;
2878
339
    if (tokenKind == tok::kw___bridge)
2879
128
      Kind = OBC_Bridge;
2880
211
    else if (tokenKind == tok::kw___bridge_transfer)
2881
107
      Kind = OBC_BridgeTransfer;
2882
104
    else if (tokenKind == tok::kw___bridge_retained)
2883
100
      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
0
      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
2895
0
    TypeResult Ty = ParseTypeName();
2896
339
    T.consumeClose();
2897
339
    ColonProtection.restore();
2898
339
    RParenLoc = T.getCloseLocation();
2899
2900
339
    PreferredType.enterTypeCast(Tok.getLocation(), Ty.get().get());
2901
339
    ExprResult SubExpr = ParseCastExpression(AnyCastExpr);
2902
2903
339
    if (Ty.isInvalid() || SubExpr.isInvalid())
2904
0
      return ExprError();
2905
2906
339
    return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2907
339
                                        BridgeKeywordLoc, Ty.get(),
2908
339
                                        RParenLoc, SubExpr.get());
2909
5.49M
  } else if (ExprType >= CompoundLiteral &&
2910
5.49M
             
isTypeIdInParens(isAmbiguousTypeId)5.49M
) {
2911
2912
    // Otherwise, this is a compound literal expression or cast expression.
2913
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.46M
    if (isAmbiguousTypeId && 
!stopIfCastExpr1.73k
) {
2920
1.66k
      ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2921
1.66k
                                                        ColonProtection);
2922
1.66k
      RParenLoc = T.getCloseLocation();
2923
1.66k
      return res;
2924
1.66k
    }
2925
2926
    // Parse the type declarator.
2927
4.46M
    DeclSpec DS(AttrFactory);
2928
4.46M
    ParseSpecifierQualifierList(DS);
2929
4.46M
    Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
2930
4.46M
    ParseDeclarator(DeclaratorInfo);
2931
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.46M
    if (!DeclaratorInfo.isInvalidType() && 
Tok.is(tok::identifier)4.46M
&&
2936
4.46M
        
!InMessageExpression77
&&
getLangOpts().ObjC77
&&
2937
4.46M
        
(75
NextToken().is(tok::colon)75
||
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.46M
    } else {
2947
      // Match the ')'.
2948
4.46M
      T.consumeClose();
2949
4.46M
      ColonProtection.restore();
2950
4.46M
      RParenLoc = T.getCloseLocation();
2951
4.46M
      if (Tok.is(tok::l_brace)) {
2952
51.0k
        ExprType = CompoundLiteral;
2953
51.0k
        TypeResult Ty;
2954
51.0k
        {
2955
51.0k
          InMessageExpressionRAIIObject InMessage(*this, false);
2956
51.0k
          Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2957
51.0k
        }
2958
51.0k
        return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2959
51.0k
      }
2960
2961
4.41M
      if (Tok.is(tok::l_paren)) {
2962
        // This could be OpenCL vector Literals
2963
370k
        if (getLangOpts().OpenCL)
2964
474
        {
2965
474
          TypeResult Ty;
2966
474
          {
2967
474
            InMessageExpressionRAIIObject InMessage(*this, false);
2968
474
            Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2969
474
          }
2970
474
          if(Ty.isInvalid())
2971
0
          {
2972
0
             return ExprError();
2973
0
          }
2974
474
          QualType QT = Ty.get().get().getCanonicalType();
2975
474
          if (QT->isVectorType())
2976
164
          {
2977
            // We parsed '(' vector-type-name ')' followed by '('
2978
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
164
            Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
2983
164
                                         /*isAddressOfOperand=*/false,
2984
164
                                         /*isTypeCast=*/IsTypeCast,
2985
164
                                         /*isVectorLiteral=*/true);
2986
2987
164
            if (!Result.isInvalid()) {
2988
164
              Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2989
164
                                             DeclaratorInfo, CastTy,
2990
164
                                             RParenLoc, Result.get());
2991
164
            }
2992
2993
            // After we performed the cast we can check for postfix-expr pieces.
2994
164
            if (!Result.isInvalid()) {
2995
161
              Result = ParsePostfixExpressionSuffix(Result);
2996
161
            }
2997
2998
164
            return Result;
2999
164
          }
3000
474
        }
3001
370k
      }
3002
3003
4.41M
      if (ExprType == CastExpr) {
3004
        // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
3005
3006
4.41M
        if (DeclaratorInfo.isInvalidType())
3007
7
          return ExprError();
3008
3009
        // Note that this doesn't parse the subsequent cast-expression, it just
3010
        // returns the parsed type to the callee.
3011
4.41M
        if (stopIfCastExpr) {
3012
76.1k
          TypeResult Ty;
3013
76.1k
          {
3014
76.1k
            InMessageExpressionRAIIObject InMessage(*this, false);
3015
76.1k
            Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3016
76.1k
          }
3017
76.1k
          CastTy = Ty.get();
3018
76.1k
          return ExprResult();
3019
76.1k
        }
3020
3021
        // Reject the cast of super idiom in ObjC.
3022
4.33M
        if (Tok.is(tok::identifier) && 
getLangOpts().ObjC3.79M
&&
3023
4.33M
            
Tok.getIdentifierInfo() == Ident_super263k
&&
3024
4.33M
            
getCurScope()->isInObjcMethodScope()10
&&
3025
4.33M
            
GetLookAheadToken(1).isNot(tok::period)8
) {
3026
7
          Diag(Tok.getLocation(), diag::err_illegal_super_cast)
3027
7
            << SourceRange(OpenLoc, RParenLoc);
3028
7
          return ExprError();
3029
7
        }
3030
3031
4.33M
        PreferredType.enterTypeCast(Tok.getLocation(), CastTy.get());
3032
        // Parse the cast-expression that follows it next.
3033
        // TODO: For cast expression with CastTy.
3034
4.33M
        Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
3035
4.33M
                                     /*isAddressOfOperand=*/false,
3036
4.33M
                                     /*isTypeCast=*/IsTypeCast);
3037
4.33M
        if (!Result.isInvalid()) {
3038
4.33M
          Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
3039
4.33M
                                         DeclaratorInfo, CastTy,
3040
4.33M
                                         RParenLoc, Result.get());
3041
4.33M
        }
3042
4.33M
        return Result;
3043
4.33M
      }
3044
3045
0
      Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
3046
0
      return ExprError();
3047
4.41M
    }
3048
4.46M
  } else 
if (1.03M
ExprType >= FoldExpr1.03M
&&
Tok.is(tok::ellipsis)1.03M
&&
3049
1.03M
             
isFoldOperator(NextToken().getKind())27
) {
3050
23
    ExprType = FoldExpr;
3051
23
    return ParseFoldExpression(ExprResult(), T);
3052
1.03M
  } else if (isTypeCast) {
3053
    // Parse the expression-list.
3054
303k
    InMessageExpressionRAIIObject InMessage(*this, false);
3055
3056
303k
    ExprVector ArgExprs;
3057
303k
    CommaLocsTy CommaLocs;
3058
3059
303k
    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
303k
      if (ExprType >= FoldExpr && ArgExprs.size() == 1 &&
3063
303k
          
isFoldOperator(Tok.getKind())302k
&&
NextToken().is(tok::ellipsis)30
) {
3064
30
        ExprType = FoldExpr;
3065
30
        return ParseFoldExpression(ArgExprs[0], T);
3066
30
      }
3067
3068
303k
      ExprType = SimpleExpr;
3069
303k
      Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
3070
303k
                                          ArgExprs);
3071
303k
    }
3072
726k
  } else if (getLangOpts().OpenMP >= 50 && 
OpenMPDirectiveParsing3.68k
&&
3073
726k
             
ExprType == CastExpr1.19k
&&
Tok.is(tok::l_square)1.19k
&&
3074
726k
             
tryParseOpenMPArrayShapingCastPart()133
) {
3075
125
    bool ErrorFound = false;
3076
125
    SmallVector<Expr *, 4> OMPDimensions;
3077
125
    SmallVector<SourceRange, 4> OMPBracketsRanges;
3078
269
    do {
3079
269
      BalancedDelimiterTracker TS(*this, tok::l_square);
3080
269
      TS.consumeOpen();
3081
269
      ExprResult NumElements =
3082
269
          Actions.CorrectDelayedTyposInExpr(ParseExpression());
3083
269
      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
269
      TS.consumeClose();
3090
269
      OMPDimensions.push_back(NumElements.get());
3091
269
      OMPBracketsRanges.push_back(TS.getRange());
3092
269
    } while (Tok.isNot(tok::r_paren));
3093
    // Match the ')'.
3094
125
    T.consumeClose();
3095
125
    RParenLoc = T.getCloseLocation();
3096
125
    Result = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3097
125
    if (ErrorFound) {
3098
12
      Result = ExprError();
3099
113
    } else if (!Result.isInvalid()) {
3100
113
      Result = Actions.ActOnOMPArrayShapingExpr(
3101
113
          Result.get(), OpenLoc, RParenLoc, OMPDimensions, OMPBracketsRanges);
3102
113
    }
3103
125
    return Result;
3104
726k
  } else {
3105
726k
    InMessageExpressionRAIIObject InMessage(*this, false);
3106
3107
726k
    Result = ParseExpression(MaybeTypeCast);
3108
726k
    if (!getLangOpts().CPlusPlus && 
MaybeTypeCast295k
&&
Result.isUsable()295k
) {
3109
      // Correct typos in non-C++ code earlier so that implicit-cast-like
3110
      // expressions are parsed correctly.
3111
295k
      Result = Actions.CorrectDelayedTyposInExpr(Result);
3112
295k
    }
3113
3114
726k
    if (ExprType >= FoldExpr && isFoldOperator(Tok.getKind()) &&
3115
726k
        
NextToken().is(tok::ellipsis)178
) {
3116
166
      ExprType = FoldExpr;
3117
166
      return ParseFoldExpression(Result, T);
3118
166
    }
3119
726k
    ExprType = SimpleExpr;
3120
3121
    // Don't build a paren expression unless we actually match a ')'.
3122
726k
    if (!Result.isInvalid() && 
Tok.is(tok::r_paren)725k
)
3123
725k
      Result =
3124
725k
          Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
3125
726k
  }
3126
3127
  // Match the ')'.
3128
1.03M
  if (Result.isInvalid()) {
3129
559
    SkipUntil(tok::r_paren, StopAtSemi);
3130
559
    return ExprError();
3131
559
  }
3132
3133
1.03M
  T.consumeClose();
3134
1.03M
  RParenLoc = T.getCloseLocation();
3135
1.03M
  return Result;
3136
1.03M
}
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
51.0k
                                       SourceLocation RParenLoc) {
3150
51.0k
  assert(Tok.is(tok::l_brace) && "Not a compound literal!");
3151
51.0k
  if (!getLangOpts().C99)   // Compound literals don't exist in C90.
3152
6.72k
    Diag(LParenLoc, diag::ext_c99_compound_literal);
3153
51.0k
  PreferredType.enterTypeCast(Tok.getLocation(), Ty.get());
3154
51.0k
  ExprResult Result = ParseInitializer();
3155
51.0k
  if (!Result.isInvalid() && 
Ty51.0k
)
3156
51.0k
    return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
3157
4
  return Result;
3158
51.0k
}
3159
3160
/// ParseStringLiteralExpression - This handles the various token types that
3161
/// form string literals, and also handles string concatenation [C99 5.1.1.2,
3162
/// translation phase #6].
3163
///
3164
/// \verbatim
3165
///       primary-expression: [C99 6.5.1]
3166
///         string-literal
3167
/// \verbatim
3168
3.97M
ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
3169
3.97M
  assert(isTokenStringLiteral() && "Not a string literal!");
3170
3171
  // String concat.  Note that keywords like __func__ and __FUNCTION__ are not
3172
  // considered to be strings for concatenation purposes.
3173
0
  SmallVector<Token, 4> StringToks;
3174
3175
4.14M
  do {
3176
4.14M
    StringToks.push_back(Tok);
3177
4.14M
    ConsumeStringToken();
3178
4.14M
  } while (isTokenStringLiteral());
3179
3180
  // Pass the set of string tokens, ready for concatenation, to the actions.
3181
3.97M
  return Actions.ActOnStringLiteral(StringToks,
3182
3.97M
                                    AllowUserDefinedLiteral ? 
getCurScope()3.09M
3183
3.97M
                                                            : 
nullptr883k
);
3184
3.97M
}
3185
3186
/// ParseGenericSelectionExpression - Parse a C11 generic-selection
3187
/// [C11 6.5.1.1].
3188
///
3189
/// \verbatim
3190
///    generic-selection:
3191
///           _Generic ( assignment-expression , generic-assoc-list )
3192
///    generic-assoc-list:
3193
///           generic-association
3194
///           generic-assoc-list , generic-association
3195
///    generic-association:
3196
///           type-name : assignment-expression
3197
///           default : assignment-expression
3198
/// \endverbatim
3199
188
ExprResult Parser::ParseGenericSelectionExpression() {
3200
188
  assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
3201
188
  if (!getLangOpts().C11)
3202
65
    Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3203
3204
188
  SourceLocation KeyLoc = ConsumeToken();
3205
188
  BalancedDelimiterTracker T(*this, tok::l_paren);
3206
188
  if (T.expectAndConsume())
3207
1
    return ExprError();
3208
3209
187
  ExprResult ControllingExpr;
3210
187
  {
3211
    // C11 6.5.1.1p3 "The controlling expression of a generic selection is
3212
    // not evaluated."
3213
187
    EnterExpressionEvaluationContext Unevaluated(
3214
187
        Actions, Sema::ExpressionEvaluationContext::Unevaluated);
3215
187
    ControllingExpr =
3216
187
        Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3217
187
    if (ControllingExpr.isInvalid()) {
3218
1
      SkipUntil(tok::r_paren, StopAtSemi);
3219
1
      return ExprError();
3220
1
    }
3221
187
  }
3222
3223
186
  if (ExpectAndConsume(tok::comma)) {
3224
1
    SkipUntil(tok::r_paren, StopAtSemi);
3225
1
    return ExprError();
3226
1
  }
3227
3228
185
  SourceLocation DefaultLoc;
3229
185
  TypeVector Types;
3230
185
  ExprVector Exprs;
3231
406
  do {
3232
406
    ParsedType Ty;
3233
406
    if (Tok.is(tok::kw_default)) {
3234
      // C11 6.5.1.1p2 "A generic selection shall have no more than one default
3235
      // generic association."
3236
90
      if (!DefaultLoc.isInvalid()) {
3237
1
        Diag(Tok, diag::err_duplicate_default_assoc);
3238
1
        Diag(DefaultLoc, diag::note_previous_default_assoc);
3239
1
        SkipUntil(tok::r_paren, StopAtSemi);
3240
1
        return ExprError();
3241
1
      }
3242
89
      DefaultLoc = ConsumeToken();
3243
89
      Ty = nullptr;
3244
316
    } else {
3245
316
      ColonProtectionRAIIObject X(*this);
3246
316
      TypeResult TR = ParseTypeName();
3247
316
      if (TR.isInvalid()) {
3248
0
        SkipUntil(tok::r_paren, StopAtSemi);
3249
0
        return ExprError();
3250
0
      }
3251
316
      Ty = TR.get();
3252
316
    }
3253
405
    Types.push_back(Ty);
3254
3255
405
    if (ExpectAndConsume(tok::colon)) {
3256
1
      SkipUntil(tok::r_paren, StopAtSemi);
3257
1
      return ExprError();
3258
1
    }
3259
3260
    // FIXME: These expressions should be parsed in a potentially potentially
3261
    // evaluated context.
3262
404
    ExprResult ER(
3263
404
        Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
3264
404
    if (ER.isInvalid()) {
3265
0
      SkipUntil(tok::r_paren, StopAtSemi);
3266
0
      return ExprError();
3267
0
    }
3268
404
    Exprs.push_back(ER.get());
3269
404
  } while (TryConsumeToken(tok::comma));
3270
3271
183
  T.consumeClose();
3272
183
  if (T.getCloseLocation().isInvalid())
3273
0
    return ExprError();
3274
3275
183
  return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
3276
183
                                           T.getCloseLocation(),
3277
183
                                           ControllingExpr.get(),
3278
183
                                           Types, Exprs);
3279
183
}
3280
3281
/// Parse A C++1z fold-expression after the opening paren and optional
3282
/// left-hand-side expression.
3283
///
3284
/// \verbatim
3285
///   fold-expression:
3286
///       ( cast-expression fold-operator ... )
3287
///       ( ... fold-operator cast-expression )
3288
///       ( cast-expression fold-operator ... fold-operator cast-expression )
3289
ExprResult Parser::ParseFoldExpression(ExprResult LHS,
3290
219
                                       BalancedDelimiterTracker &T) {
3291
219
  if (LHS.isInvalid()) {
3292
1
    T.skipToEnd();
3293
1
    return true;
3294
1
  }
3295
3296
218
  tok::TokenKind Kind = tok::unknown;
3297
218
  SourceLocation FirstOpLoc;
3298
218
  if (LHS.isUsable()) {
3299
195
    Kind = Tok.getKind();
3300
195
    assert(isFoldOperator(Kind) && "missing fold-operator");
3301
0
    FirstOpLoc = ConsumeToken();
3302
195
  }
3303
3304
0
  assert(Tok.is(tok::ellipsis) && "not a fold-expression");
3305
0
  SourceLocation EllipsisLoc = ConsumeToken();
3306
3307
218
  ExprResult RHS;
3308
218
  if (Tok.isNot(tok::r_paren)) {
3309
80
    if (!isFoldOperator(Tok.getKind()))
3310
1
      return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
3311
3312
79
    if (Kind != tok::unknown && 
Tok.getKind() != Kind56
)
3313
2
      Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
3314
2
        << SourceRange(FirstOpLoc);
3315
79
    Kind = Tok.getKind();
3316
79
    ConsumeToken();
3317
3318
79
    RHS = ParseExpression();
3319
79
    if (RHS.isInvalid()) {
3320
0
      T.skipToEnd();
3321
0
      return true;
3322
0
    }
3323
79
  }
3324
3325
217
  Diag(EllipsisLoc, getLangOpts().CPlusPlus17
3326
217
                        ? 
diag::warn_cxx14_compat_fold_expression180
3327
217
                        : 
diag::ext_fold_expression37
);
3328
3329
217
  T.consumeClose();
3330
217
  return Actions.ActOnCXXFoldExpr(getCurScope(), T.getOpenLocation(), LHS.get(),
3331
217
                                  Kind, EllipsisLoc, RHS.get(),
3332
217
                                  T.getCloseLocation());
3333
218
}
3334
3335
/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
3336
///
3337
/// \verbatim
3338
///       argument-expression-list:
3339
///         assignment-expression
3340
///         argument-expression-list , assignment-expression
3341
///
3342
/// [C++] expression-list:
3343
/// [C++]   assignment-expression
3344
/// [C++]   expression-list , assignment-expression
3345
///
3346
/// [C++0x] expression-list:
3347
/// [C++0x]   initializer-list
3348
///
3349
/// [C++0x] initializer-list
3350
/// [C++0x]   initializer-clause ...[opt]
3351
/// [C++0x]   initializer-list , initializer-clause ...[opt]
3352
///
3353
/// [C++0x] initializer-clause:
3354
/// [C++0x]   assignment-expression
3355
/// [C++0x]   braced-init-list
3356
/// \endverbatim
3357
bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
3358
                                 SmallVectorImpl<SourceLocation> &CommaLocs,
3359
4.17M
                                 llvm::function_ref<void()> ExpressionStarts) {
3360
4.17M
  bool SawError = false;
3361
9.35M
  while (true) {
3362
9.35M
    if (ExpressionStarts)
3363
9.33M
      ExpressionStarts();
3364
3365
9.35M
    ExprResult Expr;
3366
9.35M
    if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)4.09M
) {
3367
1.82k
      Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3368
1.82k
      Expr = ParseBraceInitializer();
3369
1.82k
    } else
3370
9.34M
      Expr = ParseAssignmentExpression();
3371
3372
9.35M
    if (Tok.is(tok::ellipsis))
3373
45.1k
      Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
3374
9.30M
    else if (Tok.is(tok::code_completion)) {
3375
      // There's nothing to suggest in here as we parsed a full expression.
3376
      // Instead fail and propogate the error since caller might have something
3377
      // the suggest, e.g. signature help in function call. Note that this is
3378
      // performed before pushing the \p Expr, so that signature help can report
3379
      // current argument correctly.
3380
1
      SawError = true;
3381
1
      cutOffParsing();
3382
1
      break;
3383
1
    }
3384
9.35M
    if (Expr.isInvalid()) {
3385
3.60k
      SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
3386
3.60k
      SawError = true;
3387
9.34M
    } else {
3388
9.34M
      Exprs.push_back(Expr.get());
3389
9.34M
    }
3390
3391
9.35M
    if (Tok.isNot(tok::comma))
3392
4.17M
      break;
3393
    // Move to the next argument, remember where the comma was.
3394
5.17M
    Token Comma = Tok;
3395
5.17M
    CommaLocs.push_back(ConsumeToken());
3396
3397
5.17M
    checkPotentialAngleBracketDelimiter(Comma);
3398
5.17M
  }
3399
4.17M
  if (SawError) {
3400
    // Ensure typos get diagnosed when errors were encountered while parsing the
3401
    // expression list.
3402
3.55k
    for (auto &E : Exprs) {
3403
3.19k
      ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
3404
3.19k
      if (Expr.isUsable()) 
E = Expr.get()2.46k
;
3405
3.19k
    }
3406
3.55k
  }
3407
4.17M
  return SawError;
3408
4.17M
}
3409
3410
/// ParseSimpleExpressionList - A simple comma-separated list of expressions,
3411
/// used for misc language extensions.
3412
///
3413
/// \verbatim
3414
///       simple-expression-list:
3415
///         assignment-expression
3416
///         simple-expression-list , assignment-expression
3417
/// \endverbatim
3418
bool
3419
Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
3420
304k
                                  SmallVectorImpl<SourceLocation> &CommaLocs) {
3421
327k
  while (true) {
3422
327k
    ExprResult Expr = ParseAssignmentExpression();
3423
327k
    if (Expr.isInvalid())
3424
7
      return true;
3425
3426
327k
    Exprs.push_back(Expr.get());
3427
3428
327k
    if (Tok.isNot(tok::comma))
3429
304k
      return false;
3430
3431
    // Move to the next argument, remember where the comma was.
3432
23.1k
    Token Comma = Tok;
3433
23.1k
    CommaLocs.push_back(ConsumeToken());
3434
3435
23.1k
    checkPotentialAngleBracketDelimiter(Comma);
3436
23.1k
  }
3437
304k
}
3438
3439
/// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
3440
///
3441
/// \verbatim
3442
/// [clang] block-id:
3443
/// [clang]   specifier-qualifier-list block-declarator
3444
/// \endverbatim
3445
340
void Parser::ParseBlockId(SourceLocation CaretLoc) {
3446
340
  if (Tok.is(tok::code_completion)) {
3447
1
    cutOffParsing();
3448
1
    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
3449
1
    return;
3450
1
  }
3451
3452
  // Parse the specifier-qualifier-list piece.
3453
339
  DeclSpec DS(AttrFactory);
3454
339
  ParseSpecifierQualifierList(DS);
3455
3456
  // Parse the block-declarator.
3457
339
  Declarator DeclaratorInfo(DS, DeclaratorContext::BlockLiteral);
3458
339
  DeclaratorInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
3459
339
  ParseDeclarator(DeclaratorInfo);
3460
3461
339
  MaybeParseGNUAttributes(DeclaratorInfo);
3462
3463
  // Inform sema that we are starting a block.
3464
339
  Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
3465
339
}
3466
3467
/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
3468
/// like ^(int x){ return x+1; }
3469
///
3470
/// \verbatim
3471
///         block-literal:
3472
/// [clang]   '^' block-args[opt] compound-statement
3473
/// [clang]   '^' block-id compound-statement
3474
/// [clang] block-args:
3475
/// [clang]   '(' parameter-list ')'
3476
/// \endverbatim
3477
3.05k
ExprResult Parser::ParseBlockLiteralExpression() {
3478
3.05k
  assert(Tok.is(tok::caret) && "block literal starts with ^");
3479
0
  SourceLocation CaretLoc = ConsumeToken();
3480
3481
3.05k
  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
3482
3.05k
                                "block literal parsing");
3483
3484
  // Enter a scope to hold everything within the block.  This includes the
3485
  // argument decls, decls within the compound expression, etc.  This also
3486
  // allows determining whether a variable reference inside the block is
3487
  // within or outside of the block.
3488
3.05k
  ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
3489
3.05k
                                  Scope::CompoundStmtScope | Scope::DeclScope);
3490
3491
  // Inform sema that we are starting a block.
3492
3.05k
  Actions.ActOnBlockStart(CaretLoc, getCurScope());
3493
3494
  // Parse the return type if present.
3495
3.05k
  DeclSpec DS(AttrFactory);
3496
3.05k
  Declarator ParamInfo(DS, DeclaratorContext::BlockLiteral);
3497
3.05k
  ParamInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
3498
  // FIXME: Since the return type isn't actually parsed, it can't be used to
3499
  // fill ParamInfo with an initial valid range, so do it manually.
3500
3.05k
  ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
3501
3502
  // If this block has arguments, parse them.  There is no ambiguity here with
3503
  // the expression case, because the expression case requires a parameter list.
3504
3.05k
  if (Tok.is(tok::l_paren)) {
3505
1.04k
    ParseParenDeclarator(ParamInfo);
3506
    // Parse the pieces after the identifier as if we had "int(...)".
3507
    // SetIdentifier sets the source range end, but in this case we're past
3508
    // that location.
3509
1.04k
    SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
3510
1.04k
    ParamInfo.SetIdentifier(nullptr, CaretLoc);
3511
1.04k
    ParamInfo.SetRangeEnd(Tmp);
3512
1.04k
    if (ParamInfo.isInvalidType()) {
3513
      // If there was an error parsing the arguments, they may have
3514
      // tried to use ^(x+y) which requires an argument list.  Just
3515
      // skip the whole block literal.
3516
0
      Actions.ActOnBlockError(CaretLoc, getCurScope());
3517
0
      return ExprError();
3518
0
    }
3519
3520
1.04k
    MaybeParseGNUAttributes(ParamInfo);
3521
3522
    // Inform sema that we are starting a block.
3523
1.04k
    Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3524
2.01k
  } else if (!Tok.is(tok::l_brace)) {
3525
340
    ParseBlockId(CaretLoc);
3526
1.67k
  } else {
3527
    // Otherwise, pretend we saw (void).
3528
1.67k
    SourceLocation NoLoc;
3529
1.67k
    ParamInfo.AddTypeInfo(
3530
1.67k
        DeclaratorChunk::getFunction(/*HasProto=*/true,
3531
1.67k
                                     /*IsAmbiguous=*/false,
3532
1.67k
                                     /*RParenLoc=*/NoLoc,
3533
1.67k
                                     /*ArgInfo=*/nullptr,
3534
1.67k
                                     /*NumParams=*/0,
3535
1.67k
                                     /*EllipsisLoc=*/NoLoc,
3536
1.67k
                                     /*RParenLoc=*/NoLoc,
3537
1.67k
                                     /*RefQualifierIsLvalueRef=*/true,
3538
1.67k
                                     /*RefQualifierLoc=*/NoLoc,
3539
1.67k
                                     /*MutableLoc=*/NoLoc, EST_None,
3540
1.67k
                                     /*ESpecRange=*/SourceRange(),
3541
1.67k
                                     /*Exceptions=*/nullptr,
3542
1.67k
                                     /*ExceptionRanges=*/nullptr,
3543
1.67k
                                     /*NumExceptions=*/0,
3544
1.67k
                                     /*NoexceptExpr=*/nullptr,
3545
1.67k
                                     /*ExceptionSpecTokens=*/nullptr,
3546
1.67k
                                     /*DeclsInPrototype=*/None, CaretLoc,
3547
1.67k
                                     CaretLoc, ParamInfo),
3548
1.67k
        CaretLoc);
3549
3550
1.67k
    MaybeParseGNUAttributes(ParamInfo);
3551
3552
    // Inform sema that we are starting a block.
3553
1.67k
    Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3554
1.67k
  }
3555
3556
3557
3.05k
  ExprResult Result(true);
3558
3.05k
  if (!Tok.is(tok::l_brace)) {
3559
    // Saw something like: ^expr
3560
131
    Diag(Tok, diag::err_expected_expression);
3561
131
    Actions.ActOnBlockError(CaretLoc, getCurScope());
3562
131
    return ExprError();
3563
131
  }
3564
3565
2.92k
  StmtResult Stmt(ParseCompoundStatementBody());
3566
2.92k
  BlockScope.Exit();
3567
2.92k
  if (!Stmt.isInvalid())
3568
2.92k
    Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
3569
0
  else
3570
0
    Actions.ActOnBlockError(CaretLoc, getCurScope());
3571
2.92k
  return Result;
3572
3.05k
}
3573
3574
/// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
3575
///
3576
///         '__objc_yes'
3577
///         '__objc_no'
3578
913
ExprResult Parser::ParseObjCBoolLiteral() {
3579
913
  tok::TokenKind Kind = Tok.getKind();
3580
913
  return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
3581
913
}
3582
3583
/// Validate availability spec list, emitting diagnostics if necessary. Returns
3584
/// true if invalid.
3585
static bool CheckAvailabilitySpecList(Parser &P,
3586
108
                                      ArrayRef<AvailabilitySpec> AvailSpecs) {
3587
108
  llvm::SmallSet<StringRef, 4> Platforms;
3588
108
  bool HasOtherPlatformSpec = false;
3589
108
  bool Valid = true;
3590
224
  for (const auto &Spec : AvailSpecs) {
3591
224
    if (Spec.isOtherPlatformSpec()) {
3592
107
      if (HasOtherPlatformSpec) {
3593
0
        P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
3594
0
        Valid = false;
3595
0
      }
3596
3597
107
      HasOtherPlatformSpec = true;
3598
107
      continue;
3599
107
    }
3600
3601
117
    bool Inserted = Platforms.insert(Spec.getPlatform()).second;
3602
117
    if (!Inserted) {
3603
      // Rule out multiple version specs referring to the same platform.
3604
      // For example, we emit an error for:
3605
      // @available(macos 10.10, macos 10.11, *)
3606
1
      StringRef Platform = Spec.getPlatform();
3607
1
      P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
3608
1
          << Spec.getEndLoc() << Platform;
3609
1
      Valid = false;
3610
1
    }
3611
117
  }
3612
3613
108
  if (!HasOtherPlatformSpec) {
3614
1
    SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
3615
1
    P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
3616
1
        << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
3617
1
    return true;
3618
1
  }
3619
3620
107
  return !Valid;
3621
108
}
3622
3623
/// Parse availability query specification.
3624
///
3625
///  availability-spec:
3626
///     '*'
3627
///     identifier version-tuple
3628
235
Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
3629
235
  if (Tok.is(tok::star)) {
3630
109
    return AvailabilitySpec(ConsumeToken());
3631
126
  } else {
3632
    // Parse the platform name.
3633
126
    if (Tok.is(tok::code_completion)) {
3634
2
      cutOffParsing();
3635
2
      Actions.CodeCompleteAvailabilityPlatformName();
3636
2
      return None;
3637
2
    }
3638
124
    if (Tok.isNot(tok::identifier)) {
3639
2
      Diag(Tok, diag::err_avail_query_expected_platform_name);
3640
2
      return None;
3641
2
    }
3642
3643
122
    IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
3644
122
    SourceRange VersionRange;
3645
122
    VersionTuple Version = ParseVersionTuple(VersionRange);
3646
3647
122
    if (Version.empty())
3648
1
      return None;
3649
3650
121
    StringRef GivenPlatform = PlatformIdentifier->Ident->getName();
3651
121
    StringRef Platform =
3652
121
        AvailabilityAttr::canonicalizePlatformName(GivenPlatform);
3653
3654
121
    if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
3655
3
      Diag(PlatformIdentifier->Loc,
3656
3
           diag::err_avail_query_unrecognized_platform_name)
3657
3
          << GivenPlatform;
3658
3
      return None;
3659
3
    }
3660
3661
118
    return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
3662
118
                            VersionRange.getEnd());
3663
121
  }
3664
235
}
3665
3666
116
ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
3667
116
  assert(Tok.is(tok::kw___builtin_available) ||
3668
116
         Tok.isObjCAtKeyword(tok::objc_available));
3669
3670
  // Eat the available or __builtin_available.
3671
0
  ConsumeToken();
3672
3673
116
  BalancedDelimiterTracker Parens(*this, tok::l_paren);
3674
116
  if (Parens.expectAndConsume())
3675
1
    return ExprError();
3676
3677
115
  SmallVector<AvailabilitySpec, 4> AvailSpecs;
3678
115
  bool HasError = false;
3679
235
  while (true) {
3680
235
    Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
3681
235
    if (!Spec)
3682
8
      HasError = true;
3683
227
    else
3684
227
      AvailSpecs.push_back(*Spec);
3685
3686
235
    if (!TryConsumeToken(tok::comma))
3687
115
      break;
3688
235
  }
3689
3690
115
  if (HasError) {
3691
7
    SkipUntil(tok::r_paren, StopAtSemi);
3692
7
    return ExprError();
3693
7
  }
3694
3695
108
  CheckAvailabilitySpecList(*this, AvailSpecs);
3696
3697
108
  if (Parens.consumeClose())
3698
0
    return ExprError();
3699
3700
108
  return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
3701
108
                                                Parens.getCloseLocation());
3702
108
}