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