xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaExprCXX.cpp (revision ba3c1f5972d7b90feb6e6da47905ff2757e0fe57)
1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
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 /// Implements semantic analysis for C++ expressions.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/Type.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Basic/AlignedAllocation.h"
27 #include "clang/Basic/DiagnosticSema.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Basic/TokenKinds.h"
31 #include "clang/Basic/TypeTraits.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "clang/Sema/SemaLambda.h"
41 #include "clang/Sema/Template.h"
42 #include "clang/Sema/TemplateDeduction.h"
43 #include "llvm/ADT/APInt.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/TypeSize.h"
47 #include <optional>
48 using namespace clang;
49 using namespace sema;
50 
51 /// Handle the result of the special case name lookup for inheriting
52 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
53 /// constructor names in member using declarations, even if 'X' is not the
54 /// name of the corresponding type.
55 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
56                                               SourceLocation NameLoc,
57                                               IdentifierInfo &Name) {
58   NestedNameSpecifier *NNS = SS.getScopeRep();
59 
60   // Convert the nested-name-specifier into a type.
61   QualType Type;
62   switch (NNS->getKind()) {
63   case NestedNameSpecifier::TypeSpec:
64   case NestedNameSpecifier::TypeSpecWithTemplate:
65     Type = QualType(NNS->getAsType(), 0);
66     break;
67 
68   case NestedNameSpecifier::Identifier:
69     // Strip off the last layer of the nested-name-specifier and build a
70     // typename type for it.
71     assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
72     Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
73                                         NNS->getAsIdentifier());
74     break;
75 
76   case NestedNameSpecifier::Global:
77   case NestedNameSpecifier::Super:
78   case NestedNameSpecifier::Namespace:
79   case NestedNameSpecifier::NamespaceAlias:
80     llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
81   }
82 
83   // This reference to the type is located entirely at the location of the
84   // final identifier in the qualified-id.
85   return CreateParsedType(Type,
86                           Context.getTrivialTypeSourceInfo(Type, NameLoc));
87 }
88 
89 ParsedType Sema::getConstructorName(IdentifierInfo &II,
90                                     SourceLocation NameLoc,
91                                     Scope *S, CXXScopeSpec &SS,
92                                     bool EnteringContext) {
93   CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
94   assert(CurClass && &II == CurClass->getIdentifier() &&
95          "not a constructor name");
96 
97   // When naming a constructor as a member of a dependent context (eg, in a
98   // friend declaration or an inherited constructor declaration), form an
99   // unresolved "typename" type.
100   if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
101     QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
102     return ParsedType::make(T);
103   }
104 
105   if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
106     return ParsedType();
107 
108   // Find the injected-class-name declaration. Note that we make no attempt to
109   // diagnose cases where the injected-class-name is shadowed: the only
110   // declaration that can validly shadow the injected-class-name is a
111   // non-static data member, and if the class contains both a non-static data
112   // member and a constructor then it is ill-formed (we check that in
113   // CheckCompletedCXXClass).
114   CXXRecordDecl *InjectedClassName = nullptr;
115   for (NamedDecl *ND : CurClass->lookup(&II)) {
116     auto *RD = dyn_cast<CXXRecordDecl>(ND);
117     if (RD && RD->isInjectedClassName()) {
118       InjectedClassName = RD;
119       break;
120     }
121   }
122   if (!InjectedClassName) {
123     if (!CurClass->isInvalidDecl()) {
124       // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
125       // properly. Work around it here for now.
126       Diag(SS.getLastQualifierNameLoc(),
127            diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
128     }
129     return ParsedType();
130   }
131 
132   QualType T = Context.getTypeDeclType(InjectedClassName);
133   DiagnoseUseOfDecl(InjectedClassName, NameLoc);
134   MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
135 
136   return ParsedType::make(T);
137 }
138 
139 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
140                                    IdentifierInfo &II,
141                                    SourceLocation NameLoc,
142                                    Scope *S, CXXScopeSpec &SS,
143                                    ParsedType ObjectTypePtr,
144                                    bool EnteringContext) {
145   // Determine where to perform name lookup.
146 
147   // FIXME: This area of the standard is very messy, and the current
148   // wording is rather unclear about which scopes we search for the
149   // destructor name; see core issues 399 and 555. Issue 399 in
150   // particular shows where the current description of destructor name
151   // lookup is completely out of line with existing practice, e.g.,
152   // this appears to be ill-formed:
153   //
154   //   namespace N {
155   //     template <typename T> struct S {
156   //       ~S();
157   //     };
158   //   }
159   //
160   //   void f(N::S<int>* s) {
161   //     s->N::S<int>::~S();
162   //   }
163   //
164   // See also PR6358 and PR6359.
165   //
166   // For now, we accept all the cases in which the name given could plausibly
167   // be interpreted as a correct destructor name, issuing off-by-default
168   // extension diagnostics on the cases that don't strictly conform to the
169   // C++20 rules. This basically means we always consider looking in the
170   // nested-name-specifier prefix, the complete nested-name-specifier, and
171   // the scope, and accept if we find the expected type in any of the three
172   // places.
173 
174   if (SS.isInvalid())
175     return nullptr;
176 
177   // Whether we've failed with a diagnostic already.
178   bool Failed = false;
179 
180   llvm::SmallVector<NamedDecl*, 8> FoundDecls;
181   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;
182 
183   // If we have an object type, it's because we are in a
184   // pseudo-destructor-expression or a member access expression, and
185   // we know what type we're looking for.
186   QualType SearchType =
187       ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
188 
189   auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
190     auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
191       auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
192       if (!Type)
193         return false;
194 
195       if (SearchType.isNull() || SearchType->isDependentType())
196         return true;
197 
198       QualType T = Context.getTypeDeclType(Type);
199       return Context.hasSameUnqualifiedType(T, SearchType);
200     };
201 
202     unsigned NumAcceptableResults = 0;
203     for (NamedDecl *D : Found) {
204       if (IsAcceptableResult(D))
205         ++NumAcceptableResults;
206 
207       // Don't list a class twice in the lookup failure diagnostic if it's
208       // found by both its injected-class-name and by the name in the enclosing
209       // scope.
210       if (auto *RD = dyn_cast<CXXRecordDecl>(D))
211         if (RD->isInjectedClassName())
212           D = cast<NamedDecl>(RD->getParent());
213 
214       if (FoundDeclSet.insert(D).second)
215         FoundDecls.push_back(D);
216     }
217 
218     // As an extension, attempt to "fix" an ambiguity by erasing all non-type
219     // results, and all non-matching results if we have a search type. It's not
220     // clear what the right behavior is if destructor lookup hits an ambiguity,
221     // but other compilers do generally accept at least some kinds of
222     // ambiguity.
223     if (Found.isAmbiguous() && NumAcceptableResults == 1) {
224       Diag(NameLoc, diag::ext_dtor_name_ambiguous);
225       LookupResult::Filter F = Found.makeFilter();
226       while (F.hasNext()) {
227         NamedDecl *D = F.next();
228         if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
229           Diag(D->getLocation(), diag::note_destructor_type_here)
230               << Context.getTypeDeclType(TD);
231         else
232           Diag(D->getLocation(), diag::note_destructor_nontype_here);
233 
234         if (!IsAcceptableResult(D))
235           F.erase();
236       }
237       F.done();
238     }
239 
240     if (Found.isAmbiguous())
241       Failed = true;
242 
243     if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
244       if (IsAcceptableResult(Type)) {
245         QualType T = Context.getTypeDeclType(Type);
246         MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
247         return CreateParsedType(Context.getElaboratedType(ETK_None, nullptr, T),
248                                 Context.getTrivialTypeSourceInfo(T, NameLoc));
249       }
250     }
251 
252     return nullptr;
253   };
254 
255   bool IsDependent = false;
256 
257   auto LookupInObjectType = [&]() -> ParsedType {
258     if (Failed || SearchType.isNull())
259       return nullptr;
260 
261     IsDependent |= SearchType->isDependentType();
262 
263     LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
264     DeclContext *LookupCtx = computeDeclContext(SearchType);
265     if (!LookupCtx)
266       return nullptr;
267     LookupQualifiedName(Found, LookupCtx);
268     return CheckLookupResult(Found);
269   };
270 
271   auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
272     if (Failed)
273       return nullptr;
274 
275     IsDependent |= isDependentScopeSpecifier(LookupSS);
276     DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
277     if (!LookupCtx)
278       return nullptr;
279 
280     LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
281     if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
282       Failed = true;
283       return nullptr;
284     }
285     LookupQualifiedName(Found, LookupCtx);
286     return CheckLookupResult(Found);
287   };
288 
289   auto LookupInScope = [&]() -> ParsedType {
290     if (Failed || !S)
291       return nullptr;
292 
293     LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
294     LookupName(Found, S);
295     return CheckLookupResult(Found);
296   };
297 
298   // C++2a [basic.lookup.qual]p6:
299   //   In a qualified-id of the form
300   //
301   //     nested-name-specifier[opt] type-name :: ~ type-name
302   //
303   //   the second type-name is looked up in the same scope as the first.
304   //
305   // We interpret this as meaning that if you do a dual-scope lookup for the
306   // first name, you also do a dual-scope lookup for the second name, per
307   // C++ [basic.lookup.classref]p4:
308   //
309   //   If the id-expression in a class member access is a qualified-id of the
310   //   form
311   //
312   //     class-name-or-namespace-name :: ...
313   //
314   //   the class-name-or-namespace-name following the . or -> is first looked
315   //   up in the class of the object expression and the name, if found, is used.
316   //   Otherwise, it is looked up in the context of the entire
317   //   postfix-expression.
318   //
319   // This looks in the same scopes as for an unqualified destructor name:
320   //
321   // C++ [basic.lookup.classref]p3:
322   //   If the unqualified-id is ~ type-name, the type-name is looked up
323   //   in the context of the entire postfix-expression. If the type T
324   //   of the object expression is of a class type C, the type-name is
325   //   also looked up in the scope of class C. At least one of the
326   //   lookups shall find a name that refers to cv T.
327   //
328   // FIXME: The intent is unclear here. Should type-name::~type-name look in
329   // the scope anyway if it finds a non-matching name declared in the class?
330   // If both lookups succeed and find a dependent result, which result should
331   // we retain? (Same question for p->~type-name().)
332 
333   if (NestedNameSpecifier *Prefix =
334       SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
335     // This is
336     //
337     //   nested-name-specifier type-name :: ~ type-name
338     //
339     // Look for the second type-name in the nested-name-specifier.
340     CXXScopeSpec PrefixSS;
341     PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
342     if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
343       return T;
344   } else {
345     // This is one of
346     //
347     //   type-name :: ~ type-name
348     //   ~ type-name
349     //
350     // Look in the scope and (if any) the object type.
351     if (ParsedType T = LookupInScope())
352       return T;
353     if (ParsedType T = LookupInObjectType())
354       return T;
355   }
356 
357   if (Failed)
358     return nullptr;
359 
360   if (IsDependent) {
361     // We didn't find our type, but that's OK: it's dependent anyway.
362 
363     // FIXME: What if we have no nested-name-specifier?
364     QualType T = CheckTypenameType(ETK_None, SourceLocation(),
365                                    SS.getWithLocInContext(Context),
366                                    II, NameLoc);
367     return ParsedType::make(T);
368   }
369 
370   // The remaining cases are all non-standard extensions imitating the behavior
371   // of various other compilers.
372   unsigned NumNonExtensionDecls = FoundDecls.size();
373 
374   if (SS.isSet()) {
375     // For compatibility with older broken C++ rules and existing code,
376     //
377     //   nested-name-specifier :: ~ type-name
378     //
379     // also looks for type-name within the nested-name-specifier.
380     if (ParsedType T = LookupInNestedNameSpec(SS)) {
381       Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
382           << SS.getRange()
383           << FixItHint::CreateInsertion(SS.getEndLoc(),
384                                         ("::" + II.getName()).str());
385       return T;
386     }
387 
388     // For compatibility with other compilers and older versions of Clang,
389     //
390     //   nested-name-specifier type-name :: ~ type-name
391     //
392     // also looks for type-name in the scope. Unfortunately, we can't
393     // reasonably apply this fallback for dependent nested-name-specifiers.
394     if (SS.getScopeRep()->getPrefix()) {
395       if (ParsedType T = LookupInScope()) {
396         Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
397             << FixItHint::CreateRemoval(SS.getRange());
398         Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
399             << GetTypeFromParser(T);
400         return T;
401       }
402     }
403   }
404 
405   // We didn't find anything matching; tell the user what we did find (if
406   // anything).
407 
408   // Don't tell the user about declarations we shouldn't have found.
409   FoundDecls.resize(NumNonExtensionDecls);
410 
411   // List types before non-types.
412   std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
413                    [](NamedDecl *A, NamedDecl *B) {
414                      return isa<TypeDecl>(A->getUnderlyingDecl()) >
415                             isa<TypeDecl>(B->getUnderlyingDecl());
416                    });
417 
418   // Suggest a fixit to properly name the destroyed type.
419   auto MakeFixItHint = [&]{
420     const CXXRecordDecl *Destroyed = nullptr;
421     // FIXME: If we have a scope specifier, suggest its last component?
422     if (!SearchType.isNull())
423       Destroyed = SearchType->getAsCXXRecordDecl();
424     else if (S)
425       Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
426     if (Destroyed)
427       return FixItHint::CreateReplacement(SourceRange(NameLoc),
428                                           Destroyed->getNameAsString());
429     return FixItHint();
430   };
431 
432   if (FoundDecls.empty()) {
433     // FIXME: Attempt typo-correction?
434     Diag(NameLoc, diag::err_undeclared_destructor_name)
435       << &II << MakeFixItHint();
436   } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
437     if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
438       assert(!SearchType.isNull() &&
439              "should only reject a type result if we have a search type");
440       QualType T = Context.getTypeDeclType(TD);
441       Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
442           << T << SearchType << MakeFixItHint();
443     } else {
444       Diag(NameLoc, diag::err_destructor_expr_nontype)
445           << &II << MakeFixItHint();
446     }
447   } else {
448     Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
449                                       : diag::err_destructor_expr_mismatch)
450         << &II << SearchType << MakeFixItHint();
451   }
452 
453   for (NamedDecl *FoundD : FoundDecls) {
454     if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
455       Diag(FoundD->getLocation(), diag::note_destructor_type_here)
456           << Context.getTypeDeclType(TD);
457     else
458       Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
459           << FoundD;
460   }
461 
462   return nullptr;
463 }
464 
465 ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
466                                               ParsedType ObjectType) {
467   if (DS.getTypeSpecType() == DeclSpec::TST_error)
468     return nullptr;
469 
470   if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
471     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
472     return nullptr;
473   }
474 
475   assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
476          "unexpected type in getDestructorType");
477   QualType T = BuildDecltypeType(DS.getRepAsExpr());
478 
479   // If we know the type of the object, check that the correct destructor
480   // type was named now; we can give better diagnostics this way.
481   QualType SearchType = GetTypeFromParser(ObjectType);
482   if (!SearchType.isNull() && !SearchType->isDependentType() &&
483       !Context.hasSameUnqualifiedType(T, SearchType)) {
484     Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
485       << T << SearchType;
486     return nullptr;
487   }
488 
489   return ParsedType::make(T);
490 }
491 
492 bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
493                                   const UnqualifiedId &Name, bool IsUDSuffix) {
494   assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
495   if (!IsUDSuffix) {
496     // [over.literal] p8
497     //
498     // double operator""_Bq(long double);  // OK: not a reserved identifier
499     // double operator"" _Bq(long double); // ill-formed, no diagnostic required
500     IdentifierInfo *II = Name.Identifier;
501     ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts());
502     SourceLocation Loc = Name.getEndLoc();
503     if (isReservedInAllContexts(Status) &&
504         !PP.getSourceManager().isInSystemHeader(Loc)) {
505       Diag(Loc, diag::warn_reserved_extern_symbol)
506           << II << static_cast<int>(Status)
507           << FixItHint::CreateReplacement(
508                  Name.getSourceRange(),
509                  (StringRef("operator\"\"") + II->getName()).str());
510     }
511   }
512 
513   if (!SS.isValid())
514     return false;
515 
516   switch (SS.getScopeRep()->getKind()) {
517   case NestedNameSpecifier::Identifier:
518   case NestedNameSpecifier::TypeSpec:
519   case NestedNameSpecifier::TypeSpecWithTemplate:
520     // Per C++11 [over.literal]p2, literal operators can only be declared at
521     // namespace scope. Therefore, this unqualified-id cannot name anything.
522     // Reject it early, because we have no AST representation for this in the
523     // case where the scope is dependent.
524     Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
525         << SS.getScopeRep();
526     return true;
527 
528   case NestedNameSpecifier::Global:
529   case NestedNameSpecifier::Super:
530   case NestedNameSpecifier::Namespace:
531   case NestedNameSpecifier::NamespaceAlias:
532     return false;
533   }
534 
535   llvm_unreachable("unknown nested name specifier kind");
536 }
537 
538 /// Build a C++ typeid expression with a type operand.
539 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
540                                 SourceLocation TypeidLoc,
541                                 TypeSourceInfo *Operand,
542                                 SourceLocation RParenLoc) {
543   // C++ [expr.typeid]p4:
544   //   The top-level cv-qualifiers of the lvalue expression or the type-id
545   //   that is the operand of typeid are always ignored.
546   //   If the type of the type-id is a class type or a reference to a class
547   //   type, the class shall be completely-defined.
548   Qualifiers Quals;
549   QualType T
550     = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
551                                       Quals);
552   if (T->getAs<RecordType>() &&
553       RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
554     return ExprError();
555 
556   if (T->isVariablyModifiedType())
557     return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
558 
559   if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
560     return ExprError();
561 
562   return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
563                                      SourceRange(TypeidLoc, RParenLoc));
564 }
565 
566 /// Build a C++ typeid expression with an expression operand.
567 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
568                                 SourceLocation TypeidLoc,
569                                 Expr *E,
570                                 SourceLocation RParenLoc) {
571   bool WasEvaluated = false;
572   if (E && !E->isTypeDependent()) {
573     if (E->hasPlaceholderType()) {
574       ExprResult result = CheckPlaceholderExpr(E);
575       if (result.isInvalid()) return ExprError();
576       E = result.get();
577     }
578 
579     QualType T = E->getType();
580     if (const RecordType *RecordT = T->getAs<RecordType>()) {
581       CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
582       // C++ [expr.typeid]p3:
583       //   [...] If the type of the expression is a class type, the class
584       //   shall be completely-defined.
585       if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
586         return ExprError();
587 
588       // C++ [expr.typeid]p3:
589       //   When typeid is applied to an expression other than an glvalue of a
590       //   polymorphic class type [...] [the] expression is an unevaluated
591       //   operand. [...]
592       if (RecordD->isPolymorphic() && E->isGLValue()) {
593         if (isUnevaluatedContext()) {
594           // The operand was processed in unevaluated context, switch the
595           // context and recheck the subexpression.
596           ExprResult Result = TransformToPotentiallyEvaluated(E);
597           if (Result.isInvalid())
598             return ExprError();
599           E = Result.get();
600         }
601 
602         // We require a vtable to query the type at run time.
603         MarkVTableUsed(TypeidLoc, RecordD);
604         WasEvaluated = true;
605       }
606     }
607 
608     ExprResult Result = CheckUnevaluatedOperand(E);
609     if (Result.isInvalid())
610       return ExprError();
611     E = Result.get();
612 
613     // C++ [expr.typeid]p4:
614     //   [...] If the type of the type-id is a reference to a possibly
615     //   cv-qualified type, the result of the typeid expression refers to a
616     //   std::type_info object representing the cv-unqualified referenced
617     //   type.
618     Qualifiers Quals;
619     QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
620     if (!Context.hasSameType(T, UnqualT)) {
621       T = UnqualT;
622       E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
623     }
624   }
625 
626   if (E->getType()->isVariablyModifiedType())
627     return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
628                      << E->getType());
629   else if (!inTemplateInstantiation() &&
630            E->HasSideEffects(Context, WasEvaluated)) {
631     // The expression operand for typeid is in an unevaluated expression
632     // context, so side effects could result in unintended consequences.
633     Diag(E->getExprLoc(), WasEvaluated
634                               ? diag::warn_side_effects_typeid
635                               : diag::warn_side_effects_unevaluated_context);
636   }
637 
638   return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
639                                      SourceRange(TypeidLoc, RParenLoc));
640 }
641 
642 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
643 ExprResult
644 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
645                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
646   // typeid is not supported in OpenCL.
647   if (getLangOpts().OpenCLCPlusPlus) {
648     return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
649                      << "typeid");
650   }
651 
652   // Find the std::type_info type.
653   if (!getStdNamespace())
654     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
655 
656   if (!CXXTypeInfoDecl) {
657     IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
658     LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
659     LookupQualifiedName(R, getStdNamespace());
660     CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
661     // Microsoft's typeinfo doesn't have type_info in std but in the global
662     // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
663     if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
664       LookupQualifiedName(R, Context.getTranslationUnitDecl());
665       CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
666     }
667     if (!CXXTypeInfoDecl)
668       return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
669   }
670 
671   if (!getLangOpts().RTTI) {
672     return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
673   }
674 
675   QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
676 
677   if (isType) {
678     // The operand is a type; handle it as such.
679     TypeSourceInfo *TInfo = nullptr;
680     QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
681                                    &TInfo);
682     if (T.isNull())
683       return ExprError();
684 
685     if (!TInfo)
686       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
687 
688     return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
689   }
690 
691   // The operand is an expression.
692   ExprResult Result =
693       BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
694 
695   if (!getLangOpts().RTTIData && !Result.isInvalid())
696     if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
697       if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
698         Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
699             << (getDiagnostics().getDiagnosticOptions().getFormat() ==
700                 DiagnosticOptions::MSVC);
701   return Result;
702 }
703 
704 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
705 /// a single GUID.
706 static void
707 getUuidAttrOfType(Sema &SemaRef, QualType QT,
708                   llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
709   // Optionally remove one level of pointer, reference or array indirection.
710   const Type *Ty = QT.getTypePtr();
711   if (QT->isPointerType() || QT->isReferenceType())
712     Ty = QT->getPointeeType().getTypePtr();
713   else if (QT->isArrayType())
714     Ty = Ty->getBaseElementTypeUnsafe();
715 
716   const auto *TD = Ty->getAsTagDecl();
717   if (!TD)
718     return;
719 
720   if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
721     UuidAttrs.insert(Uuid);
722     return;
723   }
724 
725   // __uuidof can grab UUIDs from template arguments.
726   if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
727     const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
728     for (const TemplateArgument &TA : TAL.asArray()) {
729       const UuidAttr *UuidForTA = nullptr;
730       if (TA.getKind() == TemplateArgument::Type)
731         getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
732       else if (TA.getKind() == TemplateArgument::Declaration)
733         getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
734 
735       if (UuidForTA)
736         UuidAttrs.insert(UuidForTA);
737     }
738   }
739 }
740 
741 /// Build a Microsoft __uuidof expression with a type operand.
742 ExprResult Sema::BuildCXXUuidof(QualType Type,
743                                 SourceLocation TypeidLoc,
744                                 TypeSourceInfo *Operand,
745                                 SourceLocation RParenLoc) {
746   MSGuidDecl *Guid = nullptr;
747   if (!Operand->getType()->isDependentType()) {
748     llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
749     getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
750     if (UuidAttrs.empty())
751       return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
752     if (UuidAttrs.size() > 1)
753       return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
754     Guid = UuidAttrs.back()->getGuidDecl();
755   }
756 
757   return new (Context)
758       CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
759 }
760 
761 /// Build a Microsoft __uuidof expression with an expression operand.
762 ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc,
763                                 Expr *E, SourceLocation RParenLoc) {
764   MSGuidDecl *Guid = nullptr;
765   if (!E->getType()->isDependentType()) {
766     if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
767       // A null pointer results in {00000000-0000-0000-0000-000000000000}.
768       Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{});
769     } else {
770       llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
771       getUuidAttrOfType(*this, E->getType(), UuidAttrs);
772       if (UuidAttrs.empty())
773         return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
774       if (UuidAttrs.size() > 1)
775         return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
776       Guid = UuidAttrs.back()->getGuidDecl();
777     }
778   }
779 
780   return new (Context)
781       CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
782 }
783 
784 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
785 ExprResult
786 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
787                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
788   QualType GuidType = Context.getMSGuidType();
789   GuidType.addConst();
790 
791   if (isType) {
792     // The operand is a type; handle it as such.
793     TypeSourceInfo *TInfo = nullptr;
794     QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
795                                    &TInfo);
796     if (T.isNull())
797       return ExprError();
798 
799     if (!TInfo)
800       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
801 
802     return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
803   }
804 
805   // The operand is an expression.
806   return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
807 }
808 
809 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
810 ExprResult
811 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
812   assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
813          "Unknown C++ Boolean value!");
814   return new (Context)
815       CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
816 }
817 
818 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
819 ExprResult
820 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
821   return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
822 }
823 
824 /// ActOnCXXThrow - Parse throw expressions.
825 ExprResult
826 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
827   bool IsThrownVarInScope = false;
828   if (Ex) {
829     // C++0x [class.copymove]p31:
830     //   When certain criteria are met, an implementation is allowed to omit the
831     //   copy/move construction of a class object [...]
832     //
833     //     - in a throw-expression, when the operand is the name of a
834     //       non-volatile automatic object (other than a function or catch-
835     //       clause parameter) whose scope does not extend beyond the end of the
836     //       innermost enclosing try-block (if there is one), the copy/move
837     //       operation from the operand to the exception object (15.1) can be
838     //       omitted by constructing the automatic object directly into the
839     //       exception object
840     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
841       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
842         if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
843           for( ; S; S = S->getParent()) {
844             if (S->isDeclScope(Var)) {
845               IsThrownVarInScope = true;
846               break;
847             }
848 
849             // FIXME: Many of the scope checks here seem incorrect.
850             if (S->getFlags() &
851                 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
852                  Scope::ObjCMethodScope | Scope::TryScope))
853               break;
854           }
855         }
856       }
857   }
858 
859   return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
860 }
861 
862 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
863                                bool IsThrownVarInScope) {
864   // Don't report an error if 'throw' is used in system headers.
865   if (!getLangOpts().CXXExceptions &&
866       !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
867     // Delay error emission for the OpenMP device code.
868     targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
869   }
870 
871   // Exceptions aren't allowed in CUDA device code.
872   if (getLangOpts().CUDA)
873     CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
874         << "throw" << CurrentCUDATarget();
875 
876   if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
877     Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
878 
879   if (Ex && !Ex->isTypeDependent()) {
880     // Initialize the exception result.  This implicitly weeds out
881     // abstract types or types with inaccessible copy constructors.
882 
883     // C++0x [class.copymove]p31:
884     //   When certain criteria are met, an implementation is allowed to omit the
885     //   copy/move construction of a class object [...]
886     //
887     //     - in a throw-expression, when the operand is the name of a
888     //       non-volatile automatic object (other than a function or
889     //       catch-clause
890     //       parameter) whose scope does not extend beyond the end of the
891     //       innermost enclosing try-block (if there is one), the copy/move
892     //       operation from the operand to the exception object (15.1) can be
893     //       omitted by constructing the automatic object directly into the
894     //       exception object
895     NamedReturnInfo NRInfo =
896         IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
897 
898     QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
899     if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
900       return ExprError();
901 
902     InitializedEntity Entity =
903         InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
904     ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
905     if (Res.isInvalid())
906       return ExprError();
907     Ex = Res.get();
908   }
909 
910   // PPC MMA non-pointer types are not allowed as throw expr types.
911   if (Ex && Context.getTargetInfo().getTriple().isPPC64())
912     CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
913 
914   return new (Context)
915       CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
916 }
917 
918 static void
919 collectPublicBases(CXXRecordDecl *RD,
920                    llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
921                    llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
922                    llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
923                    bool ParentIsPublic) {
924   for (const CXXBaseSpecifier &BS : RD->bases()) {
925     CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
926     bool NewSubobject;
927     // Virtual bases constitute the same subobject.  Non-virtual bases are
928     // always distinct subobjects.
929     if (BS.isVirtual())
930       NewSubobject = VBases.insert(BaseDecl).second;
931     else
932       NewSubobject = true;
933 
934     if (NewSubobject)
935       ++SubobjectsSeen[BaseDecl];
936 
937     // Only add subobjects which have public access throughout the entire chain.
938     bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
939     if (PublicPath)
940       PublicSubobjectsSeen.insert(BaseDecl);
941 
942     // Recurse on to each base subobject.
943     collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
944                        PublicPath);
945   }
946 }
947 
948 static void getUnambiguousPublicSubobjects(
949     CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
950   llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
951   llvm::SmallSet<CXXRecordDecl *, 2> VBases;
952   llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
953   SubobjectsSeen[RD] = 1;
954   PublicSubobjectsSeen.insert(RD);
955   collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
956                      /*ParentIsPublic=*/true);
957 
958   for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
959     // Skip ambiguous objects.
960     if (SubobjectsSeen[PublicSubobject] > 1)
961       continue;
962 
963     Objects.push_back(PublicSubobject);
964   }
965 }
966 
967 /// CheckCXXThrowOperand - Validate the operand of a throw.
968 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
969                                 QualType ExceptionObjectTy, Expr *E) {
970   //   If the type of the exception would be an incomplete type or a pointer
971   //   to an incomplete type other than (cv) void the program is ill-formed.
972   QualType Ty = ExceptionObjectTy;
973   bool isPointer = false;
974   if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
975     Ty = Ptr->getPointeeType();
976     isPointer = true;
977   }
978   if (!isPointer || !Ty->isVoidType()) {
979     if (RequireCompleteType(ThrowLoc, Ty,
980                             isPointer ? diag::err_throw_incomplete_ptr
981                                       : diag::err_throw_incomplete,
982                             E->getSourceRange()))
983       return true;
984 
985     if (!isPointer && Ty->isSizelessType()) {
986       Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
987       return true;
988     }
989 
990     if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
991                                diag::err_throw_abstract_type, E))
992       return true;
993   }
994 
995   // If the exception has class type, we need additional handling.
996   CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
997   if (!RD)
998     return false;
999 
1000   // If we are throwing a polymorphic class type or pointer thereof,
1001   // exception handling will make use of the vtable.
1002   MarkVTableUsed(ThrowLoc, RD);
1003 
1004   // If a pointer is thrown, the referenced object will not be destroyed.
1005   if (isPointer)
1006     return false;
1007 
1008   // If the class has a destructor, we must be able to call it.
1009   if (!RD->hasIrrelevantDestructor()) {
1010     if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
1011       MarkFunctionReferenced(E->getExprLoc(), Destructor);
1012       CheckDestructorAccess(E->getExprLoc(), Destructor,
1013                             PDiag(diag::err_access_dtor_exception) << Ty);
1014       if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
1015         return true;
1016     }
1017   }
1018 
1019   // The MSVC ABI creates a list of all types which can catch the exception
1020   // object.  This list also references the appropriate copy constructor to call
1021   // if the object is caught by value and has a non-trivial copy constructor.
1022   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1023     // We are only interested in the public, unambiguous bases contained within
1024     // the exception object.  Bases which are ambiguous or otherwise
1025     // inaccessible are not catchable types.
1026     llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1027     getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1028 
1029     for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1030       // Attempt to lookup the copy constructor.  Various pieces of machinery
1031       // will spring into action, like template instantiation, which means this
1032       // cannot be a simple walk of the class's decls.  Instead, we must perform
1033       // lookup and overload resolution.
1034       CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1035       if (!CD || CD->isDeleted())
1036         continue;
1037 
1038       // Mark the constructor referenced as it is used by this throw expression.
1039       MarkFunctionReferenced(E->getExprLoc(), CD);
1040 
1041       // Skip this copy constructor if it is trivial, we don't need to record it
1042       // in the catchable type data.
1043       if (CD->isTrivial())
1044         continue;
1045 
1046       // The copy constructor is non-trivial, create a mapping from this class
1047       // type to this constructor.
1048       // N.B.  The selection of copy constructor is not sensitive to this
1049       // particular throw-site.  Lookup will be performed at the catch-site to
1050       // ensure that the copy constructor is, in fact, accessible (via
1051       // friendship or any other means).
1052       Context.addCopyConstructorForExceptionObject(Subobject, CD);
1053 
1054       // We don't keep the instantiated default argument expressions around so
1055       // we must rebuild them here.
1056       for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1057         if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1058           return true;
1059       }
1060     }
1061   }
1062 
1063   // Under the Itanium C++ ABI, memory for the exception object is allocated by
1064   // the runtime with no ability for the compiler to request additional
1065   // alignment. Warn if the exception type requires alignment beyond the minimum
1066   // guaranteed by the target C++ runtime.
1067   if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
1068     CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1069     CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1070     if (ExnObjAlign < TypeAlign) {
1071       Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1072       Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1073           << Ty << (unsigned)TypeAlign.getQuantity()
1074           << (unsigned)ExnObjAlign.getQuantity();
1075     }
1076   }
1077 
1078   return false;
1079 }
1080 
1081 static QualType adjustCVQualifiersForCXXThisWithinLambda(
1082     ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1083     DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1084 
1085   QualType ClassType = ThisTy->getPointeeType();
1086   LambdaScopeInfo *CurLSI = nullptr;
1087   DeclContext *CurDC = CurSemaContext;
1088 
1089   // Iterate through the stack of lambdas starting from the innermost lambda to
1090   // the outermost lambda, checking if '*this' is ever captured by copy - since
1091   // that could change the cv-qualifiers of the '*this' object.
1092   // The object referred to by '*this' starts out with the cv-qualifiers of its
1093   // member function.  We then start with the innermost lambda and iterate
1094   // outward checking to see if any lambda performs a by-copy capture of '*this'
1095   // - and if so, any nested lambda must respect the 'constness' of that
1096   // capturing lamdbda's call operator.
1097   //
1098 
1099   // Since the FunctionScopeInfo stack is representative of the lexical
1100   // nesting of the lambda expressions during initial parsing (and is the best
1101   // place for querying information about captures about lambdas that are
1102   // partially processed) and perhaps during instantiation of function templates
1103   // that contain lambda expressions that need to be transformed BUT not
1104   // necessarily during instantiation of a nested generic lambda's function call
1105   // operator (which might even be instantiated at the end of the TU) - at which
1106   // time the DeclContext tree is mature enough to query capture information
1107   // reliably - we use a two pronged approach to walk through all the lexically
1108   // enclosing lambda expressions:
1109   //
1110   //  1) Climb down the FunctionScopeInfo stack as long as each item represents
1111   //  a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1112   //  enclosed by the call-operator of the LSI below it on the stack (while
1113   //  tracking the enclosing DC for step 2 if needed).  Note the topmost LSI on
1114   //  the stack represents the innermost lambda.
1115   //
1116   //  2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1117   //  represents a lambda's call operator.  If it does, we must be instantiating
1118   //  a generic lambda's call operator (represented by the Current LSI, and
1119   //  should be the only scenario where an inconsistency between the LSI and the
1120   //  DeclContext should occur), so climb out the DeclContexts if they
1121   //  represent lambdas, while querying the corresponding closure types
1122   //  regarding capture information.
1123 
1124   // 1) Climb down the function scope info stack.
1125   for (int I = FunctionScopes.size();
1126        I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1127        (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1128                        cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1129        CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1130     CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1131 
1132     if (!CurLSI->isCXXThisCaptured())
1133         continue;
1134 
1135     auto C = CurLSI->getCXXThisCapture();
1136 
1137     if (C.isCopyCapture()) {
1138       ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1139       if (CurLSI->CallOperator->isConst())
1140         ClassType.addConst();
1141       return ASTCtx.getPointerType(ClassType);
1142     }
1143   }
1144 
1145   // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1146   //    can happen during instantiation of its nested generic lambda call
1147   //    operator); 2. if we're in a lambda scope (lambda body).
1148   if (CurLSI && isLambdaCallOperator(CurDC)) {
1149     assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1150            "While computing 'this' capture-type for a generic lambda, when we "
1151            "run out of enclosing LSI's, yet the enclosing DC is a "
1152            "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1153            "lambda call oeprator");
1154     assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1155 
1156     auto IsThisCaptured =
1157         [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1158       IsConst = false;
1159       IsByCopy = false;
1160       for (auto &&C : Closure->captures()) {
1161         if (C.capturesThis()) {
1162           if (C.getCaptureKind() == LCK_StarThis)
1163             IsByCopy = true;
1164           if (Closure->getLambdaCallOperator()->isConst())
1165             IsConst = true;
1166           return true;
1167         }
1168       }
1169       return false;
1170     };
1171 
1172     bool IsByCopyCapture = false;
1173     bool IsConstCapture = false;
1174     CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1175     while (Closure &&
1176            IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1177       if (IsByCopyCapture) {
1178         ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1179         if (IsConstCapture)
1180           ClassType.addConst();
1181         return ASTCtx.getPointerType(ClassType);
1182       }
1183       Closure = isLambdaCallOperator(Closure->getParent())
1184                     ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1185                     : nullptr;
1186     }
1187   }
1188   return ASTCtx.getPointerType(ClassType);
1189 }
1190 
1191 QualType Sema::getCurrentThisType() {
1192   DeclContext *DC = getFunctionLevelDeclContext();
1193   QualType ThisTy = CXXThisTypeOverride;
1194 
1195   if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1196     if (method && method->isInstance())
1197       ThisTy = method->getThisType();
1198   }
1199 
1200   if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1201       inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
1202 
1203     // This is a lambda call operator that is being instantiated as a default
1204     // initializer. DC must point to the enclosing class type, so we can recover
1205     // the 'this' type from it.
1206     QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1207     // There are no cv-qualifiers for 'this' within default initializers,
1208     // per [expr.prim.general]p4.
1209     ThisTy = Context.getPointerType(ClassTy);
1210   }
1211 
1212   // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1213   // might need to be adjusted if the lambda or any of its enclosing lambda's
1214   // captures '*this' by copy.
1215   if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1216     return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1217                                                     CurContext, Context);
1218   return ThisTy;
1219 }
1220 
1221 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1222                                          Decl *ContextDecl,
1223                                          Qualifiers CXXThisTypeQuals,
1224                                          bool Enabled)
1225   : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1226 {
1227   if (!Enabled || !ContextDecl)
1228     return;
1229 
1230   CXXRecordDecl *Record = nullptr;
1231   if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1232     Record = Template->getTemplatedDecl();
1233   else
1234     Record = cast<CXXRecordDecl>(ContextDecl);
1235 
1236   QualType T = S.Context.getRecordType(Record);
1237   T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1238 
1239   S.CXXThisTypeOverride = S.Context.getPointerType(T);
1240 
1241   this->Enabled = true;
1242 }
1243 
1244 
1245 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1246   if (Enabled) {
1247     S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1248   }
1249 }
1250 
1251 static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) {
1252   SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1253   assert(!LSI->isCXXThisCaptured());
1254   //  [=, this] {};   // until C++20: Error: this when = is the default
1255   if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval &&
1256       !Sema.getLangOpts().CPlusPlus20)
1257     return;
1258   Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1259       << FixItHint::CreateInsertion(
1260              DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1261 }
1262 
1263 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1264     bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1265     const bool ByCopy) {
1266   // We don't need to capture this in an unevaluated context.
1267   if (isUnevaluatedContext() && !Explicit)
1268     return true;
1269 
1270   assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1271 
1272   const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1273                                          ? *FunctionScopeIndexToStopAt
1274                                          : FunctionScopes.size() - 1;
1275 
1276   // Check that we can capture the *enclosing object* (referred to by '*this')
1277   // by the capturing-entity/closure (lambda/block/etc) at
1278   // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1279 
1280   // Note: The *enclosing object* can only be captured by-value by a
1281   // closure that is a lambda, using the explicit notation:
1282   //    [*this] { ... }.
1283   // Every other capture of the *enclosing object* results in its by-reference
1284   // capture.
1285 
1286   // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1287   // stack), we can capture the *enclosing object* only if:
1288   // - 'L' has an explicit byref or byval capture of the *enclosing object*
1289   // -  or, 'L' has an implicit capture.
1290   // AND
1291   //   -- there is no enclosing closure
1292   //   -- or, there is some enclosing closure 'E' that has already captured the
1293   //      *enclosing object*, and every intervening closure (if any) between 'E'
1294   //      and 'L' can implicitly capture the *enclosing object*.
1295   //   -- or, every enclosing closure can implicitly capture the
1296   //      *enclosing object*
1297 
1298 
1299   unsigned NumCapturingClosures = 0;
1300   for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1301     if (CapturingScopeInfo *CSI =
1302             dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1303       if (CSI->CXXThisCaptureIndex != 0) {
1304         // 'this' is already being captured; there isn't anything more to do.
1305         CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1306         break;
1307       }
1308       LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1309       if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1310         // This context can't implicitly capture 'this'; fail out.
1311         if (BuildAndDiagnose) {
1312           Diag(Loc, diag::err_this_capture)
1313               << (Explicit && idx == MaxFunctionScopesIndex);
1314           if (!Explicit)
1315             buildLambdaThisCaptureFixit(*this, LSI);
1316         }
1317         return true;
1318       }
1319       if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1320           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1321           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1322           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1323           (Explicit && idx == MaxFunctionScopesIndex)) {
1324         // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1325         // iteration through can be an explicit capture, all enclosing closures,
1326         // if any, must perform implicit captures.
1327 
1328         // This closure can capture 'this'; continue looking upwards.
1329         NumCapturingClosures++;
1330         continue;
1331       }
1332       // This context can't implicitly capture 'this'; fail out.
1333       if (BuildAndDiagnose)
1334         Diag(Loc, diag::err_this_capture)
1335             << (Explicit && idx == MaxFunctionScopesIndex);
1336 
1337       if (!Explicit)
1338         buildLambdaThisCaptureFixit(*this, LSI);
1339       return true;
1340     }
1341     break;
1342   }
1343   if (!BuildAndDiagnose) return false;
1344 
1345   // If we got here, then the closure at MaxFunctionScopesIndex on the
1346   // FunctionScopes stack, can capture the *enclosing object*, so capture it
1347   // (including implicit by-reference captures in any enclosing closures).
1348 
1349   // In the loop below, respect the ByCopy flag only for the closure requesting
1350   // the capture (i.e. first iteration through the loop below).  Ignore it for
1351   // all enclosing closure's up to NumCapturingClosures (since they must be
1352   // implicitly capturing the *enclosing  object* by reference (see loop
1353   // above)).
1354   assert((!ByCopy ||
1355           isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1356          "Only a lambda can capture the enclosing object (referred to by "
1357          "*this) by copy");
1358   QualType ThisTy = getCurrentThisType();
1359   for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1360        --idx, --NumCapturingClosures) {
1361     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1362 
1363     // The type of the corresponding data member (not a 'this' pointer if 'by
1364     // copy').
1365     QualType CaptureType = ThisTy;
1366     if (ByCopy) {
1367       // If we are capturing the object referred to by '*this' by copy, ignore
1368       // any cv qualifiers inherited from the type of the member function for
1369       // the type of the closure-type's corresponding data member and any use
1370       // of 'this'.
1371       CaptureType = ThisTy->getPointeeType();
1372       CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1373     }
1374 
1375     bool isNested = NumCapturingClosures > 1;
1376     CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1377   }
1378   return false;
1379 }
1380 
1381 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1382   /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1383   /// is a non-lvalue expression whose value is the address of the object for
1384   /// which the function is called.
1385 
1386   QualType ThisTy = getCurrentThisType();
1387   if (ThisTy.isNull())
1388     return Diag(Loc, diag::err_invalid_this_use);
1389   return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1390 }
1391 
1392 Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1393                              bool IsImplicit) {
1394   if (getLangOpts().HLSL && Type.getTypePtr()->isPointerType()) {
1395     auto *This = new (Context)
1396         CXXThisExpr(Loc, Type.getTypePtr()->getPointeeType(), IsImplicit);
1397     This->setValueKind(ExprValueKind::VK_LValue);
1398     MarkThisReferenced(This);
1399     return This;
1400   }
1401   auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1402   MarkThisReferenced(This);
1403   return This;
1404 }
1405 
1406 void Sema::MarkThisReferenced(CXXThisExpr *This) {
1407   CheckCXXThisCapture(This->getExprLoc());
1408 }
1409 
1410 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1411   // If we're outside the body of a member function, then we'll have a specified
1412   // type for 'this'.
1413   if (CXXThisTypeOverride.isNull())
1414     return false;
1415 
1416   // Determine whether we're looking into a class that's currently being
1417   // defined.
1418   CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1419   return Class && Class->isBeingDefined();
1420 }
1421 
1422 /// Parse construction of a specified type.
1423 /// Can be interpreted either as function-style casting ("int(x)")
1424 /// or class type construction ("ClassType(x,y,z)")
1425 /// or creation of a value-initialized type ("int()").
1426 ExprResult
1427 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1428                                 SourceLocation LParenOrBraceLoc,
1429                                 MultiExprArg exprs,
1430                                 SourceLocation RParenOrBraceLoc,
1431                                 bool ListInitialization) {
1432   if (!TypeRep)
1433     return ExprError();
1434 
1435   TypeSourceInfo *TInfo;
1436   QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1437   if (!TInfo)
1438     TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1439 
1440   auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1441                                           RParenOrBraceLoc, ListInitialization);
1442   // Avoid creating a non-type-dependent expression that contains typos.
1443   // Non-type-dependent expressions are liable to be discarded without
1444   // checking for embedded typos.
1445   if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1446       !Result.get()->isTypeDependent())
1447     Result = CorrectDelayedTyposInExpr(Result.get());
1448   else if (Result.isInvalid())
1449     Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(),
1450                                 RParenOrBraceLoc, exprs, Ty);
1451   return Result;
1452 }
1453 
1454 ExprResult
1455 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1456                                 SourceLocation LParenOrBraceLoc,
1457                                 MultiExprArg Exprs,
1458                                 SourceLocation RParenOrBraceLoc,
1459                                 bool ListInitialization) {
1460   QualType Ty = TInfo->getType();
1461   SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1462 
1463   assert((!ListInitialization || Exprs.size() == 1) &&
1464          "List initialization must have exactly one expression.");
1465   SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1466 
1467   InitializedEntity Entity =
1468       InitializedEntity::InitializeTemporary(Context, TInfo);
1469   InitializationKind Kind =
1470       Exprs.size()
1471           ? ListInitialization
1472                 ? InitializationKind::CreateDirectList(
1473                       TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1474                 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1475                                                    RParenOrBraceLoc)
1476           : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1477                                             RParenOrBraceLoc);
1478 
1479   // C++1z [expr.type.conv]p1:
1480   //   If the type is a placeholder for a deduced class type, [...perform class
1481   //   template argument deduction...]
1482   // C++2b:
1483   //   Otherwise, if the type contains a placeholder type, it is replaced by the
1484   //   type determined by placeholder type deduction.
1485   DeducedType *Deduced = Ty->getContainedDeducedType();
1486   if (Deduced && !Deduced->isDeduced() &&
1487       isa<DeducedTemplateSpecializationType>(Deduced)) {
1488     Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1489                                                      Kind, Exprs);
1490     if (Ty.isNull())
1491       return ExprError();
1492     Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1493   } else if (Deduced && !Deduced->isDeduced()) {
1494     MultiExprArg Inits = Exprs;
1495     if (ListInitialization) {
1496       auto *ILE = cast<InitListExpr>(Exprs[0]);
1497       Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1498     }
1499 
1500     if (Inits.empty())
1501       return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1502                        << Ty << FullRange);
1503     if (Inits.size() > 1) {
1504       Expr *FirstBad = Inits[1];
1505       return ExprError(Diag(FirstBad->getBeginLoc(),
1506                             diag::err_auto_expr_init_multiple_expressions)
1507                        << Ty << FullRange);
1508     }
1509     if (getLangOpts().CPlusPlus2b) {
1510       if (Ty->getAs<AutoType>())
1511         Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1512     }
1513     Expr *Deduce = Inits[0];
1514     if (isa<InitListExpr>(Deduce))
1515       return ExprError(
1516           Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
1517           << ListInitialization << Ty << FullRange);
1518     QualType DeducedType;
1519     TemplateDeductionInfo Info(Deduce->getExprLoc());
1520     TemplateDeductionResult Result =
1521         DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);
1522     if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed)
1523       return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1524                        << Ty << Deduce->getType() << FullRange
1525                        << Deduce->getSourceRange());
1526     if (DeducedType.isNull()) {
1527       assert(Result == TDK_AlreadyDiagnosed);
1528       return ExprError();
1529     }
1530 
1531     Ty = DeducedType;
1532     Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1533   }
1534 
1535   if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
1536     // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1537     // directly. We work around this by dropping the locations of the braces.
1538     SourceRange Locs = ListInitialization
1539                            ? SourceRange()
1540                            : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1541     return CXXUnresolvedConstructExpr::Create(Context, Ty.getNonReferenceType(),
1542                                               TInfo, Locs.getBegin(), Exprs,
1543                                               Locs.getEnd());
1544   }
1545 
1546   // C++ [expr.type.conv]p1:
1547   // If the expression list is a parenthesized single expression, the type
1548   // conversion expression is equivalent (in definedness, and if defined in
1549   // meaning) to the corresponding cast expression.
1550   if (Exprs.size() == 1 && !ListInitialization &&
1551       !isa<InitListExpr>(Exprs[0])) {
1552     Expr *Arg = Exprs[0];
1553     return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1554                                       RParenOrBraceLoc);
1555   }
1556 
1557   //   For an expression of the form T(), T shall not be an array type.
1558   QualType ElemTy = Ty;
1559   if (Ty->isArrayType()) {
1560     if (!ListInitialization)
1561       return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1562                          << FullRange);
1563     ElemTy = Context.getBaseElementType(Ty);
1564   }
1565 
1566   // Only construct objects with object types.
1567   // The standard doesn't explicitly forbid function types here, but that's an
1568   // obvious oversight, as there's no way to dynamically construct a function
1569   // in general.
1570   if (Ty->isFunctionType())
1571     return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1572                        << Ty << FullRange);
1573 
1574   // C++17 [expr.type.conv]p2:
1575   //   If the type is cv void and the initializer is (), the expression is a
1576   //   prvalue of the specified type that performs no initialization.
1577   if (!Ty->isVoidType() &&
1578       RequireCompleteType(TyBeginLoc, ElemTy,
1579                           diag::err_invalid_incomplete_type_use, FullRange))
1580     return ExprError();
1581 
1582   //   Otherwise, the expression is a prvalue of the specified type whose
1583   //   result object is direct-initialized (11.6) with the initializer.
1584   InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1585   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1586 
1587   if (Result.isInvalid())
1588     return Result;
1589 
1590   Expr *Inner = Result.get();
1591   if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1592     Inner = BTE->getSubExpr();
1593   if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1594       !isa<CXXScalarValueInitExpr>(Inner)) {
1595     // If we created a CXXTemporaryObjectExpr, that node also represents the
1596     // functional cast. Otherwise, create an explicit cast to represent
1597     // the syntactic form of a functional-style cast that was used here.
1598     //
1599     // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1600     // would give a more consistent AST representation than using a
1601     // CXXTemporaryObjectExpr. It's also weird that the functional cast
1602     // is sometimes handled by initialization and sometimes not.
1603     QualType ResultType = Result.get()->getType();
1604     SourceRange Locs = ListInitialization
1605                            ? SourceRange()
1606                            : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1607     Result = CXXFunctionalCastExpr::Create(
1608         Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1609         Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1610         Locs.getBegin(), Locs.getEnd());
1611   }
1612 
1613   return Result;
1614 }
1615 
1616 bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1617   // [CUDA] Ignore this function, if we can't call it.
1618   const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1619   if (getLangOpts().CUDA) {
1620     auto CallPreference = IdentifyCUDAPreference(Caller, Method);
1621     // If it's not callable at all, it's not the right function.
1622     if (CallPreference < CFP_WrongSide)
1623       return false;
1624     if (CallPreference == CFP_WrongSide) {
1625       // Maybe. We have to check if there are better alternatives.
1626       DeclContext::lookup_result R =
1627           Method->getDeclContext()->lookup(Method->getDeclName());
1628       for (const auto *D : R) {
1629         if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1630           if (IdentifyCUDAPreference(Caller, FD) > CFP_WrongSide)
1631             return false;
1632         }
1633       }
1634       // We've found no better variants.
1635     }
1636   }
1637 
1638   SmallVector<const FunctionDecl*, 4> PreventedBy;
1639   bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1640 
1641   if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1642     return Result;
1643 
1644   // In case of CUDA, return true if none of the 1-argument deallocator
1645   // functions are actually callable.
1646   return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1647     assert(FD->getNumParams() == 1 &&
1648            "Only single-operand functions should be in PreventedBy");
1649     return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1650   });
1651 }
1652 
1653 /// Determine whether the given function is a non-placement
1654 /// deallocation function.
1655 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1656   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1657     return S.isUsualDeallocationFunction(Method);
1658 
1659   if (FD->getOverloadedOperator() != OO_Delete &&
1660       FD->getOverloadedOperator() != OO_Array_Delete)
1661     return false;
1662 
1663   unsigned UsualParams = 1;
1664 
1665   if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1666       S.Context.hasSameUnqualifiedType(
1667           FD->getParamDecl(UsualParams)->getType(),
1668           S.Context.getSizeType()))
1669     ++UsualParams;
1670 
1671   if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1672       S.Context.hasSameUnqualifiedType(
1673           FD->getParamDecl(UsualParams)->getType(),
1674           S.Context.getTypeDeclType(S.getStdAlignValT())))
1675     ++UsualParams;
1676 
1677   return UsualParams == FD->getNumParams();
1678 }
1679 
1680 namespace {
1681   struct UsualDeallocFnInfo {
1682     UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1683     UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1684         : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1685           Destroying(false), HasSizeT(false), HasAlignValT(false),
1686           CUDAPref(Sema::CFP_Native) {
1687       // A function template declaration is never a usual deallocation function.
1688       if (!FD)
1689         return;
1690       unsigned NumBaseParams = 1;
1691       if (FD->isDestroyingOperatorDelete()) {
1692         Destroying = true;
1693         ++NumBaseParams;
1694       }
1695 
1696       if (NumBaseParams < FD->getNumParams() &&
1697           S.Context.hasSameUnqualifiedType(
1698               FD->getParamDecl(NumBaseParams)->getType(),
1699               S.Context.getSizeType())) {
1700         ++NumBaseParams;
1701         HasSizeT = true;
1702       }
1703 
1704       if (NumBaseParams < FD->getNumParams() &&
1705           FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1706         ++NumBaseParams;
1707         HasAlignValT = true;
1708       }
1709 
1710       // In CUDA, determine how much we'd like / dislike to call this.
1711       if (S.getLangOpts().CUDA)
1712         if (auto *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
1713           CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1714     }
1715 
1716     explicit operator bool() const { return FD; }
1717 
1718     bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1719                       bool WantAlign) const {
1720       // C++ P0722:
1721       //   A destroying operator delete is preferred over a non-destroying
1722       //   operator delete.
1723       if (Destroying != Other.Destroying)
1724         return Destroying;
1725 
1726       // C++17 [expr.delete]p10:
1727       //   If the type has new-extended alignment, a function with a parameter
1728       //   of type std::align_val_t is preferred; otherwise a function without
1729       //   such a parameter is preferred
1730       if (HasAlignValT != Other.HasAlignValT)
1731         return HasAlignValT == WantAlign;
1732 
1733       if (HasSizeT != Other.HasSizeT)
1734         return HasSizeT == WantSize;
1735 
1736       // Use CUDA call preference as a tiebreaker.
1737       return CUDAPref > Other.CUDAPref;
1738     }
1739 
1740     DeclAccessPair Found;
1741     FunctionDecl *FD;
1742     bool Destroying, HasSizeT, HasAlignValT;
1743     Sema::CUDAFunctionPreference CUDAPref;
1744   };
1745 }
1746 
1747 /// Determine whether a type has new-extended alignment. This may be called when
1748 /// the type is incomplete (for a delete-expression with an incomplete pointee
1749 /// type), in which case it will conservatively return false if the alignment is
1750 /// not known.
1751 static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1752   return S.getLangOpts().AlignedAllocation &&
1753          S.getASTContext().getTypeAlignIfKnown(AllocType) >
1754              S.getASTContext().getTargetInfo().getNewAlign();
1755 }
1756 
1757 /// Select the correct "usual" deallocation function to use from a selection of
1758 /// deallocation functions (either global or class-scope).
1759 static UsualDeallocFnInfo resolveDeallocationOverload(
1760     Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1761     llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1762   UsualDeallocFnInfo Best;
1763 
1764   for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1765     UsualDeallocFnInfo Info(S, I.getPair());
1766     if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1767         Info.CUDAPref == Sema::CFP_Never)
1768       continue;
1769 
1770     if (!Best) {
1771       Best = Info;
1772       if (BestFns)
1773         BestFns->push_back(Info);
1774       continue;
1775     }
1776 
1777     if (Best.isBetterThan(Info, WantSize, WantAlign))
1778       continue;
1779 
1780     //   If more than one preferred function is found, all non-preferred
1781     //   functions are eliminated from further consideration.
1782     if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1783       BestFns->clear();
1784 
1785     Best = Info;
1786     if (BestFns)
1787       BestFns->push_back(Info);
1788   }
1789 
1790   return Best;
1791 }
1792 
1793 /// Determine whether a given type is a class for which 'delete[]' would call
1794 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1795 /// we need to store the array size (even if the type is
1796 /// trivially-destructible).
1797 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1798                                          QualType allocType) {
1799   const RecordType *record =
1800     allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1801   if (!record) return false;
1802 
1803   // Try to find an operator delete[] in class scope.
1804 
1805   DeclarationName deleteName =
1806     S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1807   LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1808   S.LookupQualifiedName(ops, record->getDecl());
1809 
1810   // We're just doing this for information.
1811   ops.suppressDiagnostics();
1812 
1813   // Very likely: there's no operator delete[].
1814   if (ops.empty()) return false;
1815 
1816   // If it's ambiguous, it should be illegal to call operator delete[]
1817   // on this thing, so it doesn't matter if we allocate extra space or not.
1818   if (ops.isAmbiguous()) return false;
1819 
1820   // C++17 [expr.delete]p10:
1821   //   If the deallocation functions have class scope, the one without a
1822   //   parameter of type std::size_t is selected.
1823   auto Best = resolveDeallocationOverload(
1824       S, ops, /*WantSize*/false,
1825       /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1826   return Best && Best.HasSizeT;
1827 }
1828 
1829 /// Parsed a C++ 'new' expression (C++ 5.3.4).
1830 ///
1831 /// E.g.:
1832 /// @code new (memory) int[size][4] @endcode
1833 /// or
1834 /// @code ::new Foo(23, "hello") @endcode
1835 ///
1836 /// \param StartLoc The first location of the expression.
1837 /// \param UseGlobal True if 'new' was prefixed with '::'.
1838 /// \param PlacementLParen Opening paren of the placement arguments.
1839 /// \param PlacementArgs Placement new arguments.
1840 /// \param PlacementRParen Closing paren of the placement arguments.
1841 /// \param TypeIdParens If the type is in parens, the source range.
1842 /// \param D The type to be allocated, as well as array dimensions.
1843 /// \param Initializer The initializing expression or initializer-list, or null
1844 ///   if there is none.
1845 ExprResult
1846 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1847                   SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1848                   SourceLocation PlacementRParen, SourceRange TypeIdParens,
1849                   Declarator &D, Expr *Initializer) {
1850   std::optional<Expr *> ArraySize;
1851   // If the specified type is an array, unwrap it and save the expression.
1852   if (D.getNumTypeObjects() > 0 &&
1853       D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1854     DeclaratorChunk &Chunk = D.getTypeObject(0);
1855     if (D.getDeclSpec().hasAutoTypeSpec())
1856       return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1857         << D.getSourceRange());
1858     if (Chunk.Arr.hasStatic)
1859       return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1860         << D.getSourceRange());
1861     if (!Chunk.Arr.NumElts && !Initializer)
1862       return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1863         << D.getSourceRange());
1864 
1865     ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1866     D.DropFirstTypeObject();
1867   }
1868 
1869   // Every dimension shall be of constant size.
1870   if (ArraySize) {
1871     for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1872       if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1873         break;
1874 
1875       DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1876       if (Expr *NumElts = (Expr *)Array.NumElts) {
1877         if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1878           // FIXME: GCC permits constant folding here. We should either do so consistently
1879           // or not do so at all, rather than changing behavior in C++14 onwards.
1880           if (getLangOpts().CPlusPlus14) {
1881             // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1882             //   shall be a converted constant expression (5.19) of type std::size_t
1883             //   and shall evaluate to a strictly positive value.
1884             llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1885             Array.NumElts
1886              = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1887                                                 CCEK_ArrayBound)
1888                  .get();
1889           } else {
1890             Array.NumElts =
1891                 VerifyIntegerConstantExpression(
1892                     NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
1893                     .get();
1894           }
1895           if (!Array.NumElts)
1896             return ExprError();
1897         }
1898       }
1899     }
1900   }
1901 
1902   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1903   QualType AllocType = TInfo->getType();
1904   if (D.isInvalidType())
1905     return ExprError();
1906 
1907   SourceRange DirectInitRange;
1908   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1909     DirectInitRange = List->getSourceRange();
1910 
1911   return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1912                      PlacementLParen, PlacementArgs, PlacementRParen,
1913                      TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1914                      Initializer);
1915 }
1916 
1917 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1918                                        Expr *Init) {
1919   if (!Init)
1920     return true;
1921   if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1922     return PLE->getNumExprs() == 0;
1923   if (isa<ImplicitValueInitExpr>(Init))
1924     return true;
1925   else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1926     return !CCE->isListInitialization() &&
1927            CCE->getConstructor()->isDefaultConstructor();
1928   else if (Style == CXXNewExpr::ListInit) {
1929     assert(isa<InitListExpr>(Init) &&
1930            "Shouldn't create list CXXConstructExprs for arrays.");
1931     return true;
1932   }
1933   return false;
1934 }
1935 
1936 bool
1937 Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1938   if (!getLangOpts().AlignedAllocationUnavailable)
1939     return false;
1940   if (FD.isDefined())
1941     return false;
1942   std::optional<unsigned> AlignmentParam;
1943   if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
1944       AlignmentParam)
1945     return true;
1946   return false;
1947 }
1948 
1949 // Emit a diagnostic if an aligned allocation/deallocation function that is not
1950 // implemented in the standard library is selected.
1951 void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1952                                                 SourceLocation Loc) {
1953   if (isUnavailableAlignedAllocationFunction(FD)) {
1954     const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1955     StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1956         getASTContext().getTargetInfo().getPlatformName());
1957     VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
1958 
1959     OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1960     bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1961     Diag(Loc, diag::err_aligned_allocation_unavailable)
1962         << IsDelete << FD.getType().getAsString() << OSName
1963         << OSVersion.getAsString() << OSVersion.empty();
1964     Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1965   }
1966 }
1967 
1968 ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1969                              SourceLocation PlacementLParen,
1970                              MultiExprArg PlacementArgs,
1971                              SourceLocation PlacementRParen,
1972                              SourceRange TypeIdParens, QualType AllocType,
1973                              TypeSourceInfo *AllocTypeInfo,
1974                              std::optional<Expr *> ArraySize,
1975                              SourceRange DirectInitRange, Expr *Initializer) {
1976   SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1977   SourceLocation StartLoc = Range.getBegin();
1978 
1979   CXXNewExpr::InitializationStyle initStyle;
1980   if (DirectInitRange.isValid()) {
1981     assert(Initializer && "Have parens but no initializer.");
1982     initStyle = CXXNewExpr::CallInit;
1983   } else if (Initializer && isa<InitListExpr>(Initializer))
1984     initStyle = CXXNewExpr::ListInit;
1985   else {
1986     assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1987             isa<CXXConstructExpr>(Initializer)) &&
1988            "Initializer expression that cannot have been implicitly created.");
1989     initStyle = CXXNewExpr::NoInit;
1990   }
1991 
1992   MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
1993   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1994     assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1995     Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
1996   }
1997 
1998   // C++11 [expr.new]p15:
1999   //   A new-expression that creates an object of type T initializes that
2000   //   object as follows:
2001   InitializationKind Kind
2002       //     - If the new-initializer is omitted, the object is default-
2003       //       initialized (8.5); if no initialization is performed,
2004       //       the object has indeterminate value
2005       = initStyle == CXXNewExpr::NoInit
2006             ? InitializationKind::CreateDefault(TypeRange.getBegin())
2007             //     - Otherwise, the new-initializer is interpreted according to
2008             //     the
2009             //       initialization rules of 8.5 for direct-initialization.
2010             : initStyle == CXXNewExpr::ListInit
2011                   ? InitializationKind::CreateDirectList(
2012                         TypeRange.getBegin(), Initializer->getBeginLoc(),
2013                         Initializer->getEndLoc())
2014                   : InitializationKind::CreateDirect(TypeRange.getBegin(),
2015                                                      DirectInitRange.getBegin(),
2016                                                      DirectInitRange.getEnd());
2017 
2018   // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2019   auto *Deduced = AllocType->getContainedDeducedType();
2020   if (Deduced && !Deduced->isDeduced() &&
2021       isa<DeducedTemplateSpecializationType>(Deduced)) {
2022     if (ArraySize)
2023       return ExprError(
2024           Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2025                diag::err_deduced_class_template_compound_type)
2026           << /*array*/ 2
2027           << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2028 
2029     InitializedEntity Entity
2030       = InitializedEntity::InitializeNew(StartLoc, AllocType);
2031     AllocType = DeduceTemplateSpecializationFromInitializer(
2032         AllocTypeInfo, Entity, Kind, Exprs);
2033     if (AllocType.isNull())
2034       return ExprError();
2035   } else if (Deduced && !Deduced->isDeduced()) {
2036     MultiExprArg Inits = Exprs;
2037     bool Braced = (initStyle == CXXNewExpr::ListInit);
2038     if (Braced) {
2039       auto *ILE = cast<InitListExpr>(Exprs[0]);
2040       Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2041     }
2042 
2043     if (initStyle == CXXNewExpr::NoInit || Inits.empty())
2044       return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2045                        << AllocType << TypeRange);
2046     if (Inits.size() > 1) {
2047       Expr *FirstBad = Inits[1];
2048       return ExprError(Diag(FirstBad->getBeginLoc(),
2049                             diag::err_auto_new_ctor_multiple_expressions)
2050                        << AllocType << TypeRange);
2051     }
2052     if (Braced && !getLangOpts().CPlusPlus17)
2053       Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2054           << AllocType << TypeRange;
2055     Expr *Deduce = Inits[0];
2056     if (isa<InitListExpr>(Deduce))
2057       return ExprError(
2058           Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2059           << Braced << AllocType << TypeRange);
2060     QualType DeducedType;
2061     TemplateDeductionInfo Info(Deduce->getExprLoc());
2062     TemplateDeductionResult Result =
2063         DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);
2064     if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed)
2065       return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2066                        << AllocType << Deduce->getType() << TypeRange
2067                        << Deduce->getSourceRange());
2068     if (DeducedType.isNull()) {
2069       assert(Result == TDK_AlreadyDiagnosed);
2070       return ExprError();
2071     }
2072     AllocType = DeducedType;
2073   }
2074 
2075   // Per C++0x [expr.new]p5, the type being constructed may be a
2076   // typedef of an array type.
2077   if (!ArraySize) {
2078     if (const ConstantArrayType *Array
2079                               = Context.getAsConstantArrayType(AllocType)) {
2080       ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2081                                          Context.getSizeType(),
2082                                          TypeRange.getEnd());
2083       AllocType = Array->getElementType();
2084     }
2085   }
2086 
2087   if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2088     return ExprError();
2089 
2090   if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))
2091     return ExprError();
2092 
2093   // In ARC, infer 'retaining' for the allocated
2094   if (getLangOpts().ObjCAutoRefCount &&
2095       AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2096       AllocType->isObjCLifetimeType()) {
2097     AllocType = Context.getLifetimeQualifiedType(AllocType,
2098                                     AllocType->getObjCARCImplicitLifetime());
2099   }
2100 
2101   QualType ResultType = Context.getPointerType(AllocType);
2102 
2103   if (ArraySize && *ArraySize &&
2104       (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2105     ExprResult result = CheckPlaceholderExpr(*ArraySize);
2106     if (result.isInvalid()) return ExprError();
2107     ArraySize = result.get();
2108   }
2109   // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2110   //   integral or enumeration type with a non-negative value."
2111   // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2112   //   enumeration type, or a class type for which a single non-explicit
2113   //   conversion function to integral or unscoped enumeration type exists.
2114   // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2115   //   std::size_t.
2116   std::optional<uint64_t> KnownArraySize;
2117   if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2118     ExprResult ConvertedSize;
2119     if (getLangOpts().CPlusPlus14) {
2120       assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2121 
2122       ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
2123                                                 AA_Converting);
2124 
2125       if (!ConvertedSize.isInvalid() &&
2126           (*ArraySize)->getType()->getAs<RecordType>())
2127         // Diagnose the compatibility of this conversion.
2128         Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2129           << (*ArraySize)->getType() << 0 << "'size_t'";
2130     } else {
2131       class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2132       protected:
2133         Expr *ArraySize;
2134 
2135       public:
2136         SizeConvertDiagnoser(Expr *ArraySize)
2137             : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2138               ArraySize(ArraySize) {}
2139 
2140         SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2141                                              QualType T) override {
2142           return S.Diag(Loc, diag::err_array_size_not_integral)
2143                    << S.getLangOpts().CPlusPlus11 << T;
2144         }
2145 
2146         SemaDiagnosticBuilder diagnoseIncomplete(
2147             Sema &S, SourceLocation Loc, QualType T) override {
2148           return S.Diag(Loc, diag::err_array_size_incomplete_type)
2149                    << T << ArraySize->getSourceRange();
2150         }
2151 
2152         SemaDiagnosticBuilder diagnoseExplicitConv(
2153             Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2154           return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2155         }
2156 
2157         SemaDiagnosticBuilder noteExplicitConv(
2158             Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2159           return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2160                    << ConvTy->isEnumeralType() << ConvTy;
2161         }
2162 
2163         SemaDiagnosticBuilder diagnoseAmbiguous(
2164             Sema &S, SourceLocation Loc, QualType T) override {
2165           return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2166         }
2167 
2168         SemaDiagnosticBuilder noteAmbiguous(
2169             Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2170           return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2171                    << ConvTy->isEnumeralType() << ConvTy;
2172         }
2173 
2174         SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2175                                                  QualType T,
2176                                                  QualType ConvTy) override {
2177           return S.Diag(Loc,
2178                         S.getLangOpts().CPlusPlus11
2179                           ? diag::warn_cxx98_compat_array_size_conversion
2180                           : diag::ext_array_size_conversion)
2181                    << T << ConvTy->isEnumeralType() << ConvTy;
2182         }
2183       } SizeDiagnoser(*ArraySize);
2184 
2185       ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2186                                                           SizeDiagnoser);
2187     }
2188     if (ConvertedSize.isInvalid())
2189       return ExprError();
2190 
2191     ArraySize = ConvertedSize.get();
2192     QualType SizeType = (*ArraySize)->getType();
2193 
2194     if (!SizeType->isIntegralOrUnscopedEnumerationType())
2195       return ExprError();
2196 
2197     // C++98 [expr.new]p7:
2198     //   The expression in a direct-new-declarator shall have integral type
2199     //   with a non-negative value.
2200     //
2201     // Let's see if this is a constant < 0. If so, we reject it out of hand,
2202     // per CWG1464. Otherwise, if it's not a constant, we must have an
2203     // unparenthesized array type.
2204 
2205     // We've already performed any required implicit conversion to integer or
2206     // unscoped enumeration type.
2207     // FIXME: Per CWG1464, we are required to check the value prior to
2208     // converting to size_t. This will never find a negative array size in
2209     // C++14 onwards, because Value is always unsigned here!
2210     if (std::optional<llvm::APSInt> Value =
2211             (*ArraySize)->getIntegerConstantExpr(Context)) {
2212       if (Value->isSigned() && Value->isNegative()) {
2213         return ExprError(Diag((*ArraySize)->getBeginLoc(),
2214                               diag::err_typecheck_negative_array_size)
2215                          << (*ArraySize)->getSourceRange());
2216       }
2217 
2218       if (!AllocType->isDependentType()) {
2219         unsigned ActiveSizeBits =
2220             ConstantArrayType::getNumAddressingBits(Context, AllocType, *Value);
2221         if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2222           return ExprError(
2223               Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2224               << toString(*Value, 10) << (*ArraySize)->getSourceRange());
2225       }
2226 
2227       KnownArraySize = Value->getZExtValue();
2228     } else if (TypeIdParens.isValid()) {
2229       // Can't have dynamic array size when the type-id is in parentheses.
2230       Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2231           << (*ArraySize)->getSourceRange()
2232           << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2233           << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2234 
2235       TypeIdParens = SourceRange();
2236     }
2237 
2238     // Note that we do *not* convert the argument in any way.  It can
2239     // be signed, larger than size_t, whatever.
2240   }
2241 
2242   FunctionDecl *OperatorNew = nullptr;
2243   FunctionDecl *OperatorDelete = nullptr;
2244   unsigned Alignment =
2245       AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2246   unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2247   bool PassAlignment = getLangOpts().AlignedAllocation &&
2248                        Alignment > NewAlignment;
2249 
2250   AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
2251   if (!AllocType->isDependentType() &&
2252       !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2253       FindAllocationFunctions(
2254           StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2255           AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs,
2256           OperatorNew, OperatorDelete))
2257     return ExprError();
2258 
2259   // If this is an array allocation, compute whether the usual array
2260   // deallocation function for the type has a size_t parameter.
2261   bool UsualArrayDeleteWantsSize = false;
2262   if (ArraySize && !AllocType->isDependentType())
2263     UsualArrayDeleteWantsSize =
2264         doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2265 
2266   SmallVector<Expr *, 8> AllPlaceArgs;
2267   if (OperatorNew) {
2268     auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2269     VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2270                                                     : VariadicDoesNotApply;
2271 
2272     // We've already converted the placement args, just fill in any default
2273     // arguments. Skip the first parameter because we don't have a corresponding
2274     // argument. Skip the second parameter too if we're passing in the
2275     // alignment; we've already filled it in.
2276     unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
2277     if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2278                                NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2279                                CallType))
2280       return ExprError();
2281 
2282     if (!AllPlaceArgs.empty())
2283       PlacementArgs = AllPlaceArgs;
2284 
2285     // We would like to perform some checking on the given `operator new` call,
2286     // but the PlacementArgs does not contain the implicit arguments,
2287     // namely allocation size and maybe allocation alignment,
2288     // so we need to conjure them.
2289 
2290     QualType SizeTy = Context.getSizeType();
2291     unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2292 
2293     llvm::APInt SingleEltSize(
2294         SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2295 
2296     // How many bytes do we want to allocate here?
2297     std::optional<llvm::APInt> AllocationSize;
2298     if (!ArraySize && !AllocType->isDependentType()) {
2299       // For non-array operator new, we only want to allocate one element.
2300       AllocationSize = SingleEltSize;
2301     } else if (KnownArraySize && !AllocType->isDependentType()) {
2302       // For array operator new, only deal with static array size case.
2303       bool Overflow;
2304       AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2305                            .umul_ov(SingleEltSize, Overflow);
2306       (void)Overflow;
2307       assert(
2308           !Overflow &&
2309           "Expected that all the overflows would have been handled already.");
2310     }
2311 
2312     IntegerLiteral AllocationSizeLiteral(
2313         Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2314         SizeTy, SourceLocation());
2315     // Otherwise, if we failed to constant-fold the allocation size, we'll
2316     // just give up and pass-in something opaque, that isn't a null pointer.
2317     OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,
2318                                          OK_Ordinary, /*SourceExpr=*/nullptr);
2319 
2320     // Let's synthesize the alignment argument in case we will need it.
2321     // Since we *really* want to allocate these on stack, this is slightly ugly
2322     // because there might not be a `std::align_val_t` type.
2323     EnumDecl *StdAlignValT = getStdAlignValT();
2324     QualType AlignValT =
2325         StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy;
2326     IntegerLiteral AlignmentLiteral(
2327         Context,
2328         llvm::APInt(Context.getTypeSize(SizeTy),
2329                     Alignment / Context.getCharWidth()),
2330         SizeTy, SourceLocation());
2331     ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2332                                       CK_IntegralCast, &AlignmentLiteral,
2333                                       VK_PRValue, FPOptionsOverride());
2334 
2335     // Adjust placement args by prepending conjured size and alignment exprs.
2336     llvm::SmallVector<Expr *, 8> CallArgs;
2337     CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2338     CallArgs.emplace_back(AllocationSize
2339                               ? static_cast<Expr *>(&AllocationSizeLiteral)
2340                               : &OpaqueAllocationSize);
2341     if (PassAlignment)
2342       CallArgs.emplace_back(&DesiredAlignment);
2343     CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2344 
2345     DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2346 
2347     checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2348               /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2349 
2350     // Warn if the type is over-aligned and is being allocated by (unaligned)
2351     // global operator new.
2352     if (PlacementArgs.empty() && !PassAlignment &&
2353         (OperatorNew->isImplicit() ||
2354          (OperatorNew->getBeginLoc().isValid() &&
2355           getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2356       if (Alignment > NewAlignment)
2357         Diag(StartLoc, diag::warn_overaligned_type)
2358             << AllocType
2359             << unsigned(Alignment / Context.getCharWidth())
2360             << unsigned(NewAlignment / Context.getCharWidth());
2361     }
2362   }
2363 
2364   // Array 'new' can't have any initializers except empty parentheses.
2365   // Initializer lists are also allowed, in C++11. Rely on the parser for the
2366   // dialect distinction.
2367   if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2368     SourceRange InitRange(Exprs.front()->getBeginLoc(),
2369                           Exprs.back()->getEndLoc());
2370     Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2371     return ExprError();
2372   }
2373 
2374   // If we can perform the initialization, and we've not already done so,
2375   // do it now.
2376   if (!AllocType->isDependentType() &&
2377       !Expr::hasAnyTypeDependentArguments(Exprs)) {
2378     // The type we initialize is the complete type, including the array bound.
2379     QualType InitType;
2380     if (KnownArraySize)
2381       InitType = Context.getConstantArrayType(
2382           AllocType,
2383           llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2384                       *KnownArraySize),
2385           *ArraySize, ArrayType::Normal, 0);
2386     else if (ArraySize)
2387       InitType =
2388           Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2389     else
2390       InitType = AllocType;
2391 
2392     InitializedEntity Entity
2393       = InitializedEntity::InitializeNew(StartLoc, InitType);
2394     InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2395     ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2396     if (FullInit.isInvalid())
2397       return ExprError();
2398 
2399     // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2400     // we don't want the initialized object to be destructed.
2401     // FIXME: We should not create these in the first place.
2402     if (CXXBindTemporaryExpr *Binder =
2403             dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2404       FullInit = Binder->getSubExpr();
2405 
2406     Initializer = FullInit.get();
2407 
2408     // FIXME: If we have a KnownArraySize, check that the array bound of the
2409     // initializer is no greater than that constant value.
2410 
2411     if (ArraySize && !*ArraySize) {
2412       auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2413       if (CAT) {
2414         // FIXME: Track that the array size was inferred rather than explicitly
2415         // specified.
2416         ArraySize = IntegerLiteral::Create(
2417             Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2418       } else {
2419         Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2420             << Initializer->getSourceRange();
2421       }
2422     }
2423   }
2424 
2425   // Mark the new and delete operators as referenced.
2426   if (OperatorNew) {
2427     if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2428       return ExprError();
2429     MarkFunctionReferenced(StartLoc, OperatorNew);
2430   }
2431   if (OperatorDelete) {
2432     if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2433       return ExprError();
2434     MarkFunctionReferenced(StartLoc, OperatorDelete);
2435   }
2436 
2437   return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2438                             PassAlignment, UsualArrayDeleteWantsSize,
2439                             PlacementArgs, TypeIdParens, ArraySize, initStyle,
2440                             Initializer, ResultType, AllocTypeInfo, Range,
2441                             DirectInitRange);
2442 }
2443 
2444 /// Checks that a type is suitable as the allocated type
2445 /// in a new-expression.
2446 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2447                               SourceRange R) {
2448   // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2449   //   abstract class type or array thereof.
2450   if (AllocType->isFunctionType())
2451     return Diag(Loc, diag::err_bad_new_type)
2452       << AllocType << 0 << R;
2453   else if (AllocType->isReferenceType())
2454     return Diag(Loc, diag::err_bad_new_type)
2455       << AllocType << 1 << R;
2456   else if (!AllocType->isDependentType() &&
2457            RequireCompleteSizedType(
2458                Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2459     return true;
2460   else if (RequireNonAbstractType(Loc, AllocType,
2461                                   diag::err_allocation_of_abstract_type))
2462     return true;
2463   else if (AllocType->isVariablyModifiedType())
2464     return Diag(Loc, diag::err_variably_modified_new_type)
2465              << AllocType;
2466   else if (AllocType.getAddressSpace() != LangAS::Default &&
2467            !getLangOpts().OpenCLCPlusPlus)
2468     return Diag(Loc, diag::err_address_space_qualified_new)
2469       << AllocType.getUnqualifiedType()
2470       << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2471   else if (getLangOpts().ObjCAutoRefCount) {
2472     if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2473       QualType BaseAllocType = Context.getBaseElementType(AT);
2474       if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2475           BaseAllocType->isObjCLifetimeType())
2476         return Diag(Loc, diag::err_arc_new_array_without_ownership)
2477           << BaseAllocType;
2478     }
2479   }
2480 
2481   return false;
2482 }
2483 
2484 static bool resolveAllocationOverload(
2485     Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2486     bool &PassAlignment, FunctionDecl *&Operator,
2487     OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2488   OverloadCandidateSet Candidates(R.getNameLoc(),
2489                                   OverloadCandidateSet::CSK_Normal);
2490   for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2491        Alloc != AllocEnd; ++Alloc) {
2492     // Even member operator new/delete are implicitly treated as
2493     // static, so don't use AddMemberCandidate.
2494     NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2495 
2496     if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2497       S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2498                                      /*ExplicitTemplateArgs=*/nullptr, Args,
2499                                      Candidates,
2500                                      /*SuppressUserConversions=*/false);
2501       continue;
2502     }
2503 
2504     FunctionDecl *Fn = cast<FunctionDecl>(D);
2505     S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2506                            /*SuppressUserConversions=*/false);
2507   }
2508 
2509   // Do the resolution.
2510   OverloadCandidateSet::iterator Best;
2511   switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2512   case OR_Success: {
2513     // Got one!
2514     FunctionDecl *FnDecl = Best->Function;
2515     if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2516                                 Best->FoundDecl) == Sema::AR_inaccessible)
2517       return true;
2518 
2519     Operator = FnDecl;
2520     return false;
2521   }
2522 
2523   case OR_No_Viable_Function:
2524     // C++17 [expr.new]p13:
2525     //   If no matching function is found and the allocated object type has
2526     //   new-extended alignment, the alignment argument is removed from the
2527     //   argument list, and overload resolution is performed again.
2528     if (PassAlignment) {
2529       PassAlignment = false;
2530       AlignArg = Args[1];
2531       Args.erase(Args.begin() + 1);
2532       return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2533                                        Operator, &Candidates, AlignArg,
2534                                        Diagnose);
2535     }
2536 
2537     // MSVC will fall back on trying to find a matching global operator new
2538     // if operator new[] cannot be found.  Also, MSVC will leak by not
2539     // generating a call to operator delete or operator delete[], but we
2540     // will not replicate that bug.
2541     // FIXME: Find out how this interacts with the std::align_val_t fallback
2542     // once MSVC implements it.
2543     if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2544         S.Context.getLangOpts().MSVCCompat) {
2545       R.clear();
2546       R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2547       S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2548       // FIXME: This will give bad diagnostics pointing at the wrong functions.
2549       return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2550                                        Operator, /*Candidates=*/nullptr,
2551                                        /*AlignArg=*/nullptr, Diagnose);
2552     }
2553 
2554     if (Diagnose) {
2555       // If this is an allocation of the form 'new (p) X' for some object
2556       // pointer p (or an expression that will decay to such a pointer),
2557       // diagnose the missing inclusion of <new>.
2558       if (!R.isClassLookup() && Args.size() == 2 &&
2559           (Args[1]->getType()->isObjectPointerType() ||
2560            Args[1]->getType()->isArrayType())) {
2561         S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2562             << R.getLookupName() << Range;
2563         // Listing the candidates is unlikely to be useful; skip it.
2564         return true;
2565       }
2566 
2567       // Finish checking all candidates before we note any. This checking can
2568       // produce additional diagnostics so can't be interleaved with our
2569       // emission of notes.
2570       //
2571       // For an aligned allocation, separately check the aligned and unaligned
2572       // candidates with their respective argument lists.
2573       SmallVector<OverloadCandidate*, 32> Cands;
2574       SmallVector<OverloadCandidate*, 32> AlignedCands;
2575       llvm::SmallVector<Expr*, 4> AlignedArgs;
2576       if (AlignedCandidates) {
2577         auto IsAligned = [](OverloadCandidate &C) {
2578           return C.Function->getNumParams() > 1 &&
2579                  C.Function->getParamDecl(1)->getType()->isAlignValT();
2580         };
2581         auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2582 
2583         AlignedArgs.reserve(Args.size() + 1);
2584         AlignedArgs.push_back(Args[0]);
2585         AlignedArgs.push_back(AlignArg);
2586         AlignedArgs.append(Args.begin() + 1, Args.end());
2587         AlignedCands = AlignedCandidates->CompleteCandidates(
2588             S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2589 
2590         Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2591                                               R.getNameLoc(), IsUnaligned);
2592       } else {
2593         Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2594                                               R.getNameLoc());
2595       }
2596 
2597       S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2598           << R.getLookupName() << Range;
2599       if (AlignedCandidates)
2600         AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2601                                           R.getNameLoc());
2602       Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2603     }
2604     return true;
2605 
2606   case OR_Ambiguous:
2607     if (Diagnose) {
2608       Candidates.NoteCandidates(
2609           PartialDiagnosticAt(R.getNameLoc(),
2610                               S.PDiag(diag::err_ovl_ambiguous_call)
2611                                   << R.getLookupName() << Range),
2612           S, OCD_AmbiguousCandidates, Args);
2613     }
2614     return true;
2615 
2616   case OR_Deleted: {
2617     if (Diagnose) {
2618       Candidates.NoteCandidates(
2619           PartialDiagnosticAt(R.getNameLoc(),
2620                               S.PDiag(diag::err_ovl_deleted_call)
2621                                   << R.getLookupName() << Range),
2622           S, OCD_AllCandidates, Args);
2623     }
2624     return true;
2625   }
2626   }
2627   llvm_unreachable("Unreachable, bad result from BestViableFunction");
2628 }
2629 
2630 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2631                                    AllocationFunctionScope NewScope,
2632                                    AllocationFunctionScope DeleteScope,
2633                                    QualType AllocType, bool IsArray,
2634                                    bool &PassAlignment, MultiExprArg PlaceArgs,
2635                                    FunctionDecl *&OperatorNew,
2636                                    FunctionDecl *&OperatorDelete,
2637                                    bool Diagnose) {
2638   // --- Choosing an allocation function ---
2639   // C++ 5.3.4p8 - 14 & 18
2640   // 1) If looking in AFS_Global scope for allocation functions, only look in
2641   //    the global scope. Else, if AFS_Class, only look in the scope of the
2642   //    allocated class. If AFS_Both, look in both.
2643   // 2) If an array size is given, look for operator new[], else look for
2644   //   operator new.
2645   // 3) The first argument is always size_t. Append the arguments from the
2646   //   placement form.
2647 
2648   SmallVector<Expr*, 8> AllocArgs;
2649   AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2650 
2651   // We don't care about the actual value of these arguments.
2652   // FIXME: Should the Sema create the expression and embed it in the syntax
2653   // tree? Or should the consumer just recalculate the value?
2654   // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2655   IntegerLiteral Size(
2656       Context,
2657       llvm::APInt::getZero(
2658           Context.getTargetInfo().getPointerWidth(LangAS::Default)),
2659       Context.getSizeType(), SourceLocation());
2660   AllocArgs.push_back(&Size);
2661 
2662   QualType AlignValT = Context.VoidTy;
2663   if (PassAlignment) {
2664     DeclareGlobalNewDelete();
2665     AlignValT = Context.getTypeDeclType(getStdAlignValT());
2666   }
2667   CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2668   if (PassAlignment)
2669     AllocArgs.push_back(&Align);
2670 
2671   AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2672 
2673   // C++ [expr.new]p8:
2674   //   If the allocated type is a non-array type, the allocation
2675   //   function's name is operator new and the deallocation function's
2676   //   name is operator delete. If the allocated type is an array
2677   //   type, the allocation function's name is operator new[] and the
2678   //   deallocation function's name is operator delete[].
2679   DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2680       IsArray ? OO_Array_New : OO_New);
2681 
2682   QualType AllocElemType = Context.getBaseElementType(AllocType);
2683 
2684   // Find the allocation function.
2685   {
2686     LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2687 
2688     // C++1z [expr.new]p9:
2689     //   If the new-expression begins with a unary :: operator, the allocation
2690     //   function's name is looked up in the global scope. Otherwise, if the
2691     //   allocated type is a class type T or array thereof, the allocation
2692     //   function's name is looked up in the scope of T.
2693     if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2694       LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2695 
2696     // We can see ambiguity here if the allocation function is found in
2697     // multiple base classes.
2698     if (R.isAmbiguous())
2699       return true;
2700 
2701     //   If this lookup fails to find the name, or if the allocated type is not
2702     //   a class type, the allocation function's name is looked up in the
2703     //   global scope.
2704     if (R.empty()) {
2705       if (NewScope == AFS_Class)
2706         return true;
2707 
2708       LookupQualifiedName(R, Context.getTranslationUnitDecl());
2709     }
2710 
2711     if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2712       if (PlaceArgs.empty()) {
2713         Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2714       } else {
2715         Diag(StartLoc, diag::err_openclcxx_placement_new);
2716       }
2717       return true;
2718     }
2719 
2720     assert(!R.empty() && "implicitly declared allocation functions not found");
2721     assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2722 
2723     // We do our own custom access checks below.
2724     R.suppressDiagnostics();
2725 
2726     if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2727                                   OperatorNew, /*Candidates=*/nullptr,
2728                                   /*AlignArg=*/nullptr, Diagnose))
2729       return true;
2730   }
2731 
2732   // We don't need an operator delete if we're running under -fno-exceptions.
2733   if (!getLangOpts().Exceptions) {
2734     OperatorDelete = nullptr;
2735     return false;
2736   }
2737 
2738   // Note, the name of OperatorNew might have been changed from array to
2739   // non-array by resolveAllocationOverload.
2740   DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2741       OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2742           ? OO_Array_Delete
2743           : OO_Delete);
2744 
2745   // C++ [expr.new]p19:
2746   //
2747   //   If the new-expression begins with a unary :: operator, the
2748   //   deallocation function's name is looked up in the global
2749   //   scope. Otherwise, if the allocated type is a class type T or an
2750   //   array thereof, the deallocation function's name is looked up in
2751   //   the scope of T. If this lookup fails to find the name, or if
2752   //   the allocated type is not a class type or array thereof, the
2753   //   deallocation function's name is looked up in the global scope.
2754   LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2755   if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2756     auto *RD =
2757         cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2758     LookupQualifiedName(FoundDelete, RD);
2759   }
2760   if (FoundDelete.isAmbiguous())
2761     return true; // FIXME: clean up expressions?
2762 
2763   // Filter out any destroying operator deletes. We can't possibly call such a
2764   // function in this context, because we're handling the case where the object
2765   // was not successfully constructed.
2766   // FIXME: This is not covered by the language rules yet.
2767   {
2768     LookupResult::Filter Filter = FoundDelete.makeFilter();
2769     while (Filter.hasNext()) {
2770       auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2771       if (FD && FD->isDestroyingOperatorDelete())
2772         Filter.erase();
2773     }
2774     Filter.done();
2775   }
2776 
2777   bool FoundGlobalDelete = FoundDelete.empty();
2778   if (FoundDelete.empty()) {
2779     FoundDelete.clear(LookupOrdinaryName);
2780 
2781     if (DeleteScope == AFS_Class)
2782       return true;
2783 
2784     DeclareGlobalNewDelete();
2785     LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2786   }
2787 
2788   FoundDelete.suppressDiagnostics();
2789 
2790   SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2791 
2792   // Whether we're looking for a placement operator delete is dictated
2793   // by whether we selected a placement operator new, not by whether
2794   // we had explicit placement arguments.  This matters for things like
2795   //   struct A { void *operator new(size_t, int = 0); ... };
2796   //   A *a = new A()
2797   //
2798   // We don't have any definition for what a "placement allocation function"
2799   // is, but we assume it's any allocation function whose
2800   // parameter-declaration-clause is anything other than (size_t).
2801   //
2802   // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2803   // This affects whether an exception from the constructor of an overaligned
2804   // type uses the sized or non-sized form of aligned operator delete.
2805   bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2806                         OperatorNew->isVariadic();
2807 
2808   if (isPlacementNew) {
2809     // C++ [expr.new]p20:
2810     //   A declaration of a placement deallocation function matches the
2811     //   declaration of a placement allocation function if it has the
2812     //   same number of parameters and, after parameter transformations
2813     //   (8.3.5), all parameter types except the first are
2814     //   identical. [...]
2815     //
2816     // To perform this comparison, we compute the function type that
2817     // the deallocation function should have, and use that type both
2818     // for template argument deduction and for comparison purposes.
2819     QualType ExpectedFunctionType;
2820     {
2821       auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2822 
2823       SmallVector<QualType, 4> ArgTypes;
2824       ArgTypes.push_back(Context.VoidPtrTy);
2825       for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2826         ArgTypes.push_back(Proto->getParamType(I));
2827 
2828       FunctionProtoType::ExtProtoInfo EPI;
2829       // FIXME: This is not part of the standard's rule.
2830       EPI.Variadic = Proto->isVariadic();
2831 
2832       ExpectedFunctionType
2833         = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2834     }
2835 
2836     for (LookupResult::iterator D = FoundDelete.begin(),
2837                              DEnd = FoundDelete.end();
2838          D != DEnd; ++D) {
2839       FunctionDecl *Fn = nullptr;
2840       if (FunctionTemplateDecl *FnTmpl =
2841               dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2842         // Perform template argument deduction to try to match the
2843         // expected function type.
2844         TemplateDeductionInfo Info(StartLoc);
2845         if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2846                                     Info))
2847           continue;
2848       } else
2849         Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2850 
2851       if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2852                                                   ExpectedFunctionType,
2853                                                   /*AdjustExcpetionSpec*/true),
2854                               ExpectedFunctionType))
2855         Matches.push_back(std::make_pair(D.getPair(), Fn));
2856     }
2857 
2858     if (getLangOpts().CUDA)
2859       EraseUnwantedCUDAMatches(getCurFunctionDecl(/*AllowLambda=*/true),
2860                                Matches);
2861   } else {
2862     // C++1y [expr.new]p22:
2863     //   For a non-placement allocation function, the normal deallocation
2864     //   function lookup is used
2865     //
2866     // Per [expr.delete]p10, this lookup prefers a member operator delete
2867     // without a size_t argument, but prefers a non-member operator delete
2868     // with a size_t where possible (which it always is in this case).
2869     llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2870     UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2871         *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2872         /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2873         &BestDeallocFns);
2874     if (Selected)
2875       Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2876     else {
2877       // If we failed to select an operator, all remaining functions are viable
2878       // but ambiguous.
2879       for (auto Fn : BestDeallocFns)
2880         Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2881     }
2882   }
2883 
2884   // C++ [expr.new]p20:
2885   //   [...] If the lookup finds a single matching deallocation
2886   //   function, that function will be called; otherwise, no
2887   //   deallocation function will be called.
2888   if (Matches.size() == 1) {
2889     OperatorDelete = Matches[0].second;
2890 
2891     // C++1z [expr.new]p23:
2892     //   If the lookup finds a usual deallocation function (3.7.4.2)
2893     //   with a parameter of type std::size_t and that function, considered
2894     //   as a placement deallocation function, would have been
2895     //   selected as a match for the allocation function, the program
2896     //   is ill-formed.
2897     if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2898         isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2899       UsualDeallocFnInfo Info(*this,
2900                               DeclAccessPair::make(OperatorDelete, AS_public));
2901       // Core issue, per mail to core reflector, 2016-10-09:
2902       //   If this is a member operator delete, and there is a corresponding
2903       //   non-sized member operator delete, this isn't /really/ a sized
2904       //   deallocation function, it just happens to have a size_t parameter.
2905       bool IsSizedDelete = Info.HasSizeT;
2906       if (IsSizedDelete && !FoundGlobalDelete) {
2907         auto NonSizedDelete =
2908             resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2909                                         /*WantAlign*/Info.HasAlignValT);
2910         if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2911             NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2912           IsSizedDelete = false;
2913       }
2914 
2915       if (IsSizedDelete) {
2916         SourceRange R = PlaceArgs.empty()
2917                             ? SourceRange()
2918                             : SourceRange(PlaceArgs.front()->getBeginLoc(),
2919                                           PlaceArgs.back()->getEndLoc());
2920         Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2921         if (!OperatorDelete->isImplicit())
2922           Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2923               << DeleteName;
2924       }
2925     }
2926 
2927     CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2928                           Matches[0].first);
2929   } else if (!Matches.empty()) {
2930     // We found multiple suitable operators. Per [expr.new]p20, that means we
2931     // call no 'operator delete' function, but we should at least warn the user.
2932     // FIXME: Suppress this warning if the construction cannot throw.
2933     Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2934       << DeleteName << AllocElemType;
2935 
2936     for (auto &Match : Matches)
2937       Diag(Match.second->getLocation(),
2938            diag::note_member_declared_here) << DeleteName;
2939   }
2940 
2941   return false;
2942 }
2943 
2944 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2945 /// delete. These are:
2946 /// @code
2947 ///   // C++03:
2948 ///   void* operator new(std::size_t) throw(std::bad_alloc);
2949 ///   void* operator new[](std::size_t) throw(std::bad_alloc);
2950 ///   void operator delete(void *) throw();
2951 ///   void operator delete[](void *) throw();
2952 ///   // C++11:
2953 ///   void* operator new(std::size_t);
2954 ///   void* operator new[](std::size_t);
2955 ///   void operator delete(void *) noexcept;
2956 ///   void operator delete[](void *) noexcept;
2957 ///   // C++1y:
2958 ///   void* operator new(std::size_t);
2959 ///   void* operator new[](std::size_t);
2960 ///   void operator delete(void *) noexcept;
2961 ///   void operator delete[](void *) noexcept;
2962 ///   void operator delete(void *, std::size_t) noexcept;
2963 ///   void operator delete[](void *, std::size_t) noexcept;
2964 /// @endcode
2965 /// Note that the placement and nothrow forms of new are *not* implicitly
2966 /// declared. Their use requires including \<new\>.
2967 void Sema::DeclareGlobalNewDelete() {
2968   if (GlobalNewDeleteDeclared)
2969     return;
2970 
2971   // The implicitly declared new and delete operators
2972   // are not supported in OpenCL.
2973   if (getLangOpts().OpenCLCPlusPlus)
2974     return;
2975 
2976   // C++ [basic.stc.dynamic.general]p2:
2977   //   The library provides default definitions for the global allocation
2978   //   and deallocation functions. Some global allocation and deallocation
2979   //   functions are replaceable ([new.delete]); these are attached to the
2980   //   global module ([module.unit]).
2981   if (getLangOpts().CPlusPlusModules && getCurrentModule())
2982     PushGlobalModuleFragment(SourceLocation(), /*IsImplicit=*/true);
2983 
2984   // C++ [basic.std.dynamic]p2:
2985   //   [...] The following allocation and deallocation functions (18.4) are
2986   //   implicitly declared in global scope in each translation unit of a
2987   //   program
2988   //
2989   //     C++03:
2990   //     void* operator new(std::size_t) throw(std::bad_alloc);
2991   //     void* operator new[](std::size_t) throw(std::bad_alloc);
2992   //     void  operator delete(void*) throw();
2993   //     void  operator delete[](void*) throw();
2994   //     C++11:
2995   //     void* operator new(std::size_t);
2996   //     void* operator new[](std::size_t);
2997   //     void  operator delete(void*) noexcept;
2998   //     void  operator delete[](void*) noexcept;
2999   //     C++1y:
3000   //     void* operator new(std::size_t);
3001   //     void* operator new[](std::size_t);
3002   //     void  operator delete(void*) noexcept;
3003   //     void  operator delete[](void*) noexcept;
3004   //     void  operator delete(void*, std::size_t) noexcept;
3005   //     void  operator delete[](void*, std::size_t) noexcept;
3006   //
3007   //   These implicit declarations introduce only the function names operator
3008   //   new, operator new[], operator delete, operator delete[].
3009   //
3010   // Here, we need to refer to std::bad_alloc, so we will implicitly declare
3011   // "std" or "bad_alloc" as necessary to form the exception specification.
3012   // However, we do not make these implicit declarations visible to name
3013   // lookup.
3014   if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3015     // The "std::bad_alloc" class has not yet been declared, so build it
3016     // implicitly.
3017     StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
3018                                         getOrCreateStdNamespace(),
3019                                         SourceLocation(), SourceLocation(),
3020                                       &PP.getIdentifierTable().get("bad_alloc"),
3021                                         nullptr);
3022     getStdBadAlloc()->setImplicit(true);
3023 
3024     // The implicitly declared "std::bad_alloc" should live in global module
3025     // fragment.
3026     if (GlobalModuleFragment) {
3027       getStdBadAlloc()->setModuleOwnershipKind(
3028           Decl::ModuleOwnershipKind::ReachableWhenImported);
3029       getStdBadAlloc()->setLocalOwningModule(GlobalModuleFragment);
3030     }
3031   }
3032   if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3033     // The "std::align_val_t" enum class has not yet been declared, so build it
3034     // implicitly.
3035     auto *AlignValT = EnumDecl::Create(
3036         Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
3037         &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3038 
3039     // The implicitly declared "std::align_val_t" should live in global module
3040     // fragment.
3041     if (GlobalModuleFragment) {
3042       AlignValT->setModuleOwnershipKind(
3043           Decl::ModuleOwnershipKind::ReachableWhenImported);
3044       AlignValT->setLocalOwningModule(GlobalModuleFragment);
3045     }
3046 
3047     AlignValT->setIntegerType(Context.getSizeType());
3048     AlignValT->setPromotionType(Context.getSizeType());
3049     AlignValT->setImplicit(true);
3050 
3051     StdAlignValT = AlignValT;
3052   }
3053 
3054   GlobalNewDeleteDeclared = true;
3055 
3056   QualType VoidPtr = Context.getPointerType(Context.VoidTy);
3057   QualType SizeT = Context.getSizeType();
3058 
3059   auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3060                                               QualType Return, QualType Param) {
3061     llvm::SmallVector<QualType, 3> Params;
3062     Params.push_back(Param);
3063 
3064     // Create up to four variants of the function (sized/aligned).
3065     bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3066                            (Kind == OO_Delete || Kind == OO_Array_Delete);
3067     bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3068 
3069     int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3070     int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3071     for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3072       if (Sized)
3073         Params.push_back(SizeT);
3074 
3075       for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3076         if (Aligned)
3077           Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
3078 
3079         DeclareGlobalAllocationFunction(
3080             Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3081 
3082         if (Aligned)
3083           Params.pop_back();
3084       }
3085     }
3086   };
3087 
3088   DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3089   DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3090   DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3091   DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3092 
3093   if (getLangOpts().CPlusPlusModules && getCurrentModule())
3094     PopGlobalModuleFragment();
3095 }
3096 
3097 /// DeclareGlobalAllocationFunction - Declares a single implicit global
3098 /// allocation function if it doesn't already exist.
3099 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
3100                                            QualType Return,
3101                                            ArrayRef<QualType> Params) {
3102   DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
3103 
3104   // Check if this function is already declared.
3105   DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3106   for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3107        Alloc != AllocEnd; ++Alloc) {
3108     // Only look at non-template functions, as it is the predefined,
3109     // non-templated allocation function we are trying to declare here.
3110     if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3111       if (Func->getNumParams() == Params.size()) {
3112         llvm::SmallVector<QualType, 3> FuncParams;
3113         for (auto *P : Func->parameters())
3114           FuncParams.push_back(
3115               Context.getCanonicalType(P->getType().getUnqualifiedType()));
3116         if (llvm::ArrayRef(FuncParams) == Params) {
3117           // Make the function visible to name lookup, even if we found it in
3118           // an unimported module. It either is an implicitly-declared global
3119           // allocation function, or is suppressing that function.
3120           Func->setVisibleDespiteOwningModule();
3121           return;
3122         }
3123       }
3124     }
3125   }
3126 
3127   FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
3128       /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3129 
3130   QualType BadAllocType;
3131   bool HasBadAllocExceptionSpec
3132     = (Name.getCXXOverloadedOperator() == OO_New ||
3133        Name.getCXXOverloadedOperator() == OO_Array_New);
3134   if (HasBadAllocExceptionSpec) {
3135     if (!getLangOpts().CPlusPlus11) {
3136       BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
3137       assert(StdBadAlloc && "Must have std::bad_alloc declared");
3138       EPI.ExceptionSpec.Type = EST_Dynamic;
3139       EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3140     }
3141     if (getLangOpts().NewInfallible) {
3142       EPI.ExceptionSpec.Type = EST_DynamicNone;
3143     }
3144   } else {
3145     EPI.ExceptionSpec =
3146         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
3147   }
3148 
3149   auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3150     QualType FnType = Context.getFunctionType(Return, Params, EPI);
3151     FunctionDecl *Alloc = FunctionDecl::Create(
3152         Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3153         /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3154         true);
3155     Alloc->setImplicit();
3156     // Global allocation functions should always be visible.
3157     Alloc->setVisibleDespiteOwningModule();
3158 
3159     if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible)
3160       Alloc->addAttr(
3161           ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3162 
3163     // C++ [basic.stc.dynamic.general]p2:
3164     //   The library provides default definitions for the global allocation
3165     //   and deallocation functions. Some global allocation and deallocation
3166     //   functions are replaceable ([new.delete]); these are attached to the
3167     //   global module ([module.unit]).
3168     //
3169     // In the language wording, these functions are attched to the global
3170     // module all the time. But in the implementation, the global module
3171     // is only meaningful when we're in a module unit. So here we attach
3172     // these allocation functions to global module conditionally.
3173     if (GlobalModuleFragment) {
3174       Alloc->setModuleOwnershipKind(
3175           Decl::ModuleOwnershipKind::ReachableWhenImported);
3176       Alloc->setLocalOwningModule(GlobalModuleFragment);
3177     }
3178 
3179     Alloc->addAttr(VisibilityAttr::CreateImplicit(
3180         Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
3181                      ? VisibilityAttr::Hidden
3182                      : VisibilityAttr::Default));
3183 
3184     llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
3185     for (QualType T : Params) {
3186       ParamDecls.push_back(ParmVarDecl::Create(
3187           Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3188           /*TInfo=*/nullptr, SC_None, nullptr));
3189       ParamDecls.back()->setImplicit();
3190     }
3191     Alloc->setParams(ParamDecls);
3192     if (ExtraAttr)
3193       Alloc->addAttr(ExtraAttr);
3194     AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc);
3195     Context.getTranslationUnitDecl()->addDecl(Alloc);
3196     IdResolver.tryAddTopLevelDecl(Alloc, Name);
3197   };
3198 
3199   if (!LangOpts.CUDA)
3200     CreateAllocationFunctionDecl(nullptr);
3201   else {
3202     // Host and device get their own declaration so each can be
3203     // defined or re-declared independently.
3204     CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3205     CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3206   }
3207 }
3208 
3209 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
3210                                                   bool CanProvideSize,
3211                                                   bool Overaligned,
3212                                                   DeclarationName Name) {
3213   DeclareGlobalNewDelete();
3214 
3215   LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3216   LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
3217 
3218   // FIXME: It's possible for this to result in ambiguity, through a
3219   // user-declared variadic operator delete or the enable_if attribute. We
3220   // should probably not consider those cases to be usual deallocation
3221   // functions. But for now we just make an arbitrary choice in that case.
3222   auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3223                                             Overaligned);
3224   assert(Result.FD && "operator delete missing from global scope?");
3225   return Result.FD;
3226 }
3227 
3228 FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
3229                                                           CXXRecordDecl *RD) {
3230   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
3231 
3232   FunctionDecl *OperatorDelete = nullptr;
3233   if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3234     return nullptr;
3235   if (OperatorDelete)
3236     return OperatorDelete;
3237 
3238   // If there's no class-specific operator delete, look up the global
3239   // non-array delete.
3240   return FindUsualDeallocationFunction(
3241       Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
3242       Name);
3243 }
3244 
3245 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3246                                     DeclarationName Name,
3247                                     FunctionDecl *&Operator, bool Diagnose,
3248                                     bool WantSize, bool WantAligned) {
3249   LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3250   // Try to find operator delete/operator delete[] in class scope.
3251   LookupQualifiedName(Found, RD);
3252 
3253   if (Found.isAmbiguous())
3254     return true;
3255 
3256   Found.suppressDiagnostics();
3257 
3258   bool Overaligned =
3259       WantAligned || hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3260 
3261   // C++17 [expr.delete]p10:
3262   //   If the deallocation functions have class scope, the one without a
3263   //   parameter of type std::size_t is selected.
3264   llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
3265   resolveDeallocationOverload(*this, Found, /*WantSize*/ WantSize,
3266                               /*WantAlign*/ Overaligned, &Matches);
3267 
3268   // If we could find an overload, use it.
3269   if (Matches.size() == 1) {
3270     Operator = cast<CXXMethodDecl>(Matches[0].FD);
3271 
3272     // FIXME: DiagnoseUseOfDecl?
3273     if (Operator->isDeleted()) {
3274       if (Diagnose) {
3275         Diag(StartLoc, diag::err_deleted_function_use);
3276         NoteDeletedFunction(Operator);
3277       }
3278       return true;
3279     }
3280 
3281     if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3282                               Matches[0].Found, Diagnose) == AR_inaccessible)
3283       return true;
3284 
3285     return false;
3286   }
3287 
3288   // We found multiple suitable operators; complain about the ambiguity.
3289   // FIXME: The standard doesn't say to do this; it appears that the intent
3290   // is that this should never happen.
3291   if (!Matches.empty()) {
3292     if (Diagnose) {
3293       Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3294         << Name << RD;
3295       for (auto &Match : Matches)
3296         Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3297     }
3298     return true;
3299   }
3300 
3301   // We did find operator delete/operator delete[] declarations, but
3302   // none of them were suitable.
3303   if (!Found.empty()) {
3304     if (Diagnose) {
3305       Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3306         << Name << RD;
3307 
3308       for (NamedDecl *D : Found)
3309         Diag(D->getUnderlyingDecl()->getLocation(),
3310              diag::note_member_declared_here) << Name;
3311     }
3312     return true;
3313   }
3314 
3315   Operator = nullptr;
3316   return false;
3317 }
3318 
3319 namespace {
3320 /// Checks whether delete-expression, and new-expression used for
3321 ///  initializing deletee have the same array form.
3322 class MismatchingNewDeleteDetector {
3323 public:
3324   enum MismatchResult {
3325     /// Indicates that there is no mismatch or a mismatch cannot be proven.
3326     NoMismatch,
3327     /// Indicates that variable is initialized with mismatching form of \a new.
3328     VarInitMismatches,
3329     /// Indicates that member is initialized with mismatching form of \a new.
3330     MemberInitMismatches,
3331     /// Indicates that 1 or more constructors' definitions could not been
3332     /// analyzed, and they will be checked again at the end of translation unit.
3333     AnalyzeLater
3334   };
3335 
3336   /// \param EndOfTU True, if this is the final analysis at the end of
3337   /// translation unit. False, if this is the initial analysis at the point
3338   /// delete-expression was encountered.
3339   explicit MismatchingNewDeleteDetector(bool EndOfTU)
3340       : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3341         HasUndefinedConstructors(false) {}
3342 
3343   /// Checks whether pointee of a delete-expression is initialized with
3344   /// matching form of new-expression.
3345   ///
3346   /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3347   /// point where delete-expression is encountered, then a warning will be
3348   /// issued immediately. If return value is \c AnalyzeLater at the point where
3349   /// delete-expression is seen, then member will be analyzed at the end of
3350   /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3351   /// couldn't be analyzed. If at least one constructor initializes the member
3352   /// with matching type of new, the return value is \c NoMismatch.
3353   MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3354   /// Analyzes a class member.
3355   /// \param Field Class member to analyze.
3356   /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3357   /// for deleting the \p Field.
3358   MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3359   FieldDecl *Field;
3360   /// List of mismatching new-expressions used for initialization of the pointee
3361   llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3362   /// Indicates whether delete-expression was in array form.
3363   bool IsArrayForm;
3364 
3365 private:
3366   const bool EndOfTU;
3367   /// Indicates that there is at least one constructor without body.
3368   bool HasUndefinedConstructors;
3369   /// Returns \c CXXNewExpr from given initialization expression.
3370   /// \param E Expression used for initializing pointee in delete-expression.
3371   /// E can be a single-element \c InitListExpr consisting of new-expression.
3372   const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3373   /// Returns whether member is initialized with mismatching form of
3374   /// \c new either by the member initializer or in-class initialization.
3375   ///
3376   /// If bodies of all constructors are not visible at the end of translation
3377   /// unit or at least one constructor initializes member with the matching
3378   /// form of \c new, mismatch cannot be proven, and this function will return
3379   /// \c NoMismatch.
3380   MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3381   /// Returns whether variable is initialized with mismatching form of
3382   /// \c new.
3383   ///
3384   /// If variable is initialized with matching form of \c new or variable is not
3385   /// initialized with a \c new expression, this function will return true.
3386   /// If variable is initialized with mismatching form of \c new, returns false.
3387   /// \param D Variable to analyze.
3388   bool hasMatchingVarInit(const DeclRefExpr *D);
3389   /// Checks whether the constructor initializes pointee with mismatching
3390   /// form of \c new.
3391   ///
3392   /// Returns true, if member is initialized with matching form of \c new in
3393   /// member initializer list. Returns false, if member is initialized with the
3394   /// matching form of \c new in this constructor's initializer or given
3395   /// constructor isn't defined at the point where delete-expression is seen, or
3396   /// member isn't initialized by the constructor.
3397   bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3398   /// Checks whether member is initialized with matching form of
3399   /// \c new in member initializer list.
3400   bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3401   /// Checks whether member is initialized with mismatching form of \c new by
3402   /// in-class initializer.
3403   MismatchResult analyzeInClassInitializer();
3404 };
3405 }
3406 
3407 MismatchingNewDeleteDetector::MismatchResult
3408 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3409   NewExprs.clear();
3410   assert(DE && "Expected delete-expression");
3411   IsArrayForm = DE->isArrayForm();
3412   const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3413   if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3414     return analyzeMemberExpr(ME);
3415   } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3416     if (!hasMatchingVarInit(D))
3417       return VarInitMismatches;
3418   }
3419   return NoMismatch;
3420 }
3421 
3422 const CXXNewExpr *
3423 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3424   assert(E != nullptr && "Expected a valid initializer expression");
3425   E = E->IgnoreParenImpCasts();
3426   if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3427     if (ILE->getNumInits() == 1)
3428       E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3429   }
3430 
3431   return dyn_cast_or_null<const CXXNewExpr>(E);
3432 }
3433 
3434 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3435     const CXXCtorInitializer *CI) {
3436   const CXXNewExpr *NE = nullptr;
3437   if (Field == CI->getMember() &&
3438       (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3439     if (NE->isArray() == IsArrayForm)
3440       return true;
3441     else
3442       NewExprs.push_back(NE);
3443   }
3444   return false;
3445 }
3446 
3447 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3448     const CXXConstructorDecl *CD) {
3449   if (CD->isImplicit())
3450     return false;
3451   const FunctionDecl *Definition = CD;
3452   if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3453     HasUndefinedConstructors = true;
3454     return EndOfTU;
3455   }
3456   for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3457     if (hasMatchingNewInCtorInit(CI))
3458       return true;
3459   }
3460   return false;
3461 }
3462 
3463 MismatchingNewDeleteDetector::MismatchResult
3464 MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3465   assert(Field != nullptr && "This should be called only for members");
3466   const Expr *InitExpr = Field->getInClassInitializer();
3467   if (!InitExpr)
3468     return EndOfTU ? NoMismatch : AnalyzeLater;
3469   if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3470     if (NE->isArray() != IsArrayForm) {
3471       NewExprs.push_back(NE);
3472       return MemberInitMismatches;
3473     }
3474   }
3475   return NoMismatch;
3476 }
3477 
3478 MismatchingNewDeleteDetector::MismatchResult
3479 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3480                                            bool DeleteWasArrayForm) {
3481   assert(Field != nullptr && "Analysis requires a valid class member.");
3482   this->Field = Field;
3483   IsArrayForm = DeleteWasArrayForm;
3484   const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3485   for (const auto *CD : RD->ctors()) {
3486     if (hasMatchingNewInCtor(CD))
3487       return NoMismatch;
3488   }
3489   if (HasUndefinedConstructors)
3490     return EndOfTU ? NoMismatch : AnalyzeLater;
3491   if (!NewExprs.empty())
3492     return MemberInitMismatches;
3493   return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3494                                         : NoMismatch;
3495 }
3496 
3497 MismatchingNewDeleteDetector::MismatchResult
3498 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3499   assert(ME != nullptr && "Expected a member expression");
3500   if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3501     return analyzeField(F, IsArrayForm);
3502   return NoMismatch;
3503 }
3504 
3505 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3506   const CXXNewExpr *NE = nullptr;
3507   if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3508     if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3509         NE->isArray() != IsArrayForm) {
3510       NewExprs.push_back(NE);
3511     }
3512   }
3513   return NewExprs.empty();
3514 }
3515 
3516 static void
3517 DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3518                             const MismatchingNewDeleteDetector &Detector) {
3519   SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3520   FixItHint H;
3521   if (!Detector.IsArrayForm)
3522     H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3523   else {
3524     SourceLocation RSquare = Lexer::findLocationAfterToken(
3525         DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3526         SemaRef.getLangOpts(), true);
3527     if (RSquare.isValid())
3528       H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3529   }
3530   SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3531       << Detector.IsArrayForm << H;
3532 
3533   for (const auto *NE : Detector.NewExprs)
3534     SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3535         << Detector.IsArrayForm;
3536 }
3537 
3538 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3539   if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3540     return;
3541   MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3542   switch (Detector.analyzeDeleteExpr(DE)) {
3543   case MismatchingNewDeleteDetector::VarInitMismatches:
3544   case MismatchingNewDeleteDetector::MemberInitMismatches: {
3545     DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3546     break;
3547   }
3548   case MismatchingNewDeleteDetector::AnalyzeLater: {
3549     DeleteExprs[Detector.Field].push_back(
3550         std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3551     break;
3552   }
3553   case MismatchingNewDeleteDetector::NoMismatch:
3554     break;
3555   }
3556 }
3557 
3558 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3559                                      bool DeleteWasArrayForm) {
3560   MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3561   switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3562   case MismatchingNewDeleteDetector::VarInitMismatches:
3563     llvm_unreachable("This analysis should have been done for class members.");
3564   case MismatchingNewDeleteDetector::AnalyzeLater:
3565     llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3566                      "translation unit.");
3567   case MismatchingNewDeleteDetector::MemberInitMismatches:
3568     DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3569     break;
3570   case MismatchingNewDeleteDetector::NoMismatch:
3571     break;
3572   }
3573 }
3574 
3575 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3576 /// @code ::delete ptr; @endcode
3577 /// or
3578 /// @code delete [] ptr; @endcode
3579 ExprResult
3580 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3581                      bool ArrayForm, Expr *ExE) {
3582   // C++ [expr.delete]p1:
3583   //   The operand shall have a pointer type, or a class type having a single
3584   //   non-explicit conversion function to a pointer type. The result has type
3585   //   void.
3586   //
3587   // DR599 amends "pointer type" to "pointer to object type" in both cases.
3588 
3589   ExprResult Ex = ExE;
3590   FunctionDecl *OperatorDelete = nullptr;
3591   bool ArrayFormAsWritten = ArrayForm;
3592   bool UsualArrayDeleteWantsSize = false;
3593 
3594   if (!Ex.get()->isTypeDependent()) {
3595     // Perform lvalue-to-rvalue cast, if needed.
3596     Ex = DefaultLvalueConversion(Ex.get());
3597     if (Ex.isInvalid())
3598       return ExprError();
3599 
3600     QualType Type = Ex.get()->getType();
3601 
3602     class DeleteConverter : public ContextualImplicitConverter {
3603     public:
3604       DeleteConverter() : ContextualImplicitConverter(false, true) {}
3605 
3606       bool match(QualType ConvType) override {
3607         // FIXME: If we have an operator T* and an operator void*, we must pick
3608         // the operator T*.
3609         if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3610           if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3611             return true;
3612         return false;
3613       }
3614 
3615       SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3616                                             QualType T) override {
3617         return S.Diag(Loc, diag::err_delete_operand) << T;
3618       }
3619 
3620       SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3621                                                QualType T) override {
3622         return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3623       }
3624 
3625       SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3626                                                  QualType T,
3627                                                  QualType ConvTy) override {
3628         return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3629       }
3630 
3631       SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3632                                              QualType ConvTy) override {
3633         return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3634           << ConvTy;
3635       }
3636 
3637       SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3638                                               QualType T) override {
3639         return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3640       }
3641 
3642       SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3643                                           QualType ConvTy) override {
3644         return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3645           << ConvTy;
3646       }
3647 
3648       SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3649                                                QualType T,
3650                                                QualType ConvTy) override {
3651         llvm_unreachable("conversion functions are permitted");
3652       }
3653     } Converter;
3654 
3655     Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3656     if (Ex.isInvalid())
3657       return ExprError();
3658     Type = Ex.get()->getType();
3659     if (!Converter.match(Type))
3660       // FIXME: PerformContextualImplicitConversion should return ExprError
3661       //        itself in this case.
3662       return ExprError();
3663 
3664     QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3665     QualType PointeeElem = Context.getBaseElementType(Pointee);
3666 
3667     if (Pointee.getAddressSpace() != LangAS::Default &&
3668         !getLangOpts().OpenCLCPlusPlus)
3669       return Diag(Ex.get()->getBeginLoc(),
3670                   diag::err_address_space_qualified_delete)
3671              << Pointee.getUnqualifiedType()
3672              << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3673 
3674     CXXRecordDecl *PointeeRD = nullptr;
3675     if (Pointee->isVoidType() && !isSFINAEContext()) {
3676       // The C++ standard bans deleting a pointer to a non-object type, which
3677       // effectively bans deletion of "void*". However, most compilers support
3678       // this, so we treat it as a warning unless we're in a SFINAE context.
3679       Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3680         << Type << Ex.get()->getSourceRange();
3681     } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3682                Pointee->isSizelessType()) {
3683       return ExprError(Diag(StartLoc, diag::err_delete_operand)
3684         << Type << Ex.get()->getSourceRange());
3685     } else if (!Pointee->isDependentType()) {
3686       // FIXME: This can result in errors if the definition was imported from a
3687       // module but is hidden.
3688       if (!RequireCompleteType(StartLoc, Pointee,
3689                                diag::warn_delete_incomplete, Ex.get())) {
3690         if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3691           PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3692       }
3693     }
3694 
3695     if (Pointee->isArrayType() && !ArrayForm) {
3696       Diag(StartLoc, diag::warn_delete_array_type)
3697           << Type << Ex.get()->getSourceRange()
3698           << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3699       ArrayForm = true;
3700     }
3701 
3702     DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3703                                       ArrayForm ? OO_Array_Delete : OO_Delete);
3704 
3705     if (PointeeRD) {
3706       if (!UseGlobal &&
3707           FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3708                                    OperatorDelete))
3709         return ExprError();
3710 
3711       // If we're allocating an array of records, check whether the
3712       // usual operator delete[] has a size_t parameter.
3713       if (ArrayForm) {
3714         // If the user specifically asked to use the global allocator,
3715         // we'll need to do the lookup into the class.
3716         if (UseGlobal)
3717           UsualArrayDeleteWantsSize =
3718             doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3719 
3720         // Otherwise, the usual operator delete[] should be the
3721         // function we just found.
3722         else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3723           UsualArrayDeleteWantsSize =
3724             UsualDeallocFnInfo(*this,
3725                                DeclAccessPair::make(OperatorDelete, AS_public))
3726               .HasSizeT;
3727       }
3728 
3729       if (!PointeeRD->hasIrrelevantDestructor())
3730         if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3731           MarkFunctionReferenced(StartLoc,
3732                                     const_cast<CXXDestructorDecl*>(Dtor));
3733           if (DiagnoseUseOfDecl(Dtor, StartLoc))
3734             return ExprError();
3735         }
3736 
3737       CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3738                            /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3739                            /*WarnOnNonAbstractTypes=*/!ArrayForm,
3740                            SourceLocation());
3741     }
3742 
3743     if (!OperatorDelete) {
3744       if (getLangOpts().OpenCLCPlusPlus) {
3745         Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3746         return ExprError();
3747       }
3748 
3749       bool IsComplete = isCompleteType(StartLoc, Pointee);
3750       bool CanProvideSize =
3751           IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3752                          Pointee.isDestructedType());
3753       bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3754 
3755       // Look for a global declaration.
3756       OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3757                                                      Overaligned, DeleteName);
3758     }
3759 
3760     MarkFunctionReferenced(StartLoc, OperatorDelete);
3761 
3762     // Check access and ambiguity of destructor if we're going to call it.
3763     // Note that this is required even for a virtual delete.
3764     bool IsVirtualDelete = false;
3765     if (PointeeRD) {
3766       if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3767         CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3768                               PDiag(diag::err_access_dtor) << PointeeElem);
3769         IsVirtualDelete = Dtor->isVirtual();
3770       }
3771     }
3772 
3773     DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3774 
3775     // Convert the operand to the type of the first parameter of operator
3776     // delete. This is only necessary if we selected a destroying operator
3777     // delete that we are going to call (non-virtually); converting to void*
3778     // is trivial and left to AST consumers to handle.
3779     QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3780     if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3781       Qualifiers Qs = Pointee.getQualifiers();
3782       if (Qs.hasCVRQualifiers()) {
3783         // Qualifiers are irrelevant to this conversion; we're only looking
3784         // for access and ambiguity.
3785         Qs.removeCVRQualifiers();
3786         QualType Unqual = Context.getPointerType(
3787             Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3788         Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3789       }
3790       Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3791       if (Ex.isInvalid())
3792         return ExprError();
3793     }
3794   }
3795 
3796   CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3797       Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3798       UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3799   AnalyzeDeleteExprMismatch(Result);
3800   return Result;
3801 }
3802 
3803 static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3804                                             bool IsDelete,
3805                                             FunctionDecl *&Operator) {
3806 
3807   DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3808       IsDelete ? OO_Delete : OO_New);
3809 
3810   LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3811   S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3812   assert(!R.empty() && "implicitly declared allocation functions not found");
3813   assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3814 
3815   // We do our own custom access checks below.
3816   R.suppressDiagnostics();
3817 
3818   SmallVector<Expr *, 8> Args(TheCall->arguments());
3819   OverloadCandidateSet Candidates(R.getNameLoc(),
3820                                   OverloadCandidateSet::CSK_Normal);
3821   for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3822        FnOvl != FnOvlEnd; ++FnOvl) {
3823     // Even member operator new/delete are implicitly treated as
3824     // static, so don't use AddMemberCandidate.
3825     NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3826 
3827     if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3828       S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3829                                      /*ExplicitTemplateArgs=*/nullptr, Args,
3830                                      Candidates,
3831                                      /*SuppressUserConversions=*/false);
3832       continue;
3833     }
3834 
3835     FunctionDecl *Fn = cast<FunctionDecl>(D);
3836     S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3837                            /*SuppressUserConversions=*/false);
3838   }
3839 
3840   SourceRange Range = TheCall->getSourceRange();
3841 
3842   // Do the resolution.
3843   OverloadCandidateSet::iterator Best;
3844   switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3845   case OR_Success: {
3846     // Got one!
3847     FunctionDecl *FnDecl = Best->Function;
3848     assert(R.getNamingClass() == nullptr &&
3849            "class members should not be considered");
3850 
3851     if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3852       S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3853           << (IsDelete ? 1 : 0) << Range;
3854       S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3855           << R.getLookupName() << FnDecl->getSourceRange();
3856       return true;
3857     }
3858 
3859     Operator = FnDecl;
3860     return false;
3861   }
3862 
3863   case OR_No_Viable_Function:
3864     Candidates.NoteCandidates(
3865         PartialDiagnosticAt(R.getNameLoc(),
3866                             S.PDiag(diag::err_ovl_no_viable_function_in_call)
3867                                 << R.getLookupName() << Range),
3868         S, OCD_AllCandidates, Args);
3869     return true;
3870 
3871   case OR_Ambiguous:
3872     Candidates.NoteCandidates(
3873         PartialDiagnosticAt(R.getNameLoc(),
3874                             S.PDiag(diag::err_ovl_ambiguous_call)
3875                                 << R.getLookupName() << Range),
3876         S, OCD_AmbiguousCandidates, Args);
3877     return true;
3878 
3879   case OR_Deleted: {
3880     Candidates.NoteCandidates(
3881         PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3882                                                 << R.getLookupName() << Range),
3883         S, OCD_AllCandidates, Args);
3884     return true;
3885   }
3886   }
3887   llvm_unreachable("Unreachable, bad result from BestViableFunction");
3888 }
3889 
3890 ExprResult
3891 Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3892                                              bool IsDelete) {
3893   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3894   if (!getLangOpts().CPlusPlus) {
3895     Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3896         << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3897         << "C++";
3898     return ExprError();
3899   }
3900   // CodeGen assumes it can find the global new and delete to call,
3901   // so ensure that they are declared.
3902   DeclareGlobalNewDelete();
3903 
3904   FunctionDecl *OperatorNewOrDelete = nullptr;
3905   if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3906                                       OperatorNewOrDelete))
3907     return ExprError();
3908   assert(OperatorNewOrDelete && "should be found");
3909 
3910   DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3911   MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3912 
3913   TheCall->setType(OperatorNewOrDelete->getReturnType());
3914   for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3915     QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3916     InitializedEntity Entity =
3917         InitializedEntity::InitializeParameter(Context, ParamTy, false);
3918     ExprResult Arg = PerformCopyInitialization(
3919         Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3920     if (Arg.isInvalid())
3921       return ExprError();
3922     TheCall->setArg(i, Arg.get());
3923   }
3924   auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3925   assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3926          "Callee expected to be implicit cast to a builtin function pointer");
3927   Callee->setType(OperatorNewOrDelete->getType());
3928 
3929   return TheCallResult;
3930 }
3931 
3932 void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3933                                 bool IsDelete, bool CallCanBeVirtual,
3934                                 bool WarnOnNonAbstractTypes,
3935                                 SourceLocation DtorLoc) {
3936   if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3937     return;
3938 
3939   // C++ [expr.delete]p3:
3940   //   In the first alternative (delete object), if the static type of the
3941   //   object to be deleted is different from its dynamic type, the static
3942   //   type shall be a base class of the dynamic type of the object to be
3943   //   deleted and the static type shall have a virtual destructor or the
3944   //   behavior is undefined.
3945   //
3946   const CXXRecordDecl *PointeeRD = dtor->getParent();
3947   // Note: a final class cannot be derived from, no issue there
3948   if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3949     return;
3950 
3951   // If the superclass is in a system header, there's nothing that can be done.
3952   // The `delete` (where we emit the warning) can be in a system header,
3953   // what matters for this warning is where the deleted type is defined.
3954   if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3955     return;
3956 
3957   QualType ClassType = dtor->getThisType()->getPointeeType();
3958   if (PointeeRD->isAbstract()) {
3959     // If the class is abstract, we warn by default, because we're
3960     // sure the code has undefined behavior.
3961     Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3962                                                            << ClassType;
3963   } else if (WarnOnNonAbstractTypes) {
3964     // Otherwise, if this is not an array delete, it's a bit suspect,
3965     // but not necessarily wrong.
3966     Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3967                                                   << ClassType;
3968   }
3969   if (!IsDelete) {
3970     std::string TypeStr;
3971     ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3972     Diag(DtorLoc, diag::note_delete_non_virtual)
3973         << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3974   }
3975 }
3976 
3977 Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3978                                                    SourceLocation StmtLoc,
3979                                                    ConditionKind CK) {
3980   ExprResult E =
3981       CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3982   if (E.isInvalid())
3983     return ConditionError();
3984   return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3985                          CK == ConditionKind::ConstexprIf);
3986 }
3987 
3988 /// Check the use of the given variable as a C++ condition in an if,
3989 /// while, do-while, or switch statement.
3990 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3991                                         SourceLocation StmtLoc,
3992                                         ConditionKind CK) {
3993   if (ConditionVar->isInvalidDecl())
3994     return ExprError();
3995 
3996   QualType T = ConditionVar->getType();
3997 
3998   // C++ [stmt.select]p2:
3999   //   The declarator shall not specify a function or an array.
4000   if (T->isFunctionType())
4001     return ExprError(Diag(ConditionVar->getLocation(),
4002                           diag::err_invalid_use_of_function_type)
4003                        << ConditionVar->getSourceRange());
4004   else if (T->isArrayType())
4005     return ExprError(Diag(ConditionVar->getLocation(),
4006                           diag::err_invalid_use_of_array_type)
4007                      << ConditionVar->getSourceRange());
4008 
4009   ExprResult Condition = BuildDeclRefExpr(
4010       ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
4011       ConditionVar->getLocation());
4012 
4013   switch (CK) {
4014   case ConditionKind::Boolean:
4015     return CheckBooleanCondition(StmtLoc, Condition.get());
4016 
4017   case ConditionKind::ConstexprIf:
4018     return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4019 
4020   case ConditionKind::Switch:
4021     return CheckSwitchCondition(StmtLoc, Condition.get());
4022   }
4023 
4024   llvm_unreachable("unexpected condition kind");
4025 }
4026 
4027 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
4028 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4029   // C++11 6.4p4:
4030   // The value of a condition that is an initialized declaration in a statement
4031   // other than a switch statement is the value of the declared variable
4032   // implicitly converted to type bool. If that conversion is ill-formed, the
4033   // program is ill-formed.
4034   // The value of a condition that is an expression is the value of the
4035   // expression, implicitly converted to bool.
4036   //
4037   // C++2b 8.5.2p2
4038   // If the if statement is of the form if constexpr, the value of the condition
4039   // is contextually converted to bool and the converted expression shall be
4040   // a constant expression.
4041   //
4042 
4043   ExprResult E = PerformContextuallyConvertToBool(CondExpr);
4044   if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4045     return E;
4046 
4047   // FIXME: Return this value to the caller so they don't need to recompute it.
4048   llvm::APSInt Cond;
4049   E = VerifyIntegerConstantExpression(
4050       E.get(), &Cond,
4051       diag::err_constexpr_if_condition_expression_is_not_constant);
4052   return E;
4053 }
4054 
4055 /// Helper function to determine whether this is the (deprecated) C++
4056 /// conversion from a string literal to a pointer to non-const char or
4057 /// non-const wchar_t (for narrow and wide string literals,
4058 /// respectively).
4059 bool
4060 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
4061   // Look inside the implicit cast, if it exists.
4062   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4063     From = Cast->getSubExpr();
4064 
4065   // A string literal (2.13.4) that is not a wide string literal can
4066   // be converted to an rvalue of type "pointer to char"; a wide
4067   // string literal can be converted to an rvalue of type "pointer
4068   // to wchar_t" (C++ 4.2p2).
4069   if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4070     if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4071       if (const BuiltinType *ToPointeeType
4072           = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4073         // This conversion is considered only when there is an
4074         // explicit appropriate pointer target type (C++ 4.2p2).
4075         if (!ToPtrType->getPointeeType().hasQualifiers()) {
4076           switch (StrLit->getKind()) {
4077             case StringLiteral::UTF8:
4078             case StringLiteral::UTF16:
4079             case StringLiteral::UTF32:
4080               // We don't allow UTF literals to be implicitly converted
4081               break;
4082             case StringLiteral::Ordinary:
4083               return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4084                       ToPointeeType->getKind() == BuiltinType::Char_S);
4085             case StringLiteral::Wide:
4086               return Context.typesAreCompatible(Context.getWideCharType(),
4087                                                 QualType(ToPointeeType, 0));
4088           }
4089         }
4090       }
4091 
4092   return false;
4093 }
4094 
4095 static ExprResult BuildCXXCastArgument(Sema &S,
4096                                        SourceLocation CastLoc,
4097                                        QualType Ty,
4098                                        CastKind Kind,
4099                                        CXXMethodDecl *Method,
4100                                        DeclAccessPair FoundDecl,
4101                                        bool HadMultipleCandidates,
4102                                        Expr *From) {
4103   switch (Kind) {
4104   default: llvm_unreachable("Unhandled cast kind!");
4105   case CK_ConstructorConversion: {
4106     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4107     SmallVector<Expr*, 8> ConstructorArgs;
4108 
4109     if (S.RequireNonAbstractType(CastLoc, Ty,
4110                                  diag::err_allocation_of_abstract_type))
4111       return ExprError();
4112 
4113     if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4114                                   ConstructorArgs))
4115       return ExprError();
4116 
4117     S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4118                              InitializedEntity::InitializeTemporary(Ty));
4119     if (S.DiagnoseUseOfDecl(Method, CastLoc))
4120       return ExprError();
4121 
4122     ExprResult Result = S.BuildCXXConstructExpr(
4123         CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4124         ConstructorArgs, HadMultipleCandidates,
4125         /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4126         CXXConstructExpr::CK_Complete, SourceRange());
4127     if (Result.isInvalid())
4128       return ExprError();
4129 
4130     return S.MaybeBindToTemporary(Result.getAs<Expr>());
4131   }
4132 
4133   case CK_UserDefinedConversion: {
4134     assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4135 
4136     S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4137     if (S.DiagnoseUseOfDecl(Method, CastLoc))
4138       return ExprError();
4139 
4140     // Create an implicit call expr that calls it.
4141     CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4142     ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4143                                                  HadMultipleCandidates);
4144     if (Result.isInvalid())
4145       return ExprError();
4146     // Record usage of conversion in an implicit cast.
4147     Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4148                                       CK_UserDefinedConversion, Result.get(),
4149                                       nullptr, Result.get()->getValueKind(),
4150                                       S.CurFPFeatureOverrides());
4151 
4152     return S.MaybeBindToTemporary(Result.get());
4153   }
4154   }
4155 }
4156 
4157 /// PerformImplicitConversion - Perform an implicit conversion of the
4158 /// expression From to the type ToType using the pre-computed implicit
4159 /// conversion sequence ICS. Returns the converted
4160 /// expression. Action is the kind of conversion we're performing,
4161 /// used in the error message.
4162 ExprResult
4163 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4164                                 const ImplicitConversionSequence &ICS,
4165                                 AssignmentAction Action,
4166                                 CheckedConversionKind CCK) {
4167   // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4168   if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
4169     return From;
4170 
4171   switch (ICS.getKind()) {
4172   case ImplicitConversionSequence::StandardConversion: {
4173     ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4174                                                Action, CCK);
4175     if (Res.isInvalid())
4176       return ExprError();
4177     From = Res.get();
4178     break;
4179   }
4180 
4181   case ImplicitConversionSequence::UserDefinedConversion: {
4182 
4183       FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
4184       CastKind CastKind;
4185       QualType BeforeToType;
4186       assert(FD && "no conversion function for user-defined conversion seq");
4187       if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4188         CastKind = CK_UserDefinedConversion;
4189 
4190         // If the user-defined conversion is specified by a conversion function,
4191         // the initial standard conversion sequence converts the source type to
4192         // the implicit object parameter of the conversion function.
4193         BeforeToType = Context.getTagDeclType(Conv->getParent());
4194       } else {
4195         const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4196         CastKind = CK_ConstructorConversion;
4197         // Do no conversion if dealing with ... for the first conversion.
4198         if (!ICS.UserDefined.EllipsisConversion) {
4199           // If the user-defined conversion is specified by a constructor, the
4200           // initial standard conversion sequence converts the source type to
4201           // the type required by the argument of the constructor
4202           BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4203         }
4204       }
4205       // Watch out for ellipsis conversion.
4206       if (!ICS.UserDefined.EllipsisConversion) {
4207         ExprResult Res =
4208           PerformImplicitConversion(From, BeforeToType,
4209                                     ICS.UserDefined.Before, AA_Converting,
4210                                     CCK);
4211         if (Res.isInvalid())
4212           return ExprError();
4213         From = Res.get();
4214       }
4215 
4216       ExprResult CastArg = BuildCXXCastArgument(
4217           *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4218           cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4219           ICS.UserDefined.HadMultipleCandidates, From);
4220 
4221       if (CastArg.isInvalid())
4222         return ExprError();
4223 
4224       From = CastArg.get();
4225 
4226       // C++ [over.match.oper]p7:
4227       //   [...] the second standard conversion sequence of a user-defined
4228       //   conversion sequence is not applied.
4229       if (CCK == CCK_ForBuiltinOverloadedOp)
4230         return From;
4231 
4232       return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4233                                        AA_Converting, CCK);
4234   }
4235 
4236   case ImplicitConversionSequence::AmbiguousConversion:
4237     ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4238                           PDiag(diag::err_typecheck_ambiguous_condition)
4239                             << From->getSourceRange());
4240     return ExprError();
4241 
4242   case ImplicitConversionSequence::EllipsisConversion:
4243   case ImplicitConversionSequence::StaticObjectArgumentConversion:
4244     llvm_unreachable("bad conversion");
4245 
4246   case ImplicitConversionSequence::BadConversion:
4247     Sema::AssignConvertType ConvTy =
4248         CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4249     bool Diagnosed = DiagnoseAssignmentResult(
4250         ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4251         ToType, From->getType(), From, Action);
4252     assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4253     return ExprError();
4254   }
4255 
4256   // Everything went well.
4257   return From;
4258 }
4259 
4260 /// PerformImplicitConversion - Perform an implicit conversion of the
4261 /// expression From to the type ToType by following the standard
4262 /// conversion sequence SCS. Returns the converted
4263 /// expression. Flavor is the context in which we're performing this
4264 /// conversion, for use in error messages.
4265 ExprResult
4266 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4267                                 const StandardConversionSequence& SCS,
4268                                 AssignmentAction Action,
4269                                 CheckedConversionKind CCK) {
4270   bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
4271 
4272   // Overall FIXME: we are recomputing too many types here and doing far too
4273   // much extra work. What this means is that we need to keep track of more
4274   // information that is computed when we try the implicit conversion initially,
4275   // so that we don't need to recompute anything here.
4276   QualType FromType = From->getType();
4277 
4278   if (SCS.CopyConstructor) {
4279     // FIXME: When can ToType be a reference type?
4280     assert(!ToType->isReferenceType());
4281     if (SCS.Second == ICK_Derived_To_Base) {
4282       SmallVector<Expr*, 8> ConstructorArgs;
4283       if (CompleteConstructorCall(
4284               cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4285               /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4286         return ExprError();
4287       return BuildCXXConstructExpr(
4288           /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4289           SCS.FoundCopyConstructor, SCS.CopyConstructor,
4290           ConstructorArgs, /*HadMultipleCandidates*/ false,
4291           /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4292           CXXConstructExpr::CK_Complete, SourceRange());
4293     }
4294     return BuildCXXConstructExpr(
4295         /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4296         SCS.FoundCopyConstructor, SCS.CopyConstructor,
4297         From, /*HadMultipleCandidates*/ false,
4298         /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4299         CXXConstructExpr::CK_Complete, SourceRange());
4300   }
4301 
4302   // Resolve overloaded function references.
4303   if (Context.hasSameType(FromType, Context.OverloadTy)) {
4304     DeclAccessPair Found;
4305     FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
4306                                                           true, Found);
4307     if (!Fn)
4308       return ExprError();
4309 
4310     if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4311       return ExprError();
4312 
4313     From = FixOverloadedFunctionReference(From, Found, Fn);
4314 
4315     // We might get back another placeholder expression if we resolved to a
4316     // builtin.
4317     ExprResult Checked = CheckPlaceholderExpr(From);
4318     if (Checked.isInvalid())
4319       return ExprError();
4320 
4321     From = Checked.get();
4322     FromType = From->getType();
4323   }
4324 
4325   // If we're converting to an atomic type, first convert to the corresponding
4326   // non-atomic type.
4327   QualType ToAtomicType;
4328   if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4329     ToAtomicType = ToType;
4330     ToType = ToAtomic->getValueType();
4331   }
4332 
4333   QualType InitialFromType = FromType;
4334   // Perform the first implicit conversion.
4335   switch (SCS.First) {
4336   case ICK_Identity:
4337     if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4338       FromType = FromAtomic->getValueType().getUnqualifiedType();
4339       From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4340                                       From, /*BasePath=*/nullptr, VK_PRValue,
4341                                       FPOptionsOverride());
4342     }
4343     break;
4344 
4345   case ICK_Lvalue_To_Rvalue: {
4346     assert(From->getObjectKind() != OK_ObjCProperty);
4347     ExprResult FromRes = DefaultLvalueConversion(From);
4348     if (FromRes.isInvalid())
4349       return ExprError();
4350 
4351     From = FromRes.get();
4352     FromType = From->getType();
4353     break;
4354   }
4355 
4356   case ICK_Array_To_Pointer:
4357     FromType = Context.getArrayDecayedType(FromType);
4358     From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4359                              /*BasePath=*/nullptr, CCK)
4360                .get();
4361     break;
4362 
4363   case ICK_Function_To_Pointer:
4364     FromType = Context.getPointerType(FromType);
4365     From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4366                              VK_PRValue, /*BasePath=*/nullptr, CCK)
4367                .get();
4368     break;
4369 
4370   default:
4371     llvm_unreachable("Improper first standard conversion");
4372   }
4373 
4374   // Perform the second implicit conversion
4375   switch (SCS.Second) {
4376   case ICK_Identity:
4377     // C++ [except.spec]p5:
4378     //   [For] assignment to and initialization of pointers to functions,
4379     //   pointers to member functions, and references to functions: the
4380     //   target entity shall allow at least the exceptions allowed by the
4381     //   source value in the assignment or initialization.
4382     switch (Action) {
4383     case AA_Assigning:
4384     case AA_Initializing:
4385       // Note, function argument passing and returning are initialization.
4386     case AA_Passing:
4387     case AA_Returning:
4388     case AA_Sending:
4389     case AA_Passing_CFAudited:
4390       if (CheckExceptionSpecCompatibility(From, ToType))
4391         return ExprError();
4392       break;
4393 
4394     case AA_Casting:
4395     case AA_Converting:
4396       // Casts and implicit conversions are not initialization, so are not
4397       // checked for exception specification mismatches.
4398       break;
4399     }
4400     // Nothing else to do.
4401     break;
4402 
4403   case ICK_Integral_Promotion:
4404   case ICK_Integral_Conversion:
4405     if (ToType->isBooleanType()) {
4406       assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4407              SCS.Second == ICK_Integral_Promotion &&
4408              "only enums with fixed underlying type can promote to bool");
4409       From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue,
4410                                /*BasePath=*/nullptr, CCK)
4411                  .get();
4412     } else {
4413       From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue,
4414                                /*BasePath=*/nullptr, CCK)
4415                  .get();
4416     }
4417     break;
4418 
4419   case ICK_Floating_Promotion:
4420   case ICK_Floating_Conversion:
4421     From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue,
4422                              /*BasePath=*/nullptr, CCK)
4423                .get();
4424     break;
4425 
4426   case ICK_Complex_Promotion:
4427   case ICK_Complex_Conversion: {
4428     QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4429     QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4430     CastKind CK;
4431     if (FromEl->isRealFloatingType()) {
4432       if (ToEl->isRealFloatingType())
4433         CK = CK_FloatingComplexCast;
4434       else
4435         CK = CK_FloatingComplexToIntegralComplex;
4436     } else if (ToEl->isRealFloatingType()) {
4437       CK = CK_IntegralComplexToFloatingComplex;
4438     } else {
4439       CK = CK_IntegralComplexCast;
4440     }
4441     From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4442                              CCK)
4443                .get();
4444     break;
4445   }
4446 
4447   case ICK_Floating_Integral:
4448     if (ToType->isRealFloatingType())
4449       From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue,
4450                                /*BasePath=*/nullptr, CCK)
4451                  .get();
4452     else
4453       From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue,
4454                                /*BasePath=*/nullptr, CCK)
4455                  .get();
4456     break;
4457 
4458   case ICK_Compatible_Conversion:
4459     From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4460                              /*BasePath=*/nullptr, CCK).get();
4461     break;
4462 
4463   case ICK_Writeback_Conversion:
4464   case ICK_Pointer_Conversion: {
4465     if (SCS.IncompatibleObjC && Action != AA_Casting) {
4466       // Diagnose incompatible Objective-C conversions
4467       if (Action == AA_Initializing || Action == AA_Assigning)
4468         Diag(From->getBeginLoc(),
4469              diag::ext_typecheck_convert_incompatible_pointer)
4470             << ToType << From->getType() << Action << From->getSourceRange()
4471             << 0;
4472       else
4473         Diag(From->getBeginLoc(),
4474              diag::ext_typecheck_convert_incompatible_pointer)
4475             << From->getType() << ToType << Action << From->getSourceRange()
4476             << 0;
4477 
4478       if (From->getType()->isObjCObjectPointerType() &&
4479           ToType->isObjCObjectPointerType())
4480         EmitRelatedResultTypeNote(From);
4481     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4482                !CheckObjCARCUnavailableWeakConversion(ToType,
4483                                                       From->getType())) {
4484       if (Action == AA_Initializing)
4485         Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4486       else
4487         Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4488             << (Action == AA_Casting) << From->getType() << ToType
4489             << From->getSourceRange();
4490     }
4491 
4492     // Defer address space conversion to the third conversion.
4493     QualType FromPteeType = From->getType()->getPointeeType();
4494     QualType ToPteeType = ToType->getPointeeType();
4495     QualType NewToType = ToType;
4496     if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4497         FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4498       NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4499       NewToType = Context.getAddrSpaceQualType(NewToType,
4500                                                FromPteeType.getAddressSpace());
4501       if (ToType->isObjCObjectPointerType())
4502         NewToType = Context.getObjCObjectPointerType(NewToType);
4503       else if (ToType->isBlockPointerType())
4504         NewToType = Context.getBlockPointerType(NewToType);
4505       else
4506         NewToType = Context.getPointerType(NewToType);
4507     }
4508 
4509     CastKind Kind;
4510     CXXCastPath BasePath;
4511     if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4512       return ExprError();
4513 
4514     // Make sure we extend blocks if necessary.
4515     // FIXME: doing this here is really ugly.
4516     if (Kind == CK_BlockPointerToObjCPointerCast) {
4517       ExprResult E = From;
4518       (void) PrepareCastToObjCObjectPointer(E);
4519       From = E.get();
4520     }
4521     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4522       CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4523     From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4524                .get();
4525     break;
4526   }
4527 
4528   case ICK_Pointer_Member: {
4529     CastKind Kind;
4530     CXXCastPath BasePath;
4531     if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4532       return ExprError();
4533     if (CheckExceptionSpecCompatibility(From, ToType))
4534       return ExprError();
4535 
4536     // We may not have been able to figure out what this member pointer resolved
4537     // to up until this exact point.  Attempt to lock-in it's inheritance model.
4538     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4539       (void)isCompleteType(From->getExprLoc(), From->getType());
4540       (void)isCompleteType(From->getExprLoc(), ToType);
4541     }
4542 
4543     From =
4544         ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4545     break;
4546   }
4547 
4548   case ICK_Boolean_Conversion:
4549     // Perform half-to-boolean conversion via float.
4550     if (From->getType()->isHalfType()) {
4551       From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4552       FromType = Context.FloatTy;
4553     }
4554 
4555     From = ImpCastExprToType(From, Context.BoolTy,
4556                              ScalarTypeToBooleanCastKind(FromType), VK_PRValue,
4557                              /*BasePath=*/nullptr, CCK)
4558                .get();
4559     break;
4560 
4561   case ICK_Derived_To_Base: {
4562     CXXCastPath BasePath;
4563     if (CheckDerivedToBaseConversion(
4564             From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4565             From->getSourceRange(), &BasePath, CStyle))
4566       return ExprError();
4567 
4568     From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4569                       CK_DerivedToBase, From->getValueKind(),
4570                       &BasePath, CCK).get();
4571     break;
4572   }
4573 
4574   case ICK_Vector_Conversion:
4575     From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4576                              /*BasePath=*/nullptr, CCK)
4577                .get();
4578     break;
4579 
4580   case ICK_SVE_Vector_Conversion:
4581     From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4582                              /*BasePath=*/nullptr, CCK)
4583                .get();
4584     break;
4585 
4586   case ICK_Vector_Splat: {
4587     // Vector splat from any arithmetic type to a vector.
4588     Expr *Elem = prepareVectorSplat(ToType, From).get();
4589     From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4590                              /*BasePath=*/nullptr, CCK)
4591                .get();
4592     break;
4593   }
4594 
4595   case ICK_Complex_Real:
4596     // Case 1.  x -> _Complex y
4597     if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4598       QualType ElType = ToComplex->getElementType();
4599       bool isFloatingComplex = ElType->isRealFloatingType();
4600 
4601       // x -> y
4602       if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4603         // do nothing
4604       } else if (From->getType()->isRealFloatingType()) {
4605         From = ImpCastExprToType(From, ElType,
4606                 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4607       } else {
4608         assert(From->getType()->isIntegerType());
4609         From = ImpCastExprToType(From, ElType,
4610                 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4611       }
4612       // y -> _Complex y
4613       From = ImpCastExprToType(From, ToType,
4614                    isFloatingComplex ? CK_FloatingRealToComplex
4615                                      : CK_IntegralRealToComplex).get();
4616 
4617     // Case 2.  _Complex x -> y
4618     } else {
4619       auto *FromComplex = From->getType()->castAs<ComplexType>();
4620       QualType ElType = FromComplex->getElementType();
4621       bool isFloatingComplex = ElType->isRealFloatingType();
4622 
4623       // _Complex x -> x
4624       From = ImpCastExprToType(From, ElType,
4625                                isFloatingComplex ? CK_FloatingComplexToReal
4626                                                  : CK_IntegralComplexToReal,
4627                                VK_PRValue, /*BasePath=*/nullptr, CCK)
4628                  .get();
4629 
4630       // x -> y
4631       if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4632         // do nothing
4633       } else if (ToType->isRealFloatingType()) {
4634         From = ImpCastExprToType(From, ToType,
4635                                  isFloatingComplex ? CK_FloatingCast
4636                                                    : CK_IntegralToFloating,
4637                                  VK_PRValue, /*BasePath=*/nullptr, CCK)
4638                    .get();
4639       } else {
4640         assert(ToType->isIntegerType());
4641         From = ImpCastExprToType(From, ToType,
4642                                  isFloatingComplex ? CK_FloatingToIntegral
4643                                                    : CK_IntegralCast,
4644                                  VK_PRValue, /*BasePath=*/nullptr, CCK)
4645                    .get();
4646       }
4647     }
4648     break;
4649 
4650   case ICK_Block_Pointer_Conversion: {
4651     LangAS AddrSpaceL =
4652         ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4653     LangAS AddrSpaceR =
4654         FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4655     assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4656            "Invalid cast");
4657     CastKind Kind =
4658         AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4659     From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4660                              VK_PRValue, /*BasePath=*/nullptr, CCK)
4661                .get();
4662     break;
4663   }
4664 
4665   case ICK_TransparentUnionConversion: {
4666     ExprResult FromRes = From;
4667     Sema::AssignConvertType ConvTy =
4668       CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4669     if (FromRes.isInvalid())
4670       return ExprError();
4671     From = FromRes.get();
4672     assert ((ConvTy == Sema::Compatible) &&
4673             "Improper transparent union conversion");
4674     (void)ConvTy;
4675     break;
4676   }
4677 
4678   case ICK_Zero_Event_Conversion:
4679   case ICK_Zero_Queue_Conversion:
4680     From = ImpCastExprToType(From, ToType,
4681                              CK_ZeroToOCLOpaqueType,
4682                              From->getValueKind()).get();
4683     break;
4684 
4685   case ICK_Lvalue_To_Rvalue:
4686   case ICK_Array_To_Pointer:
4687   case ICK_Function_To_Pointer:
4688   case ICK_Function_Conversion:
4689   case ICK_Qualification:
4690   case ICK_Num_Conversion_Kinds:
4691   case ICK_C_Only_Conversion:
4692   case ICK_Incompatible_Pointer_Conversion:
4693     llvm_unreachable("Improper second standard conversion");
4694   }
4695 
4696   switch (SCS.Third) {
4697   case ICK_Identity:
4698     // Nothing to do.
4699     break;
4700 
4701   case ICK_Function_Conversion:
4702     // If both sides are functions (or pointers/references to them), there could
4703     // be incompatible exception declarations.
4704     if (CheckExceptionSpecCompatibility(From, ToType))
4705       return ExprError();
4706 
4707     From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
4708                              /*BasePath=*/nullptr, CCK)
4709                .get();
4710     break;
4711 
4712   case ICK_Qualification: {
4713     ExprValueKind VK = From->getValueKind();
4714     CastKind CK = CK_NoOp;
4715 
4716     if (ToType->isReferenceType() &&
4717         ToType->getPointeeType().getAddressSpace() !=
4718             From->getType().getAddressSpace())
4719       CK = CK_AddressSpaceConversion;
4720 
4721     if (ToType->isPointerType() &&
4722         ToType->getPointeeType().getAddressSpace() !=
4723             From->getType()->getPointeeType().getAddressSpace())
4724       CK = CK_AddressSpaceConversion;
4725 
4726     if (!isCast(CCK) &&
4727         !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
4728         From->getType()->getPointeeType().getQualifiers().hasUnaligned()) {
4729       Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
4730           << InitialFromType << ToType;
4731     }
4732 
4733     From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4734                              /*BasePath=*/nullptr, CCK)
4735                .get();
4736 
4737     if (SCS.DeprecatedStringLiteralToCharPtr &&
4738         !getLangOpts().WritableStrings) {
4739       Diag(From->getBeginLoc(),
4740            getLangOpts().CPlusPlus11
4741                ? diag::ext_deprecated_string_literal_conversion
4742                : diag::warn_deprecated_string_literal_conversion)
4743           << ToType.getNonReferenceType();
4744     }
4745 
4746     break;
4747   }
4748 
4749   default:
4750     llvm_unreachable("Improper third standard conversion");
4751   }
4752 
4753   // If this conversion sequence involved a scalar -> atomic conversion, perform
4754   // that conversion now.
4755   if (!ToAtomicType.isNull()) {
4756     assert(Context.hasSameType(
4757         ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4758     From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4759                              VK_PRValue, nullptr, CCK)
4760                .get();
4761   }
4762 
4763   // Materialize a temporary if we're implicitly converting to a reference
4764   // type. This is not required by the C++ rules but is necessary to maintain
4765   // AST invariants.
4766   if (ToType->isReferenceType() && From->isPRValue()) {
4767     ExprResult Res = TemporaryMaterializationConversion(From);
4768     if (Res.isInvalid())
4769       return ExprError();
4770     From = Res.get();
4771   }
4772 
4773   // If this conversion sequence succeeded and involved implicitly converting a
4774   // _Nullable type to a _Nonnull one, complain.
4775   if (!isCast(CCK))
4776     diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4777                                         From->getBeginLoc());
4778 
4779   return From;
4780 }
4781 
4782 /// Check the completeness of a type in a unary type trait.
4783 ///
4784 /// If the particular type trait requires a complete type, tries to complete
4785 /// it. If completing the type fails, a diagnostic is emitted and false
4786 /// returned. If completing the type succeeds or no completion was required,
4787 /// returns true.
4788 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4789                                                 SourceLocation Loc,
4790                                                 QualType ArgTy) {
4791   // C++0x [meta.unary.prop]p3:
4792   //   For all of the class templates X declared in this Clause, instantiating
4793   //   that template with a template argument that is a class template
4794   //   specialization may result in the implicit instantiation of the template
4795   //   argument if and only if the semantics of X require that the argument
4796   //   must be a complete type.
4797   // We apply this rule to all the type trait expressions used to implement
4798   // these class templates. We also try to follow any GCC documented behavior
4799   // in these expressions to ensure portability of standard libraries.
4800   switch (UTT) {
4801   default: llvm_unreachable("not a UTT");
4802     // is_complete_type somewhat obviously cannot require a complete type.
4803   case UTT_IsCompleteType:
4804     // Fall-through
4805 
4806     // These traits are modeled on the type predicates in C++0x
4807     // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4808     // requiring a complete type, as whether or not they return true cannot be
4809     // impacted by the completeness of the type.
4810   case UTT_IsVoid:
4811   case UTT_IsIntegral:
4812   case UTT_IsFloatingPoint:
4813   case UTT_IsArray:
4814   case UTT_IsBoundedArray:
4815   case UTT_IsPointer:
4816   case UTT_IsNullPointer:
4817   case UTT_IsReferenceable:
4818   case UTT_IsLvalueReference:
4819   case UTT_IsRvalueReference:
4820   case UTT_IsMemberFunctionPointer:
4821   case UTT_IsMemberObjectPointer:
4822   case UTT_IsEnum:
4823   case UTT_IsScopedEnum:
4824   case UTT_IsUnion:
4825   case UTT_IsClass:
4826   case UTT_IsFunction:
4827   case UTT_IsReference:
4828   case UTT_IsArithmetic:
4829   case UTT_IsFundamental:
4830   case UTT_IsObject:
4831   case UTT_IsScalar:
4832   case UTT_IsCompound:
4833   case UTT_IsMemberPointer:
4834     // Fall-through
4835 
4836     // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4837     // which requires some of its traits to have the complete type. However,
4838     // the completeness of the type cannot impact these traits' semantics, and
4839     // so they don't require it. This matches the comments on these traits in
4840     // Table 49.
4841   case UTT_IsConst:
4842   case UTT_IsVolatile:
4843   case UTT_IsSigned:
4844   case UTT_IsUnboundedArray:
4845   case UTT_IsUnsigned:
4846 
4847   // This type trait always returns false, checking the type is moot.
4848   case UTT_IsInterfaceClass:
4849     return true;
4850 
4851   // C++14 [meta.unary.prop]:
4852   //   If T is a non-union class type, T shall be a complete type.
4853   case UTT_IsEmpty:
4854   case UTT_IsPolymorphic:
4855   case UTT_IsAbstract:
4856     if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4857       if (!RD->isUnion())
4858         return !S.RequireCompleteType(
4859             Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4860     return true;
4861 
4862   // C++14 [meta.unary.prop]:
4863   //   If T is a class type, T shall be a complete type.
4864   case UTT_IsFinal:
4865   case UTT_IsSealed:
4866     if (ArgTy->getAsCXXRecordDecl())
4867       return !S.RequireCompleteType(
4868           Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4869     return true;
4870 
4871   // LWG3823: T shall be an array type, a complete type, or cv void.
4872   case UTT_IsAggregate:
4873     if (ArgTy->isArrayType() || ArgTy->isVoidType())
4874       return true;
4875 
4876     return !S.RequireCompleteType(
4877         Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4878 
4879   // C++1z [meta.unary.prop]:
4880   //   remove_all_extents_t<T> shall be a complete type or cv void.
4881   case UTT_IsTrivial:
4882   case UTT_IsTriviallyCopyable:
4883   case UTT_IsStandardLayout:
4884   case UTT_IsPOD:
4885   case UTT_IsLiteral:
4886   // By analogy, is_trivially_relocatable imposes the same constraints.
4887   case UTT_IsTriviallyRelocatable:
4888   // Per the GCC type traits documentation, T shall be a complete type, cv void,
4889   // or an array of unknown bound. But GCC actually imposes the same constraints
4890   // as above.
4891   case UTT_HasNothrowAssign:
4892   case UTT_HasNothrowMoveAssign:
4893   case UTT_HasNothrowConstructor:
4894   case UTT_HasNothrowCopy:
4895   case UTT_HasTrivialAssign:
4896   case UTT_HasTrivialMoveAssign:
4897   case UTT_HasTrivialDefaultConstructor:
4898   case UTT_HasTrivialMoveConstructor:
4899   case UTT_HasTrivialCopy:
4900   case UTT_HasTrivialDestructor:
4901   case UTT_HasVirtualDestructor:
4902     ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4903     [[fallthrough]];
4904 
4905   // C++1z [meta.unary.prop]:
4906   //   T shall be a complete type, cv void, or an array of unknown bound.
4907   case UTT_IsDestructible:
4908   case UTT_IsNothrowDestructible:
4909   case UTT_IsTriviallyDestructible:
4910   case UTT_HasUniqueObjectRepresentations:
4911     if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4912       return true;
4913 
4914     return !S.RequireCompleteType(
4915         Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4916   }
4917 }
4918 
4919 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4920                                Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4921                                bool (CXXRecordDecl::*HasTrivial)() const,
4922                                bool (CXXRecordDecl::*HasNonTrivial)() const,
4923                                bool (CXXMethodDecl::*IsDesiredOp)() const)
4924 {
4925   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4926   if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4927     return true;
4928 
4929   DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4930   DeclarationNameInfo NameInfo(Name, KeyLoc);
4931   LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4932   if (Self.LookupQualifiedName(Res, RD)) {
4933     bool FoundOperator = false;
4934     Res.suppressDiagnostics();
4935     for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4936          Op != OpEnd; ++Op) {
4937       if (isa<FunctionTemplateDecl>(*Op))
4938         continue;
4939 
4940       CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4941       if((Operator->*IsDesiredOp)()) {
4942         FoundOperator = true;
4943         auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
4944         CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4945         if (!CPT || !CPT->isNothrow())
4946           return false;
4947       }
4948     }
4949     return FoundOperator;
4950   }
4951   return false;
4952 }
4953 
4954 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4955                                    SourceLocation KeyLoc, QualType T) {
4956   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4957 
4958   ASTContext &C = Self.Context;
4959   switch(UTT) {
4960   default: llvm_unreachable("not a UTT");
4961     // Type trait expressions corresponding to the primary type category
4962     // predicates in C++0x [meta.unary.cat].
4963   case UTT_IsVoid:
4964     return T->isVoidType();
4965   case UTT_IsIntegral:
4966     return T->isIntegralType(C);
4967   case UTT_IsFloatingPoint:
4968     return T->isFloatingType();
4969   case UTT_IsArray:
4970     return T->isArrayType();
4971   case UTT_IsBoundedArray:
4972     if (!T->isVariableArrayType()) {
4973       return T->isArrayType() && !T->isIncompleteArrayType();
4974     }
4975 
4976     Self.Diag(KeyLoc, diag::err_vla_unsupported)
4977         << 1 << tok::kw___is_bounded_array;
4978     return false;
4979   case UTT_IsUnboundedArray:
4980     if (!T->isVariableArrayType()) {
4981       return T->isIncompleteArrayType();
4982     }
4983 
4984     Self.Diag(KeyLoc, diag::err_vla_unsupported)
4985         << 1 << tok::kw___is_unbounded_array;
4986     return false;
4987   case UTT_IsPointer:
4988     return T->isAnyPointerType();
4989   case UTT_IsNullPointer:
4990     return T->isNullPtrType();
4991   case UTT_IsLvalueReference:
4992     return T->isLValueReferenceType();
4993   case UTT_IsRvalueReference:
4994     return T->isRValueReferenceType();
4995   case UTT_IsMemberFunctionPointer:
4996     return T->isMemberFunctionPointerType();
4997   case UTT_IsMemberObjectPointer:
4998     return T->isMemberDataPointerType();
4999   case UTT_IsEnum:
5000     return T->isEnumeralType();
5001   case UTT_IsScopedEnum:
5002     return T->isScopedEnumeralType();
5003   case UTT_IsUnion:
5004     return T->isUnionType();
5005   case UTT_IsClass:
5006     return T->isClassType() || T->isStructureType() || T->isInterfaceType();
5007   case UTT_IsFunction:
5008     return T->isFunctionType();
5009 
5010     // Type trait expressions which correspond to the convenient composition
5011     // predicates in C++0x [meta.unary.comp].
5012   case UTT_IsReference:
5013     return T->isReferenceType();
5014   case UTT_IsArithmetic:
5015     return T->isArithmeticType() && !T->isEnumeralType();
5016   case UTT_IsFundamental:
5017     return T->isFundamentalType();
5018   case UTT_IsObject:
5019     return T->isObjectType();
5020   case UTT_IsScalar:
5021     // Note: semantic analysis depends on Objective-C lifetime types to be
5022     // considered scalar types. However, such types do not actually behave
5023     // like scalar types at run time (since they may require retain/release
5024     // operations), so we report them as non-scalar.
5025     if (T->isObjCLifetimeType()) {
5026       switch (T.getObjCLifetime()) {
5027       case Qualifiers::OCL_None:
5028       case Qualifiers::OCL_ExplicitNone:
5029         return true;
5030 
5031       case Qualifiers::OCL_Strong:
5032       case Qualifiers::OCL_Weak:
5033       case Qualifiers::OCL_Autoreleasing:
5034         return false;
5035       }
5036     }
5037 
5038     return T->isScalarType();
5039   case UTT_IsCompound:
5040     return T->isCompoundType();
5041   case UTT_IsMemberPointer:
5042     return T->isMemberPointerType();
5043 
5044     // Type trait expressions which correspond to the type property predicates
5045     // in C++0x [meta.unary.prop].
5046   case UTT_IsConst:
5047     return T.isConstQualified();
5048   case UTT_IsVolatile:
5049     return T.isVolatileQualified();
5050   case UTT_IsTrivial:
5051     return T.isTrivialType(C);
5052   case UTT_IsTriviallyCopyable:
5053     return T.isTriviallyCopyableType(C);
5054   case UTT_IsStandardLayout:
5055     return T->isStandardLayoutType();
5056   case UTT_IsPOD:
5057     return T.isPODType(C);
5058   case UTT_IsLiteral:
5059     return T->isLiteralType(C);
5060   case UTT_IsEmpty:
5061     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5062       return !RD->isUnion() && RD->isEmpty();
5063     return false;
5064   case UTT_IsPolymorphic:
5065     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5066       return !RD->isUnion() && RD->isPolymorphic();
5067     return false;
5068   case UTT_IsAbstract:
5069     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5070       return !RD->isUnion() && RD->isAbstract();
5071     return false;
5072   case UTT_IsAggregate:
5073     // Report vector extensions and complex types as aggregates because they
5074     // support aggregate initialization. GCC mirrors this behavior for vectors
5075     // but not _Complex.
5076     return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
5077            T->isAnyComplexType();
5078   // __is_interface_class only returns true when CL is invoked in /CLR mode and
5079   // even then only when it is used with the 'interface struct ...' syntax
5080   // Clang doesn't support /CLR which makes this type trait moot.
5081   case UTT_IsInterfaceClass:
5082     return false;
5083   case UTT_IsFinal:
5084   case UTT_IsSealed:
5085     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5086       return RD->hasAttr<FinalAttr>();
5087     return false;
5088   case UTT_IsSigned:
5089     // Enum types should always return false.
5090     // Floating points should always return true.
5091     return T->isFloatingType() ||
5092            (T->isSignedIntegerType() && !T->isEnumeralType());
5093   case UTT_IsUnsigned:
5094     // Enum types should always return false.
5095     return T->isUnsignedIntegerType() && !T->isEnumeralType();
5096 
5097     // Type trait expressions which query classes regarding their construction,
5098     // destruction, and copying. Rather than being based directly on the
5099     // related type predicates in the standard, they are specified by both
5100     // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
5101     // specifications.
5102     //
5103     //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
5104     //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5105     //
5106     // Note that these builtins do not behave as documented in g++: if a class
5107     // has both a trivial and a non-trivial special member of a particular kind,
5108     // they return false! For now, we emulate this behavior.
5109     // FIXME: This appears to be a g++ bug: more complex cases reveal that it
5110     // does not correctly compute triviality in the presence of multiple special
5111     // members of the same kind. Revisit this once the g++ bug is fixed.
5112   case UTT_HasTrivialDefaultConstructor:
5113     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5114     //   If __is_pod (type) is true then the trait is true, else if type is
5115     //   a cv class or union type (or array thereof) with a trivial default
5116     //   constructor ([class.ctor]) then the trait is true, else it is false.
5117     if (T.isPODType(C))
5118       return true;
5119     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5120       return RD->hasTrivialDefaultConstructor() &&
5121              !RD->hasNonTrivialDefaultConstructor();
5122     return false;
5123   case UTT_HasTrivialMoveConstructor:
5124     //  This trait is implemented by MSVC 2012 and needed to parse the
5125     //  standard library headers. Specifically this is used as the logic
5126     //  behind std::is_trivially_move_constructible (20.9.4.3).
5127     if (T.isPODType(C))
5128       return true;
5129     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5130       return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
5131     return false;
5132   case UTT_HasTrivialCopy:
5133     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5134     //   If __is_pod (type) is true or type is a reference type then
5135     //   the trait is true, else if type is a cv class or union type
5136     //   with a trivial copy constructor ([class.copy]) then the trait
5137     //   is true, else it is false.
5138     if (T.isPODType(C) || T->isReferenceType())
5139       return true;
5140     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5141       return RD->hasTrivialCopyConstructor() &&
5142              !RD->hasNonTrivialCopyConstructor();
5143     return false;
5144   case UTT_HasTrivialMoveAssign:
5145     //  This trait is implemented by MSVC 2012 and needed to parse the
5146     //  standard library headers. Specifically it is used as the logic
5147     //  behind std::is_trivially_move_assignable (20.9.4.3)
5148     if (T.isPODType(C))
5149       return true;
5150     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5151       return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
5152     return false;
5153   case UTT_HasTrivialAssign:
5154     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5155     //   If type is const qualified or is a reference type then the
5156     //   trait is false. Otherwise if __is_pod (type) is true then the
5157     //   trait is true, else if type is a cv class or union type with
5158     //   a trivial copy assignment ([class.copy]) then the trait is
5159     //   true, else it is false.
5160     // Note: the const and reference restrictions are interesting,
5161     // given that const and reference members don't prevent a class
5162     // from having a trivial copy assignment operator (but do cause
5163     // errors if the copy assignment operator is actually used, q.v.
5164     // [class.copy]p12).
5165 
5166     if (T.isConstQualified())
5167       return false;
5168     if (T.isPODType(C))
5169       return true;
5170     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5171       return RD->hasTrivialCopyAssignment() &&
5172              !RD->hasNonTrivialCopyAssignment();
5173     return false;
5174   case UTT_IsDestructible:
5175   case UTT_IsTriviallyDestructible:
5176   case UTT_IsNothrowDestructible:
5177     // C++14 [meta.unary.prop]:
5178     //   For reference types, is_destructible<T>::value is true.
5179     if (T->isReferenceType())
5180       return true;
5181 
5182     // Objective-C++ ARC: autorelease types don't require destruction.
5183     if (T->isObjCLifetimeType() &&
5184         T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5185       return true;
5186 
5187     // C++14 [meta.unary.prop]:
5188     //   For incomplete types and function types, is_destructible<T>::value is
5189     //   false.
5190     if (T->isIncompleteType() || T->isFunctionType())
5191       return false;
5192 
5193     // A type that requires destruction (via a non-trivial destructor or ARC
5194     // lifetime semantics) is not trivially-destructible.
5195     if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
5196       return false;
5197 
5198     // C++14 [meta.unary.prop]:
5199     //   For object types and given U equal to remove_all_extents_t<T>, if the
5200     //   expression std::declval<U&>().~U() is well-formed when treated as an
5201     //   unevaluated operand (Clause 5), then is_destructible<T>::value is true
5202     if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5203       CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
5204       if (!Destructor)
5205         return false;
5206       //  C++14 [dcl.fct.def.delete]p2:
5207       //    A program that refers to a deleted function implicitly or
5208       //    explicitly, other than to declare it, is ill-formed.
5209       if (Destructor->isDeleted())
5210         return false;
5211       if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
5212         return false;
5213       if (UTT == UTT_IsNothrowDestructible) {
5214         auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
5215         CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5216         if (!CPT || !CPT->isNothrow())
5217           return false;
5218       }
5219     }
5220     return true;
5221 
5222   case UTT_HasTrivialDestructor:
5223     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5224     //   If __is_pod (type) is true or type is a reference type
5225     //   then the trait is true, else if type is a cv class or union
5226     //   type (or array thereof) with a trivial destructor
5227     //   ([class.dtor]) then the trait is true, else it is
5228     //   false.
5229     if (T.isPODType(C) || T->isReferenceType())
5230       return true;
5231 
5232     // Objective-C++ ARC: autorelease types don't require destruction.
5233     if (T->isObjCLifetimeType() &&
5234         T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5235       return true;
5236 
5237     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5238       return RD->hasTrivialDestructor();
5239     return false;
5240   // TODO: Propagate nothrowness for implicitly declared special members.
5241   case UTT_HasNothrowAssign:
5242     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5243     //   If type is const qualified or is a reference type then the
5244     //   trait is false. Otherwise if __has_trivial_assign (type)
5245     //   is true then the trait is true, else if type is a cv class
5246     //   or union type with copy assignment operators that are known
5247     //   not to throw an exception then the trait is true, else it is
5248     //   false.
5249     if (C.getBaseElementType(T).isConstQualified())
5250       return false;
5251     if (T->isReferenceType())
5252       return false;
5253     if (T.isPODType(C) || T->isObjCLifetimeType())
5254       return true;
5255 
5256     if (const RecordType *RT = T->getAs<RecordType>())
5257       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5258                                 &CXXRecordDecl::hasTrivialCopyAssignment,
5259                                 &CXXRecordDecl::hasNonTrivialCopyAssignment,
5260                                 &CXXMethodDecl::isCopyAssignmentOperator);
5261     return false;
5262   case UTT_HasNothrowMoveAssign:
5263     //  This trait is implemented by MSVC 2012 and needed to parse the
5264     //  standard library headers. Specifically this is used as the logic
5265     //  behind std::is_nothrow_move_assignable (20.9.4.3).
5266     if (T.isPODType(C))
5267       return true;
5268 
5269     if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
5270       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5271                                 &CXXRecordDecl::hasTrivialMoveAssignment,
5272                                 &CXXRecordDecl::hasNonTrivialMoveAssignment,
5273                                 &CXXMethodDecl::isMoveAssignmentOperator);
5274     return false;
5275   case UTT_HasNothrowCopy:
5276     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5277     //   If __has_trivial_copy (type) is true then the trait is true, else
5278     //   if type is a cv class or union type with copy constructors that are
5279     //   known not to throw an exception then the trait is true, else it is
5280     //   false.
5281     if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
5282       return true;
5283     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
5284       if (RD->hasTrivialCopyConstructor() &&
5285           !RD->hasNonTrivialCopyConstructor())
5286         return true;
5287 
5288       bool FoundConstructor = false;
5289       unsigned FoundTQs;
5290       for (const auto *ND : Self.LookupConstructors(RD)) {
5291         // A template constructor is never a copy constructor.
5292         // FIXME: However, it may actually be selected at the actual overload
5293         // resolution point.
5294         if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5295           continue;
5296         // UsingDecl itself is not a constructor
5297         if (isa<UsingDecl>(ND))
5298           continue;
5299         auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5300         if (Constructor->isCopyConstructor(FoundTQs)) {
5301           FoundConstructor = true;
5302           auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5303           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5304           if (!CPT)
5305             return false;
5306           // TODO: check whether evaluating default arguments can throw.
5307           // For now, we'll be conservative and assume that they can throw.
5308           if (!CPT->isNothrow() || CPT->getNumParams() > 1)
5309             return false;
5310         }
5311       }
5312 
5313       return FoundConstructor;
5314     }
5315     return false;
5316   case UTT_HasNothrowConstructor:
5317     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5318     //   If __has_trivial_constructor (type) is true then the trait is
5319     //   true, else if type is a cv class or union type (or array
5320     //   thereof) with a default constructor that is known not to
5321     //   throw an exception then the trait is true, else it is false.
5322     if (T.isPODType(C) || T->isObjCLifetimeType())
5323       return true;
5324     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5325       if (RD->hasTrivialDefaultConstructor() &&
5326           !RD->hasNonTrivialDefaultConstructor())
5327         return true;
5328 
5329       bool FoundConstructor = false;
5330       for (const auto *ND : Self.LookupConstructors(RD)) {
5331         // FIXME: In C++0x, a constructor template can be a default constructor.
5332         if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5333           continue;
5334         // UsingDecl itself is not a constructor
5335         if (isa<UsingDecl>(ND))
5336           continue;
5337         auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5338         if (Constructor->isDefaultConstructor()) {
5339           FoundConstructor = true;
5340           auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5341           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5342           if (!CPT)
5343             return false;
5344           // FIXME: check whether evaluating default arguments can throw.
5345           // For now, we'll be conservative and assume that they can throw.
5346           if (!CPT->isNothrow() || CPT->getNumParams() > 0)
5347             return false;
5348         }
5349       }
5350       return FoundConstructor;
5351     }
5352     return false;
5353   case UTT_HasVirtualDestructor:
5354     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5355     //   If type is a class type with a virtual destructor ([class.dtor])
5356     //   then the trait is true, else it is false.
5357     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5358       if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5359         return Destructor->isVirtual();
5360     return false;
5361 
5362     // These type trait expressions are modeled on the specifications for the
5363     // Embarcadero C++0x type trait functions:
5364     //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5365   case UTT_IsCompleteType:
5366     // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5367     //   Returns True if and only if T is a complete type at the point of the
5368     //   function call.
5369     return !T->isIncompleteType();
5370   case UTT_HasUniqueObjectRepresentations:
5371     return C.hasUniqueObjectRepresentations(T);
5372   case UTT_IsTriviallyRelocatable:
5373     return T.isTriviallyRelocatableType(C);
5374   case UTT_IsReferenceable:
5375     return T.isReferenceable();
5376   }
5377 }
5378 
5379 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5380                                     QualType RhsT, SourceLocation KeyLoc);
5381 
5382 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
5383                               ArrayRef<TypeSourceInfo *> Args,
5384                               SourceLocation RParenLoc) {
5385   if (Kind <= UTT_Last)
5386     return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
5387 
5388   // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
5389   // traits to avoid duplication.
5390   if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
5391     return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
5392                                    Args[1]->getType(), RParenLoc);
5393 
5394   switch (Kind) {
5395   case clang::BTT_ReferenceBindsToTemporary:
5396   case clang::TT_IsConstructible:
5397   case clang::TT_IsNothrowConstructible:
5398   case clang::TT_IsTriviallyConstructible: {
5399     // C++11 [meta.unary.prop]:
5400     //   is_trivially_constructible is defined as:
5401     //
5402     //     is_constructible<T, Args...>::value is true and the variable
5403     //     definition for is_constructible, as defined below, is known to call
5404     //     no operation that is not trivial.
5405     //
5406     //   The predicate condition for a template specialization
5407     //   is_constructible<T, Args...> shall be satisfied if and only if the
5408     //   following variable definition would be well-formed for some invented
5409     //   variable t:
5410     //
5411     //     T t(create<Args>()...);
5412     assert(!Args.empty());
5413 
5414     // Precondition: T and all types in the parameter pack Args shall be
5415     // complete types, (possibly cv-qualified) void, or arrays of
5416     // unknown bound.
5417     for (const auto *TSI : Args) {
5418       QualType ArgTy = TSI->getType();
5419       if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
5420         continue;
5421 
5422       if (S.RequireCompleteType(KWLoc, ArgTy,
5423           diag::err_incomplete_type_used_in_type_trait_expr))
5424         return false;
5425     }
5426 
5427     // Make sure the first argument is not incomplete nor a function type.
5428     QualType T = Args[0]->getType();
5429     if (T->isIncompleteType() || T->isFunctionType())
5430       return false;
5431 
5432     // Make sure the first argument is not an abstract type.
5433     CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5434     if (RD && RD->isAbstract())
5435       return false;
5436 
5437     llvm::BumpPtrAllocator OpaqueExprAllocator;
5438     SmallVector<Expr *, 2> ArgExprs;
5439     ArgExprs.reserve(Args.size() - 1);
5440     for (unsigned I = 1, N = Args.size(); I != N; ++I) {
5441       QualType ArgTy = Args[I]->getType();
5442       if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5443         ArgTy = S.Context.getRValueReferenceType(ArgTy);
5444       ArgExprs.push_back(
5445           new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5446               OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
5447                               ArgTy.getNonLValueExprType(S.Context),
5448                               Expr::getValueKindForType(ArgTy)));
5449     }
5450 
5451     // Perform the initialization in an unevaluated context within a SFINAE
5452     // trap at translation unit scope.
5453     EnterExpressionEvaluationContext Unevaluated(
5454         S, Sema::ExpressionEvaluationContext::Unevaluated);
5455     Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5456     Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
5457     InitializedEntity To(
5458         InitializedEntity::InitializeTemporary(S.Context, Args[0]));
5459     InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
5460                                                                  RParenLoc));
5461     InitializationSequence Init(S, To, InitKind, ArgExprs);
5462     if (Init.Failed())
5463       return false;
5464 
5465     ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5466     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5467       return false;
5468 
5469     if (Kind == clang::TT_IsConstructible)
5470       return true;
5471 
5472     if (Kind == clang::BTT_ReferenceBindsToTemporary) {
5473       if (!T->isReferenceType())
5474         return false;
5475 
5476       return !Init.isDirectReferenceBinding();
5477     }
5478 
5479     if (Kind == clang::TT_IsNothrowConstructible)
5480       return S.canThrow(Result.get()) == CT_Cannot;
5481 
5482     if (Kind == clang::TT_IsTriviallyConstructible) {
5483       // Under Objective-C ARC and Weak, if the destination has non-trivial
5484       // Objective-C lifetime, this is a non-trivial construction.
5485       if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5486         return false;
5487 
5488       // The initialization succeeded; now make sure there are no non-trivial
5489       // calls.
5490       return !Result.get()->hasNonTrivialCall(S.Context);
5491     }
5492 
5493     llvm_unreachable("unhandled type trait");
5494     return false;
5495   }
5496     default: llvm_unreachable("not a TT");
5497   }
5498 
5499   return false;
5500 }
5501 
5502 namespace {
5503 void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind,
5504                                 SourceLocation KWLoc) {
5505   TypeTrait Replacement;
5506   switch (Kind) {
5507     case UTT_HasNothrowAssign:
5508     case UTT_HasNothrowMoveAssign:
5509       Replacement = BTT_IsNothrowAssignable;
5510       break;
5511     case UTT_HasNothrowCopy:
5512     case UTT_HasNothrowConstructor:
5513       Replacement = TT_IsNothrowConstructible;
5514       break;
5515     case UTT_HasTrivialAssign:
5516     case UTT_HasTrivialMoveAssign:
5517       Replacement = BTT_IsTriviallyAssignable;
5518       break;
5519     case UTT_HasTrivialCopy:
5520       Replacement = UTT_IsTriviallyCopyable;
5521       break;
5522     case UTT_HasTrivialDefaultConstructor:
5523     case UTT_HasTrivialMoveConstructor:
5524       Replacement = TT_IsTriviallyConstructible;
5525       break;
5526     case UTT_HasTrivialDestructor:
5527       Replacement = UTT_IsTriviallyDestructible;
5528       break;
5529     default:
5530       return;
5531   }
5532   S.Diag(KWLoc, diag::warn_deprecated_builtin)
5533     << getTraitSpelling(Kind) << getTraitSpelling(Replacement);
5534 }
5535 }
5536 
5537 bool Sema::CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N) {
5538   if (Arity && N != Arity) {
5539     Diag(Loc, diag::err_type_trait_arity)
5540         << Arity << 0 << (Arity > 1) << (int)N << SourceRange(Loc);
5541     return false;
5542   }
5543 
5544   if (!Arity && N == 0) {
5545     Diag(Loc, diag::err_type_trait_arity)
5546         << 1 << 1 << 1 << (int)N << SourceRange(Loc);
5547     return false;
5548   }
5549   return true;
5550 }
5551 
5552 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5553                                 ArrayRef<TypeSourceInfo *> Args,
5554                                 SourceLocation RParenLoc) {
5555   if (!CheckTypeTraitArity(getTypeTraitArity(Kind), KWLoc, Args.size()))
5556     return ExprError();
5557   QualType ResultType = Context.getLogicalOperationType();
5558 
5559   if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5560                                *this, Kind, KWLoc, Args[0]->getType()))
5561     return ExprError();
5562 
5563   DiagnoseBuiltinDeprecation(*this, Kind, KWLoc);
5564 
5565   bool Dependent = false;
5566   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5567     if (Args[I]->getType()->isDependentType()) {
5568       Dependent = true;
5569       break;
5570     }
5571   }
5572 
5573   bool Result = false;
5574   if (!Dependent)
5575     Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5576 
5577   return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5578                                RParenLoc, Result);
5579 }
5580 
5581 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5582                                 ArrayRef<ParsedType> Args,
5583                                 SourceLocation RParenLoc) {
5584   SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5585   ConvertedArgs.reserve(Args.size());
5586 
5587   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5588     TypeSourceInfo *TInfo;
5589     QualType T = GetTypeFromParser(Args[I], &TInfo);
5590     if (!TInfo)
5591       TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5592 
5593     ConvertedArgs.push_back(TInfo);
5594   }
5595 
5596   return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5597 }
5598 
5599 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5600                                     QualType RhsT, SourceLocation KeyLoc) {
5601   assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5602          "Cannot evaluate traits of dependent types");
5603 
5604   switch(BTT) {
5605   case BTT_IsBaseOf: {
5606     // C++0x [meta.rel]p2
5607     // Base is a base class of Derived without regard to cv-qualifiers or
5608     // Base and Derived are not unions and name the same class type without
5609     // regard to cv-qualifiers.
5610 
5611     const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5612     const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5613     if (!rhsRecord || !lhsRecord) {
5614       const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5615       const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5616       if (!LHSObjTy || !RHSObjTy)
5617         return false;
5618 
5619       ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5620       ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5621       if (!BaseInterface || !DerivedInterface)
5622         return false;
5623 
5624       if (Self.RequireCompleteType(
5625               KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5626         return false;
5627 
5628       return BaseInterface->isSuperClassOf(DerivedInterface);
5629     }
5630 
5631     assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5632              == (lhsRecord == rhsRecord));
5633 
5634     // Unions are never base classes, and never have base classes.
5635     // It doesn't matter if they are complete or not. See PR#41843
5636     if (lhsRecord && lhsRecord->getDecl()->isUnion())
5637       return false;
5638     if (rhsRecord && rhsRecord->getDecl()->isUnion())
5639       return false;
5640 
5641     if (lhsRecord == rhsRecord)
5642       return true;
5643 
5644     // C++0x [meta.rel]p2:
5645     //   If Base and Derived are class types and are different types
5646     //   (ignoring possible cv-qualifiers) then Derived shall be a
5647     //   complete type.
5648     if (Self.RequireCompleteType(KeyLoc, RhsT,
5649                           diag::err_incomplete_type_used_in_type_trait_expr))
5650       return false;
5651 
5652     return cast<CXXRecordDecl>(rhsRecord->getDecl())
5653       ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5654   }
5655   case BTT_IsSame:
5656     return Self.Context.hasSameType(LhsT, RhsT);
5657   case BTT_TypeCompatible: {
5658     // GCC ignores cv-qualifiers on arrays for this builtin.
5659     Qualifiers LhsQuals, RhsQuals;
5660     QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5661     QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5662     return Self.Context.typesAreCompatible(Lhs, Rhs);
5663   }
5664   case BTT_IsConvertible:
5665   case BTT_IsConvertibleTo: {
5666     // C++0x [meta.rel]p4:
5667     //   Given the following function prototype:
5668     //
5669     //     template <class T>
5670     //       typename add_rvalue_reference<T>::type create();
5671     //
5672     //   the predicate condition for a template specialization
5673     //   is_convertible<From, To> shall be satisfied if and only if
5674     //   the return expression in the following code would be
5675     //   well-formed, including any implicit conversions to the return
5676     //   type of the function:
5677     //
5678     //     To test() {
5679     //       return create<From>();
5680     //     }
5681     //
5682     //   Access checking is performed as if in a context unrelated to To and
5683     //   From. Only the validity of the immediate context of the expression
5684     //   of the return-statement (including conversions to the return type)
5685     //   is considered.
5686     //
5687     // We model the initialization as a copy-initialization of a temporary
5688     // of the appropriate type, which for this expression is identical to the
5689     // return statement (since NRVO doesn't apply).
5690 
5691     // Functions aren't allowed to return function or array types.
5692     if (RhsT->isFunctionType() || RhsT->isArrayType())
5693       return false;
5694 
5695     // A return statement in a void function must have void type.
5696     if (RhsT->isVoidType())
5697       return LhsT->isVoidType();
5698 
5699     // A function definition requires a complete, non-abstract return type.
5700     if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5701       return false;
5702 
5703     // Compute the result of add_rvalue_reference.
5704     if (LhsT->isObjectType() || LhsT->isFunctionType())
5705       LhsT = Self.Context.getRValueReferenceType(LhsT);
5706 
5707     // Build a fake source and destination for initialization.
5708     InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
5709     OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5710                          Expr::getValueKindForType(LhsT));
5711     Expr *FromPtr = &From;
5712     InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
5713                                                            SourceLocation()));
5714 
5715     // Perform the initialization in an unevaluated context within a SFINAE
5716     // trap at translation unit scope.
5717     EnterExpressionEvaluationContext Unevaluated(
5718         Self, Sema::ExpressionEvaluationContext::Unevaluated);
5719     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5720     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5721     InitializationSequence Init(Self, To, Kind, FromPtr);
5722     if (Init.Failed())
5723       return false;
5724 
5725     ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5726     return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5727   }
5728 
5729   case BTT_IsAssignable:
5730   case BTT_IsNothrowAssignable:
5731   case BTT_IsTriviallyAssignable: {
5732     // C++11 [meta.unary.prop]p3:
5733     //   is_trivially_assignable is defined as:
5734     //     is_assignable<T, U>::value is true and the assignment, as defined by
5735     //     is_assignable, is known to call no operation that is not trivial
5736     //
5737     //   is_assignable is defined as:
5738     //     The expression declval<T>() = declval<U>() is well-formed when
5739     //     treated as an unevaluated operand (Clause 5).
5740     //
5741     //   For both, T and U shall be complete types, (possibly cv-qualified)
5742     //   void, or arrays of unknown bound.
5743     if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5744         Self.RequireCompleteType(KeyLoc, LhsT,
5745           diag::err_incomplete_type_used_in_type_trait_expr))
5746       return false;
5747     if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5748         Self.RequireCompleteType(KeyLoc, RhsT,
5749           diag::err_incomplete_type_used_in_type_trait_expr))
5750       return false;
5751 
5752     // cv void is never assignable.
5753     if (LhsT->isVoidType() || RhsT->isVoidType())
5754       return false;
5755 
5756     // Build expressions that emulate the effect of declval<T>() and
5757     // declval<U>().
5758     if (LhsT->isObjectType() || LhsT->isFunctionType())
5759       LhsT = Self.Context.getRValueReferenceType(LhsT);
5760     if (RhsT->isObjectType() || RhsT->isFunctionType())
5761       RhsT = Self.Context.getRValueReferenceType(RhsT);
5762     OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5763                         Expr::getValueKindForType(LhsT));
5764     OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5765                         Expr::getValueKindForType(RhsT));
5766 
5767     // Attempt the assignment in an unevaluated context within a SFINAE
5768     // trap at translation unit scope.
5769     EnterExpressionEvaluationContext Unevaluated(
5770         Self, Sema::ExpressionEvaluationContext::Unevaluated);
5771     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5772     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5773     ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5774                                         &Rhs);
5775     if (Result.isInvalid())
5776       return false;
5777 
5778     // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
5779     Self.CheckUnusedVolatileAssignment(Result.get());
5780 
5781     if (SFINAE.hasErrorOccurred())
5782       return false;
5783 
5784     if (BTT == BTT_IsAssignable)
5785       return true;
5786 
5787     if (BTT == BTT_IsNothrowAssignable)
5788       return Self.canThrow(Result.get()) == CT_Cannot;
5789 
5790     if (BTT == BTT_IsTriviallyAssignable) {
5791       // Under Objective-C ARC and Weak, if the destination has non-trivial
5792       // Objective-C lifetime, this is a non-trivial assignment.
5793       if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
5794         return false;
5795 
5796       return !Result.get()->hasNonTrivialCall(Self.Context);
5797     }
5798 
5799     llvm_unreachable("unhandled type trait");
5800     return false;
5801   }
5802     default: llvm_unreachable("not a BTT");
5803   }
5804   llvm_unreachable("Unknown type trait or not implemented");
5805 }
5806 
5807 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5808                                      SourceLocation KWLoc,
5809                                      ParsedType Ty,
5810                                      Expr* DimExpr,
5811                                      SourceLocation RParen) {
5812   TypeSourceInfo *TSInfo;
5813   QualType T = GetTypeFromParser(Ty, &TSInfo);
5814   if (!TSInfo)
5815     TSInfo = Context.getTrivialTypeSourceInfo(T);
5816 
5817   return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5818 }
5819 
5820 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5821                                            QualType T, Expr *DimExpr,
5822                                            SourceLocation KeyLoc) {
5823   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5824 
5825   switch(ATT) {
5826   case ATT_ArrayRank:
5827     if (T->isArrayType()) {
5828       unsigned Dim = 0;
5829       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5830         ++Dim;
5831         T = AT->getElementType();
5832       }
5833       return Dim;
5834     }
5835     return 0;
5836 
5837   case ATT_ArrayExtent: {
5838     llvm::APSInt Value;
5839     uint64_t Dim;
5840     if (Self.VerifyIntegerConstantExpression(
5841                 DimExpr, &Value, diag::err_dimension_expr_not_constant_integer)
5842             .isInvalid())
5843       return 0;
5844     if (Value.isSigned() && Value.isNegative()) {
5845       Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5846         << DimExpr->getSourceRange();
5847       return 0;
5848     }
5849     Dim = Value.getLimitedValue();
5850 
5851     if (T->isArrayType()) {
5852       unsigned D = 0;
5853       bool Matched = false;
5854       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5855         if (Dim == D) {
5856           Matched = true;
5857           break;
5858         }
5859         ++D;
5860         T = AT->getElementType();
5861       }
5862 
5863       if (Matched && T->isArrayType()) {
5864         if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5865           return CAT->getSize().getLimitedValue();
5866       }
5867     }
5868     return 0;
5869   }
5870   }
5871   llvm_unreachable("Unknown type trait or not implemented");
5872 }
5873 
5874 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5875                                      SourceLocation KWLoc,
5876                                      TypeSourceInfo *TSInfo,
5877                                      Expr* DimExpr,
5878                                      SourceLocation RParen) {
5879   QualType T = TSInfo->getType();
5880 
5881   // FIXME: This should likely be tracked as an APInt to remove any host
5882   // assumptions about the width of size_t on the target.
5883   uint64_t Value = 0;
5884   if (!T->isDependentType())
5885     Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5886 
5887   // While the specification for these traits from the Embarcadero C++
5888   // compiler's documentation says the return type is 'unsigned int', Clang
5889   // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5890   // compiler, there is no difference. On several other platforms this is an
5891   // important distinction.
5892   return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5893                                           RParen, Context.getSizeType());
5894 }
5895 
5896 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
5897                                       SourceLocation KWLoc,
5898                                       Expr *Queried,
5899                                       SourceLocation RParen) {
5900   // If error parsing the expression, ignore.
5901   if (!Queried)
5902     return ExprError();
5903 
5904   ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5905 
5906   return Result;
5907 }
5908 
5909 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5910   switch (ET) {
5911   case ET_IsLValueExpr: return E->isLValue();
5912   case ET_IsRValueExpr:
5913     return E->isPRValue();
5914   }
5915   llvm_unreachable("Expression trait not covered by switch");
5916 }
5917 
5918 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5919                                       SourceLocation KWLoc,
5920                                       Expr *Queried,
5921                                       SourceLocation RParen) {
5922   if (Queried->isTypeDependent()) {
5923     // Delay type-checking for type-dependent expressions.
5924   } else if (Queried->hasPlaceholderType()) {
5925     ExprResult PE = CheckPlaceholderExpr(Queried);
5926     if (PE.isInvalid()) return ExprError();
5927     return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5928   }
5929 
5930   bool Value = EvaluateExpressionTrait(ET, Queried);
5931 
5932   return new (Context)
5933       ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5934 }
5935 
5936 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5937                                             ExprValueKind &VK,
5938                                             SourceLocation Loc,
5939                                             bool isIndirect) {
5940   assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
5941          "placeholders should have been weeded out by now");
5942 
5943   // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5944   // temporary materialization conversion otherwise.
5945   if (isIndirect)
5946     LHS = DefaultLvalueConversion(LHS.get());
5947   else if (LHS.get()->isPRValue())
5948     LHS = TemporaryMaterializationConversion(LHS.get());
5949   if (LHS.isInvalid())
5950     return QualType();
5951 
5952   // The RHS always undergoes lvalue conversions.
5953   RHS = DefaultLvalueConversion(RHS.get());
5954   if (RHS.isInvalid()) return QualType();
5955 
5956   const char *OpSpelling = isIndirect ? "->*" : ".*";
5957   // C++ 5.5p2
5958   //   The binary operator .* [p3: ->*] binds its second operand, which shall
5959   //   be of type "pointer to member of T" (where T is a completely-defined
5960   //   class type) [...]
5961   QualType RHSType = RHS.get()->getType();
5962   const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5963   if (!MemPtr) {
5964     Diag(Loc, diag::err_bad_memptr_rhs)
5965       << OpSpelling << RHSType << RHS.get()->getSourceRange();
5966     return QualType();
5967   }
5968 
5969   QualType Class(MemPtr->getClass(), 0);
5970 
5971   // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5972   // member pointer points must be completely-defined. However, there is no
5973   // reason for this semantic distinction, and the rule is not enforced by
5974   // other compilers. Therefore, we do not check this property, as it is
5975   // likely to be considered a defect.
5976 
5977   // C++ 5.5p2
5978   //   [...] to its first operand, which shall be of class T or of a class of
5979   //   which T is an unambiguous and accessible base class. [p3: a pointer to
5980   //   such a class]
5981   QualType LHSType = LHS.get()->getType();
5982   if (isIndirect) {
5983     if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5984       LHSType = Ptr->getPointeeType();
5985     else {
5986       Diag(Loc, diag::err_bad_memptr_lhs)
5987         << OpSpelling << 1 << LHSType
5988         << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5989       return QualType();
5990     }
5991   }
5992 
5993   if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5994     // If we want to check the hierarchy, we need a complete type.
5995     if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5996                             OpSpelling, (int)isIndirect)) {
5997       return QualType();
5998     }
5999 
6000     if (!IsDerivedFrom(Loc, LHSType, Class)) {
6001       Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
6002         << (int)isIndirect << LHS.get()->getType();
6003       return QualType();
6004     }
6005 
6006     CXXCastPath BasePath;
6007     if (CheckDerivedToBaseConversion(
6008             LHSType, Class, Loc,
6009             SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
6010             &BasePath))
6011       return QualType();
6012 
6013     // Cast LHS to type of use.
6014     QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
6015     if (isIndirect)
6016       UseType = Context.getPointerType(UseType);
6017     ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
6018     LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
6019                             &BasePath);
6020   }
6021 
6022   if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
6023     // Diagnose use of pointer-to-member type which when used as
6024     // the functional cast in a pointer-to-member expression.
6025     Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
6026      return QualType();
6027   }
6028 
6029   // C++ 5.5p2
6030   //   The result is an object or a function of the type specified by the
6031   //   second operand.
6032   // The cv qualifiers are the union of those in the pointer and the left side,
6033   // in accordance with 5.5p5 and 5.2.5.
6034   QualType Result = MemPtr->getPointeeType();
6035   Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
6036 
6037   // C++0x [expr.mptr.oper]p6:
6038   //   In a .* expression whose object expression is an rvalue, the program is
6039   //   ill-formed if the second operand is a pointer to member function with
6040   //   ref-qualifier &. In a ->* expression or in a .* expression whose object
6041   //   expression is an lvalue, the program is ill-formed if the second operand
6042   //   is a pointer to member function with ref-qualifier &&.
6043   if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
6044     switch (Proto->getRefQualifier()) {
6045     case RQ_None:
6046       // Do nothing
6047       break;
6048 
6049     case RQ_LValue:
6050       if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
6051         // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
6052         // is (exactly) 'const'.
6053         if (Proto->isConst() && !Proto->isVolatile())
6054           Diag(Loc, getLangOpts().CPlusPlus20
6055                         ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
6056                         : diag::ext_pointer_to_const_ref_member_on_rvalue);
6057         else
6058           Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6059               << RHSType << 1 << LHS.get()->getSourceRange();
6060       }
6061       break;
6062 
6063     case RQ_RValue:
6064       if (isIndirect || !LHS.get()->Classify(Context).isRValue())
6065         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6066           << RHSType << 0 << LHS.get()->getSourceRange();
6067       break;
6068     }
6069   }
6070 
6071   // C++ [expr.mptr.oper]p6:
6072   //   The result of a .* expression whose second operand is a pointer
6073   //   to a data member is of the same value category as its
6074   //   first operand. The result of a .* expression whose second
6075   //   operand is a pointer to a member function is a prvalue. The
6076   //   result of an ->* expression is an lvalue if its second operand
6077   //   is a pointer to data member and a prvalue otherwise.
6078   if (Result->isFunctionType()) {
6079     VK = VK_PRValue;
6080     return Context.BoundMemberTy;
6081   } else if (isIndirect) {
6082     VK = VK_LValue;
6083   } else {
6084     VK = LHS.get()->getValueKind();
6085   }
6086 
6087   return Result;
6088 }
6089 
6090 /// Try to convert a type to another according to C++11 5.16p3.
6091 ///
6092 /// This is part of the parameter validation for the ? operator. If either
6093 /// value operand is a class type, the two operands are attempted to be
6094 /// converted to each other. This function does the conversion in one direction.
6095 /// It returns true if the program is ill-formed and has already been diagnosed
6096 /// as such.
6097 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
6098                                 SourceLocation QuestionLoc,
6099                                 bool &HaveConversion,
6100                                 QualType &ToType) {
6101   HaveConversion = false;
6102   ToType = To->getType();
6103 
6104   InitializationKind Kind =
6105       InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
6106   // C++11 5.16p3
6107   //   The process for determining whether an operand expression E1 of type T1
6108   //   can be converted to match an operand expression E2 of type T2 is defined
6109   //   as follows:
6110   //   -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
6111   //      implicitly converted to type "lvalue reference to T2", subject to the
6112   //      constraint that in the conversion the reference must bind directly to
6113   //      an lvalue.
6114   //   -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
6115   //      implicitly converted to the type "rvalue reference to R2", subject to
6116   //      the constraint that the reference must bind directly.
6117   if (To->isGLValue()) {
6118     QualType T = Self.Context.getReferenceQualifiedType(To);
6119     InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
6120 
6121     InitializationSequence InitSeq(Self, Entity, Kind, From);
6122     if (InitSeq.isDirectReferenceBinding()) {
6123       ToType = T;
6124       HaveConversion = true;
6125       return false;
6126     }
6127 
6128     if (InitSeq.isAmbiguous())
6129       return InitSeq.Diagnose(Self, Entity, Kind, From);
6130   }
6131 
6132   //   -- If E2 is an rvalue, or if the conversion above cannot be done:
6133   //      -- if E1 and E2 have class type, and the underlying class types are
6134   //         the same or one is a base class of the other:
6135   QualType FTy = From->getType();
6136   QualType TTy = To->getType();
6137   const RecordType *FRec = FTy->getAs<RecordType>();
6138   const RecordType *TRec = TTy->getAs<RecordType>();
6139   bool FDerivedFromT = FRec && TRec && FRec != TRec &&
6140                        Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
6141   if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
6142                        Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
6143     //         E1 can be converted to match E2 if the class of T2 is the
6144     //         same type as, or a base class of, the class of T1, and
6145     //         [cv2 > cv1].
6146     if (FRec == TRec || FDerivedFromT) {
6147       if (TTy.isAtLeastAsQualifiedAs(FTy)) {
6148         InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
6149         InitializationSequence InitSeq(Self, Entity, Kind, From);
6150         if (InitSeq) {
6151           HaveConversion = true;
6152           return false;
6153         }
6154 
6155         if (InitSeq.isAmbiguous())
6156           return InitSeq.Diagnose(Self, Entity, Kind, From);
6157       }
6158     }
6159 
6160     return false;
6161   }
6162 
6163   //     -- Otherwise: E1 can be converted to match E2 if E1 can be
6164   //        implicitly converted to the type that expression E2 would have
6165   //        if E2 were converted to an rvalue (or the type it has, if E2 is
6166   //        an rvalue).
6167   //
6168   // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
6169   // to the array-to-pointer or function-to-pointer conversions.
6170   TTy = TTy.getNonLValueExprType(Self.Context);
6171 
6172   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
6173   InitializationSequence InitSeq(Self, Entity, Kind, From);
6174   HaveConversion = !InitSeq.Failed();
6175   ToType = TTy;
6176   if (InitSeq.isAmbiguous())
6177     return InitSeq.Diagnose(Self, Entity, Kind, From);
6178 
6179   return false;
6180 }
6181 
6182 /// Try to find a common type for two according to C++0x 5.16p5.
6183 ///
6184 /// This is part of the parameter validation for the ? operator. If either
6185 /// value operand is a class type, overload resolution is used to find a
6186 /// conversion to a common type.
6187 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
6188                                     SourceLocation QuestionLoc) {
6189   Expr *Args[2] = { LHS.get(), RHS.get() };
6190   OverloadCandidateSet CandidateSet(QuestionLoc,
6191                                     OverloadCandidateSet::CSK_Operator);
6192   Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
6193                                     CandidateSet);
6194 
6195   OverloadCandidateSet::iterator Best;
6196   switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
6197     case OR_Success: {
6198       // We found a match. Perform the conversions on the arguments and move on.
6199       ExprResult LHSRes = Self.PerformImplicitConversion(
6200           LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
6201           Sema::AA_Converting);
6202       if (LHSRes.isInvalid())
6203         break;
6204       LHS = LHSRes;
6205 
6206       ExprResult RHSRes = Self.PerformImplicitConversion(
6207           RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
6208           Sema::AA_Converting);
6209       if (RHSRes.isInvalid())
6210         break;
6211       RHS = RHSRes;
6212       if (Best->Function)
6213         Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
6214       return false;
6215     }
6216 
6217     case OR_No_Viable_Function:
6218 
6219       // Emit a better diagnostic if one of the expressions is a null pointer
6220       // constant and the other is a pointer type. In this case, the user most
6221       // likely forgot to take the address of the other expression.
6222       if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6223         return true;
6224 
6225       Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6226         << LHS.get()->getType() << RHS.get()->getType()
6227         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6228       return true;
6229 
6230     case OR_Ambiguous:
6231       Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
6232         << LHS.get()->getType() << RHS.get()->getType()
6233         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6234       // FIXME: Print the possible common types by printing the return types of
6235       // the viable candidates.
6236       break;
6237 
6238     case OR_Deleted:
6239       llvm_unreachable("Conditional operator has only built-in overloads");
6240   }
6241   return true;
6242 }
6243 
6244 /// Perform an "extended" implicit conversion as returned by
6245 /// TryClassUnification.
6246 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
6247   InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
6248   InitializationKind Kind =
6249       InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
6250   Expr *Arg = E.get();
6251   InitializationSequence InitSeq(Self, Entity, Kind, Arg);
6252   ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
6253   if (Result.isInvalid())
6254     return true;
6255 
6256   E = Result;
6257   return false;
6258 }
6259 
6260 // Check the condition operand of ?: to see if it is valid for the GCC
6261 // extension.
6262 static bool isValidVectorForConditionalCondition(ASTContext &Ctx,
6263                                                  QualType CondTy) {
6264   if (!CondTy->isVectorType() && !CondTy->isExtVectorType())
6265     return false;
6266   const QualType EltTy =
6267       cast<VectorType>(CondTy.getCanonicalType())->getElementType();
6268   assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6269   return EltTy->isIntegralType(Ctx);
6270 }
6271 
6272 static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx,
6273                                                          QualType CondTy) {
6274   if (!CondTy->isVLSTBuiltinType())
6275     return false;
6276   const QualType EltTy =
6277       cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx);
6278   assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6279   return EltTy->isIntegralType(Ctx);
6280 }
6281 
6282 QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
6283                                            ExprResult &RHS,
6284                                            SourceLocation QuestionLoc) {
6285   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6286   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6287 
6288   QualType CondType = Cond.get()->getType();
6289   const auto *CondVT = CondType->castAs<VectorType>();
6290   QualType CondElementTy = CondVT->getElementType();
6291   unsigned CondElementCount = CondVT->getNumElements();
6292   QualType LHSType = LHS.get()->getType();
6293   const auto *LHSVT = LHSType->getAs<VectorType>();
6294   QualType RHSType = RHS.get()->getType();
6295   const auto *RHSVT = RHSType->getAs<VectorType>();
6296 
6297   QualType ResultType;
6298 
6299 
6300   if (LHSVT && RHSVT) {
6301     if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {
6302       Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
6303           << /*isExtVector*/ isa<ExtVectorType>(CondVT);
6304       return {};
6305     }
6306 
6307     // If both are vector types, they must be the same type.
6308     if (!Context.hasSameType(LHSType, RHSType)) {
6309       Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6310           << LHSType << RHSType;
6311       return {};
6312     }
6313     ResultType = Context.getCommonSugaredType(LHSType, RHSType);
6314   } else if (LHSVT || RHSVT) {
6315     ResultType = CheckVectorOperands(
6316         LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
6317         /*AllowBoolConversions*/ false,
6318         /*AllowBoolOperation*/ true,
6319         /*ReportInvalid*/ true);
6320     if (ResultType.isNull())
6321       return {};
6322   } else {
6323     // Both are scalar.
6324     LHSType = LHSType.getUnqualifiedType();
6325     RHSType = RHSType.getUnqualifiedType();
6326     QualType ResultElementTy =
6327         Context.hasSameType(LHSType, RHSType)
6328             ? Context.getCommonSugaredType(LHSType, RHSType)
6329             : UsualArithmeticConversions(LHS, RHS, QuestionLoc,
6330                                          ACK_Conditional);
6331 
6332     if (ResultElementTy->isEnumeralType()) {
6333       Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6334           << ResultElementTy;
6335       return {};
6336     }
6337     if (CondType->isExtVectorType())
6338       ResultType =
6339           Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());
6340     else
6341       ResultType = Context.getVectorType(
6342           ResultElementTy, CondVT->getNumElements(), VectorType::GenericVector);
6343 
6344     LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6345     RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6346   }
6347 
6348   assert(!ResultType.isNull() && ResultType->isVectorType() &&
6349          (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
6350          "Result should have been a vector type");
6351   auto *ResultVectorTy = ResultType->castAs<VectorType>();
6352   QualType ResultElementTy = ResultVectorTy->getElementType();
6353   unsigned ResultElementCount = ResultVectorTy->getNumElements();
6354 
6355   if (ResultElementCount != CondElementCount) {
6356     Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
6357                                                          << ResultType;
6358     return {};
6359   }
6360 
6361   if (Context.getTypeSize(ResultElementTy) !=
6362       Context.getTypeSize(CondElementTy)) {
6363     Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
6364                                                                  << ResultType;
6365     return {};
6366   }
6367 
6368   return ResultType;
6369 }
6370 
6371 QualType Sema::CheckSizelessVectorConditionalTypes(ExprResult &Cond,
6372                                                    ExprResult &LHS,
6373                                                    ExprResult &RHS,
6374                                                    SourceLocation QuestionLoc) {
6375   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6376   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6377 
6378   QualType CondType = Cond.get()->getType();
6379   const auto *CondBT = CondType->castAs<BuiltinType>();
6380   QualType CondElementTy = CondBT->getSveEltType(Context);
6381   llvm::ElementCount CondElementCount =
6382       Context.getBuiltinVectorTypeInfo(CondBT).EC;
6383 
6384   QualType LHSType = LHS.get()->getType();
6385   const auto *LHSBT =
6386       LHSType->isVLSTBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr;
6387   QualType RHSType = RHS.get()->getType();
6388   const auto *RHSBT =
6389       RHSType->isVLSTBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr;
6390 
6391   QualType ResultType;
6392 
6393   if (LHSBT && RHSBT) {
6394     // If both are sizeless vector types, they must be the same type.
6395     if (!Context.hasSameType(LHSType, RHSType)) {
6396       Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6397           << LHSType << RHSType;
6398       return QualType();
6399     }
6400     ResultType = LHSType;
6401   } else if (LHSBT || RHSBT) {
6402     ResultType = CheckSizelessVectorOperands(
6403         LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional);
6404     if (ResultType.isNull())
6405       return QualType();
6406   } else {
6407     // Both are scalar so splat
6408     QualType ResultElementTy;
6409     LHSType = LHSType.getCanonicalType().getUnqualifiedType();
6410     RHSType = RHSType.getCanonicalType().getUnqualifiedType();
6411 
6412     if (Context.hasSameType(LHSType, RHSType))
6413       ResultElementTy = LHSType;
6414     else
6415       ResultElementTy =
6416           UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6417 
6418     if (ResultElementTy->isEnumeralType()) {
6419       Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6420           << ResultElementTy;
6421       return QualType();
6422     }
6423 
6424     ResultType = Context.getScalableVectorType(
6425         ResultElementTy, CondElementCount.getKnownMinValue());
6426 
6427     LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6428     RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6429   }
6430 
6431   assert(!ResultType.isNull() && ResultType->isVLSTBuiltinType() &&
6432          "Result should have been a vector type");
6433   auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>();
6434   QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context);
6435   llvm::ElementCount ResultElementCount =
6436       Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC;
6437 
6438   if (ResultElementCount != CondElementCount) {
6439     Diag(QuestionLoc, diag::err_conditional_vector_size)
6440         << CondType << ResultType;
6441     return QualType();
6442   }
6443 
6444   if (Context.getTypeSize(ResultElementTy) !=
6445       Context.getTypeSize(CondElementTy)) {
6446     Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6447         << CondType << ResultType;
6448     return QualType();
6449   }
6450 
6451   return ResultType;
6452 }
6453 
6454 /// Check the operands of ?: under C++ semantics.
6455 ///
6456 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
6457 /// extension. In this case, LHS == Cond. (But they're not aliases.)
6458 ///
6459 /// This function also implements GCC's vector extension and the
6460 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
6461 /// permit the use of a?b:c where the type of a is that of a integer vector with
6462 /// the same number of elements and size as the vectors of b and c. If one of
6463 /// either b or c is a scalar it is implicitly converted to match the type of
6464 /// the vector. Otherwise the expression is ill-formed. If both b and c are
6465 /// scalars, then b and c are checked and converted to the type of a if
6466 /// possible.
6467 ///
6468 /// The expressions are evaluated differently for GCC's and OpenCL's extensions.
6469 /// For the GCC extension, the ?: operator is evaluated as
6470 ///   (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
6471 /// For the OpenCL extensions, the ?: operator is evaluated as
6472 ///   (most-significant-bit-set(a[0])  ? b[0] : c[0], .. ,
6473 ///    most-significant-bit-set(a[n]) ? b[n] : c[n]).
6474 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6475                                            ExprResult &RHS, ExprValueKind &VK,
6476                                            ExprObjectKind &OK,
6477                                            SourceLocation QuestionLoc) {
6478   // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6479   // pointers.
6480 
6481   // Assume r-value.
6482   VK = VK_PRValue;
6483   OK = OK_Ordinary;
6484   bool IsVectorConditional =
6485       isValidVectorForConditionalCondition(Context, Cond.get()->getType());
6486 
6487   bool IsSizelessVectorConditional =
6488       isValidSizelessVectorForConditionalCondition(Context,
6489                                                    Cond.get()->getType());
6490 
6491   // C++11 [expr.cond]p1
6492   //   The first expression is contextually converted to bool.
6493   if (!Cond.get()->isTypeDependent()) {
6494     ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional
6495                              ? DefaultFunctionArrayLvalueConversion(Cond.get())
6496                              : CheckCXXBooleanCondition(Cond.get());
6497     if (CondRes.isInvalid())
6498       return QualType();
6499     Cond = CondRes;
6500   } else {
6501     // To implement C++, the first expression typically doesn't alter the result
6502     // type of the conditional, however the GCC compatible vector extension
6503     // changes the result type to be that of the conditional. Since we cannot
6504     // know if this is a vector extension here, delay the conversion of the
6505     // LHS/RHS below until later.
6506     return Context.DependentTy;
6507   }
6508 
6509 
6510   // Either of the arguments dependent?
6511   if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
6512     return Context.DependentTy;
6513 
6514   // C++11 [expr.cond]p2
6515   //   If either the second or the third operand has type (cv) void, ...
6516   QualType LTy = LHS.get()->getType();
6517   QualType RTy = RHS.get()->getType();
6518   bool LVoid = LTy->isVoidType();
6519   bool RVoid = RTy->isVoidType();
6520   if (LVoid || RVoid) {
6521     //   ... one of the following shall hold:
6522     //   -- The second or the third operand (but not both) is a (possibly
6523     //      parenthesized) throw-expression; the result is of the type
6524     //      and value category of the other.
6525     bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
6526     bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
6527 
6528     // Void expressions aren't legal in the vector-conditional expressions.
6529     if (IsVectorConditional) {
6530       SourceRange DiagLoc =
6531           LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
6532       bool IsThrow = LVoid ? LThrow : RThrow;
6533       Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
6534           << DiagLoc << IsThrow;
6535       return QualType();
6536     }
6537 
6538     if (LThrow != RThrow) {
6539       Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
6540       VK = NonThrow->getValueKind();
6541       // DR (no number yet): the result is a bit-field if the
6542       // non-throw-expression operand is a bit-field.
6543       OK = NonThrow->getObjectKind();
6544       return NonThrow->getType();
6545     }
6546 
6547     //   -- Both the second and third operands have type void; the result is of
6548     //      type void and is a prvalue.
6549     if (LVoid && RVoid)
6550       return Context.getCommonSugaredType(LTy, RTy);
6551 
6552     // Neither holds, error.
6553     Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
6554       << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
6555       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6556     return QualType();
6557   }
6558 
6559   // Neither is void.
6560   if (IsVectorConditional)
6561     return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6562 
6563   if (IsSizelessVectorConditional)
6564     return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6565 
6566   // C++11 [expr.cond]p3
6567   //   Otherwise, if the second and third operand have different types, and
6568   //   either has (cv) class type [...] an attempt is made to convert each of
6569   //   those operands to the type of the other.
6570   if (!Context.hasSameType(LTy, RTy) &&
6571       (LTy->isRecordType() || RTy->isRecordType())) {
6572     // These return true if a single direction is already ambiguous.
6573     QualType L2RType, R2LType;
6574     bool HaveL2R, HaveR2L;
6575     if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
6576       return QualType();
6577     if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
6578       return QualType();
6579 
6580     //   If both can be converted, [...] the program is ill-formed.
6581     if (HaveL2R && HaveR2L) {
6582       Diag(QuestionLoc, diag::err_conditional_ambiguous)
6583         << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6584       return QualType();
6585     }
6586 
6587     //   If exactly one conversion is possible, that conversion is applied to
6588     //   the chosen operand and the converted operands are used in place of the
6589     //   original operands for the remainder of this section.
6590     if (HaveL2R) {
6591       if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
6592         return QualType();
6593       LTy = LHS.get()->getType();
6594     } else if (HaveR2L) {
6595       if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
6596         return QualType();
6597       RTy = RHS.get()->getType();
6598     }
6599   }
6600 
6601   // C++11 [expr.cond]p3
6602   //   if both are glvalues of the same value category and the same type except
6603   //   for cv-qualification, an attempt is made to convert each of those
6604   //   operands to the type of the other.
6605   // FIXME:
6606   //   Resolving a defect in P0012R1: we extend this to cover all cases where
6607   //   one of the operands is reference-compatible with the other, in order
6608   //   to support conditionals between functions differing in noexcept. This
6609   //   will similarly cover difference in array bounds after P0388R4.
6610   // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6611   //   that instead?
6612   ExprValueKind LVK = LHS.get()->getValueKind();
6613   ExprValueKind RVK = RHS.get()->getValueKind();
6614   if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
6615     // DerivedToBase was already handled by the class-specific case above.
6616     // FIXME: Should we allow ObjC conversions here?
6617     const ReferenceConversions AllowedConversions =
6618         ReferenceConversions::Qualification |
6619         ReferenceConversions::NestedQualification |
6620         ReferenceConversions::Function;
6621 
6622     ReferenceConversions RefConv;
6623     if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6624             Ref_Compatible &&
6625         !(RefConv & ~AllowedConversions) &&
6626         // [...] subject to the constraint that the reference must bind
6627         // directly [...]
6628         !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6629       RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6630       RTy = RHS.get()->getType();
6631     } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6632                    Ref_Compatible &&
6633                !(RefConv & ~AllowedConversions) &&
6634                !LHS.get()->refersToBitField() &&
6635                !LHS.get()->refersToVectorElement()) {
6636       LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6637       LTy = LHS.get()->getType();
6638     }
6639   }
6640 
6641   // C++11 [expr.cond]p4
6642   //   If the second and third operands are glvalues of the same value
6643   //   category and have the same type, the result is of that type and
6644   //   value category and it is a bit-field if the second or the third
6645   //   operand is a bit-field, or if both are bit-fields.
6646   // We only extend this to bitfields, not to the crazy other kinds of
6647   // l-values.
6648   bool Same = Context.hasSameType(LTy, RTy);
6649   if (Same && LVK == RVK && LVK != VK_PRValue &&
6650       LHS.get()->isOrdinaryOrBitFieldObject() &&
6651       RHS.get()->isOrdinaryOrBitFieldObject()) {
6652     VK = LHS.get()->getValueKind();
6653     if (LHS.get()->getObjectKind() == OK_BitField ||
6654         RHS.get()->getObjectKind() == OK_BitField)
6655       OK = OK_BitField;
6656     return Context.getCommonSugaredType(LTy, RTy);
6657   }
6658 
6659   // C++11 [expr.cond]p5
6660   //   Otherwise, the result is a prvalue. If the second and third operands
6661   //   do not have the same type, and either has (cv) class type, ...
6662   if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6663     //   ... overload resolution is used to determine the conversions (if any)
6664     //   to be applied to the operands. If the overload resolution fails, the
6665     //   program is ill-formed.
6666     if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
6667       return QualType();
6668   }
6669 
6670   // C++11 [expr.cond]p6
6671   //   Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
6672   //   conversions are performed on the second and third operands.
6673   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6674   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6675   if (LHS.isInvalid() || RHS.isInvalid())
6676     return QualType();
6677   LTy = LHS.get()->getType();
6678   RTy = RHS.get()->getType();
6679 
6680   //   After those conversions, one of the following shall hold:
6681   //   -- The second and third operands have the same type; the result
6682   //      is of that type. If the operands have class type, the result
6683   //      is a prvalue temporary of the result type, which is
6684   //      copy-initialized from either the second operand or the third
6685   //      operand depending on the value of the first operand.
6686   if (Context.hasSameType(LTy, RTy)) {
6687     if (LTy->isRecordType()) {
6688       // The operands have class type. Make a temporary copy.
6689       ExprResult LHSCopy = PerformCopyInitialization(
6690           InitializedEntity::InitializeTemporary(LTy), SourceLocation(), LHS);
6691       if (LHSCopy.isInvalid())
6692         return QualType();
6693 
6694       ExprResult RHSCopy = PerformCopyInitialization(
6695           InitializedEntity::InitializeTemporary(RTy), SourceLocation(), RHS);
6696       if (RHSCopy.isInvalid())
6697         return QualType();
6698 
6699       LHS = LHSCopy;
6700       RHS = RHSCopy;
6701     }
6702     return Context.getCommonSugaredType(LTy, RTy);
6703   }
6704 
6705   // Extension: conditional operator involving vector types.
6706   if (LTy->isVectorType() || RTy->isVectorType())
6707     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
6708                                /*AllowBothBool*/ true,
6709                                /*AllowBoolConversions*/ false,
6710                                /*AllowBoolOperation*/ false,
6711                                /*ReportInvalid*/ true);
6712 
6713   //   -- The second and third operands have arithmetic or enumeration type;
6714   //      the usual arithmetic conversions are performed to bring them to a
6715   //      common type, and the result is of that type.
6716   if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
6717     QualType ResTy =
6718         UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6719     if (LHS.isInvalid() || RHS.isInvalid())
6720       return QualType();
6721     if (ResTy.isNull()) {
6722       Diag(QuestionLoc,
6723            diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
6724         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6725       return QualType();
6726     }
6727 
6728     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6729     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6730 
6731     return ResTy;
6732   }
6733 
6734   //   -- The second and third operands have pointer type, or one has pointer
6735   //      type and the other is a null pointer constant, or both are null
6736   //      pointer constants, at least one of which is non-integral; pointer
6737   //      conversions and qualification conversions are performed to bring them
6738   //      to their composite pointer type. The result is of the composite
6739   //      pointer type.
6740   //   -- The second and third operands have pointer to member type, or one has
6741   //      pointer to member type and the other is a null pointer constant;
6742   //      pointer to member conversions and qualification conversions are
6743   //      performed to bring them to a common type, whose cv-qualification
6744   //      shall match the cv-qualification of either the second or the third
6745   //      operand. The result is of the common type.
6746   QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
6747   if (!Composite.isNull())
6748     return Composite;
6749 
6750   // Similarly, attempt to find composite type of two objective-c pointers.
6751   Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6752   if (LHS.isInvalid() || RHS.isInvalid())
6753     return QualType();
6754   if (!Composite.isNull())
6755     return Composite;
6756 
6757   // Check if we are using a null with a non-pointer type.
6758   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6759     return QualType();
6760 
6761   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6762     << LHS.get()->getType() << RHS.get()->getType()
6763     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6764   return QualType();
6765 }
6766 
6767 /// Find a merged pointer type and convert the two expressions to it.
6768 ///
6769 /// This finds the composite pointer type for \p E1 and \p E2 according to
6770 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
6771 /// it.  It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs
6772 /// is \c true).
6773 ///
6774 /// \param Loc The location of the operator requiring these two expressions to
6775 /// be converted to the composite pointer type.
6776 ///
6777 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
6778 QualType Sema::FindCompositePointerType(SourceLocation Loc,
6779                                         Expr *&E1, Expr *&E2,
6780                                         bool ConvertArgs) {
6781   assert(getLangOpts().CPlusPlus && "This function assumes C++");
6782 
6783   // C++1z [expr]p14:
6784   //   The composite pointer type of two operands p1 and p2 having types T1
6785   //   and T2
6786   QualType T1 = E1->getType(), T2 = E2->getType();
6787 
6788   //   where at least one is a pointer or pointer to member type or
6789   //   std::nullptr_t is:
6790   bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6791                          T1->isNullPtrType();
6792   bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6793                          T2->isNullPtrType();
6794   if (!T1IsPointerLike && !T2IsPointerLike)
6795     return QualType();
6796 
6797   //   - if both p1 and p2 are null pointer constants, std::nullptr_t;
6798   // This can't actually happen, following the standard, but we also use this
6799   // to implement the end of [expr.conv], which hits this case.
6800   //
6801   //   - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6802   if (T1IsPointerLike &&
6803       E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6804     if (ConvertArgs)
6805       E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6806                                          ? CK_NullToMemberPointer
6807                                          : CK_NullToPointer).get();
6808     return T1;
6809   }
6810   if (T2IsPointerLike &&
6811       E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6812     if (ConvertArgs)
6813       E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6814                                          ? CK_NullToMemberPointer
6815                                          : CK_NullToPointer).get();
6816     return T2;
6817   }
6818 
6819   // Now both have to be pointers or member pointers.
6820   if (!T1IsPointerLike || !T2IsPointerLike)
6821     return QualType();
6822   assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6823          "nullptr_t should be a null pointer constant");
6824 
6825   struct Step {
6826     enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
6827     // Qualifiers to apply under the step kind.
6828     Qualifiers Quals;
6829     /// The class for a pointer-to-member; a constant array type with a bound
6830     /// (if any) for an array.
6831     const Type *ClassOrBound;
6832 
6833     Step(Kind K, const Type *ClassOrBound = nullptr)
6834         : K(K), ClassOrBound(ClassOrBound) {}
6835     QualType rebuild(ASTContext &Ctx, QualType T) const {
6836       T = Ctx.getQualifiedType(T, Quals);
6837       switch (K) {
6838       case Pointer:
6839         return Ctx.getPointerType(T);
6840       case MemberPointer:
6841         return Ctx.getMemberPointerType(T, ClassOrBound);
6842       case ObjCPointer:
6843         return Ctx.getObjCObjectPointerType(T);
6844       case Array:
6845         if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
6846           return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
6847                                           ArrayType::Normal, 0);
6848         else
6849           return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0);
6850       }
6851       llvm_unreachable("unknown step kind");
6852     }
6853   };
6854 
6855   SmallVector<Step, 8> Steps;
6856 
6857   //  - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6858   //    is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6859   //    the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6860   //    respectively;
6861   //  - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6862   //    to member of C2 of type cv2 U2" for some non-function type U, where
6863   //    C1 is reference-related to C2 or C2 is reference-related to C1, the
6864   //    cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6865   //    respectively;
6866   //  - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6867   //    T2;
6868   //
6869   // Dismantle T1 and T2 to simultaneously determine whether they are similar
6870   // and to prepare to form the cv-combined type if so.
6871   QualType Composite1 = T1;
6872   QualType Composite2 = T2;
6873   unsigned NeedConstBefore = 0;
6874   while (true) {
6875     assert(!Composite1.isNull() && !Composite2.isNull());
6876 
6877     Qualifiers Q1, Q2;
6878     Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
6879     Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
6880 
6881     // Top-level qualifiers are ignored. Merge at all lower levels.
6882     if (!Steps.empty()) {
6883       // Find the qualifier union: (approximately) the unique minimal set of
6884       // qualifiers that is compatible with both types.
6885       Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() |
6886                                                   Q2.getCVRUQualifiers());
6887 
6888       // Under one level of pointer or pointer-to-member, we can change to an
6889       // unambiguous compatible address space.
6890       if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
6891         Quals.setAddressSpace(Q1.getAddressSpace());
6892       } else if (Steps.size() == 1) {
6893         bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
6894         bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
6895         if (MaybeQ1 == MaybeQ2) {
6896           // Exception for ptr size address spaces. Should be able to choose
6897           // either address space during comparison.
6898           if (isPtrSizeAddressSpace(Q1.getAddressSpace()) ||
6899               isPtrSizeAddressSpace(Q2.getAddressSpace()))
6900             MaybeQ1 = true;
6901           else
6902             return QualType(); // No unique best address space.
6903         }
6904         Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
6905                                       : Q2.getAddressSpace());
6906       } else {
6907         return QualType();
6908       }
6909 
6910       // FIXME: In C, we merge __strong and none to __strong at the top level.
6911       if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
6912         Quals.setObjCGCAttr(Q1.getObjCGCAttr());
6913       else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6914         assert(Steps.size() == 1);
6915       else
6916         return QualType();
6917 
6918       // Mismatched lifetime qualifiers never compatibly include each other.
6919       if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
6920         Quals.setObjCLifetime(Q1.getObjCLifetime());
6921       else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6922         assert(Steps.size() == 1);
6923       else
6924         return QualType();
6925 
6926       Steps.back().Quals = Quals;
6927       if (Q1 != Quals || Q2 != Quals)
6928         NeedConstBefore = Steps.size() - 1;
6929     }
6930 
6931     // FIXME: Can we unify the following with UnwrapSimilarTypes?
6932 
6933     const ArrayType *Arr1, *Arr2;
6934     if ((Arr1 = Context.getAsArrayType(Composite1)) &&
6935         (Arr2 = Context.getAsArrayType(Composite2))) {
6936       auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
6937       auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
6938       if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
6939         Composite1 = Arr1->getElementType();
6940         Composite2 = Arr2->getElementType();
6941         Steps.emplace_back(Step::Array, CAT1);
6942         continue;
6943       }
6944       bool IAT1 = isa<IncompleteArrayType>(Arr1);
6945       bool IAT2 = isa<IncompleteArrayType>(Arr2);
6946       if ((IAT1 && IAT2) ||
6947           (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
6948            ((bool)CAT1 != (bool)CAT2) &&
6949            (Steps.empty() || Steps.back().K != Step::Array))) {
6950         // In C++20 onwards, we can unify an array of N T with an array of
6951         // a different or unknown bound. But we can't form an array whose
6952         // element type is an array of unknown bound by doing so.
6953         Composite1 = Arr1->getElementType();
6954         Composite2 = Arr2->getElementType();
6955         Steps.emplace_back(Step::Array);
6956         if (CAT1 || CAT2)
6957           NeedConstBefore = Steps.size();
6958         continue;
6959       }
6960     }
6961 
6962     const PointerType *Ptr1, *Ptr2;
6963     if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6964         (Ptr2 = Composite2->getAs<PointerType>())) {
6965       Composite1 = Ptr1->getPointeeType();
6966       Composite2 = Ptr2->getPointeeType();
6967       Steps.emplace_back(Step::Pointer);
6968       continue;
6969     }
6970 
6971     const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
6972     if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
6973         (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
6974       Composite1 = ObjPtr1->getPointeeType();
6975       Composite2 = ObjPtr2->getPointeeType();
6976       Steps.emplace_back(Step::ObjCPointer);
6977       continue;
6978     }
6979 
6980     const MemberPointerType *MemPtr1, *MemPtr2;
6981     if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6982         (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6983       Composite1 = MemPtr1->getPointeeType();
6984       Composite2 = MemPtr2->getPointeeType();
6985 
6986       // At the top level, we can perform a base-to-derived pointer-to-member
6987       // conversion:
6988       //
6989       //  - [...] where C1 is reference-related to C2 or C2 is
6990       //    reference-related to C1
6991       //
6992       // (Note that the only kinds of reference-relatedness in scope here are
6993       // "same type or derived from".) At any other level, the class must
6994       // exactly match.
6995       const Type *Class = nullptr;
6996       QualType Cls1(MemPtr1->getClass(), 0);
6997       QualType Cls2(MemPtr2->getClass(), 0);
6998       if (Context.hasSameType(Cls1, Cls2))
6999         Class = MemPtr1->getClass();
7000       else if (Steps.empty())
7001         Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
7002                 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
7003       if (!Class)
7004         return QualType();
7005 
7006       Steps.emplace_back(Step::MemberPointer, Class);
7007       continue;
7008     }
7009 
7010     // Special case: at the top level, we can decompose an Objective-C pointer
7011     // and a 'cv void *'. Unify the qualifiers.
7012     if (Steps.empty() && ((Composite1->isVoidPointerType() &&
7013                            Composite2->isObjCObjectPointerType()) ||
7014                           (Composite1->isObjCObjectPointerType() &&
7015                            Composite2->isVoidPointerType()))) {
7016       Composite1 = Composite1->getPointeeType();
7017       Composite2 = Composite2->getPointeeType();
7018       Steps.emplace_back(Step::Pointer);
7019       continue;
7020     }
7021 
7022     // FIXME: block pointer types?
7023 
7024     // Cannot unwrap any more types.
7025     break;
7026   }
7027 
7028   //  - if T1 or T2 is "pointer to noexcept function" and the other type is
7029   //    "pointer to function", where the function types are otherwise the same,
7030   //    "pointer to function";
7031   //  - if T1 or T2 is "pointer to member of C1 of type function", the other
7032   //    type is "pointer to member of C2 of type noexcept function", and C1
7033   //    is reference-related to C2 or C2 is reference-related to C1, where
7034   //    the function types are otherwise the same, "pointer to member of C2 of
7035   //    type function" or "pointer to member of C1 of type function",
7036   //    respectively;
7037   //
7038   // We also support 'noreturn' here, so as a Clang extension we generalize the
7039   // above to:
7040   //
7041   //  - [Clang] If T1 and T2 are both of type "pointer to function" or
7042   //    "pointer to member function" and the pointee types can be unified
7043   //    by a function pointer conversion, that conversion is applied
7044   //    before checking the following rules.
7045   //
7046   // We've already unwrapped down to the function types, and we want to merge
7047   // rather than just convert, so do this ourselves rather than calling
7048   // IsFunctionConversion.
7049   //
7050   // FIXME: In order to match the standard wording as closely as possible, we
7051   // currently only do this under a single level of pointers. Ideally, we would
7052   // allow this in general, and set NeedConstBefore to the relevant depth on
7053   // the side(s) where we changed anything. If we permit that, we should also
7054   // consider this conversion when determining type similarity and model it as
7055   // a qualification conversion.
7056   if (Steps.size() == 1) {
7057     if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
7058       if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
7059         FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
7060         FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
7061 
7062         // The result is noreturn if both operands are.
7063         bool Noreturn =
7064             EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
7065         EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
7066         EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
7067 
7068         // The result is nothrow if both operands are.
7069         SmallVector<QualType, 8> ExceptionTypeStorage;
7070         EPI1.ExceptionSpec = EPI2.ExceptionSpec = Context.mergeExceptionSpecs(
7071             EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,
7072             getLangOpts().CPlusPlus17);
7073 
7074         Composite1 = Context.getFunctionType(FPT1->getReturnType(),
7075                                              FPT1->getParamTypes(), EPI1);
7076         Composite2 = Context.getFunctionType(FPT2->getReturnType(),
7077                                              FPT2->getParamTypes(), EPI2);
7078       }
7079     }
7080   }
7081 
7082   // There are some more conversions we can perform under exactly one pointer.
7083   if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
7084       !Context.hasSameType(Composite1, Composite2)) {
7085     //  - if T1 or T2 is "pointer to cv1 void" and the other type is
7086     //    "pointer to cv2 T", where T is an object type or void,
7087     //    "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
7088     if (Composite1->isVoidType() && Composite2->isObjectType())
7089       Composite2 = Composite1;
7090     else if (Composite2->isVoidType() && Composite1->isObjectType())
7091       Composite1 = Composite2;
7092     //  - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7093     //    is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7094     //    the cv-combined type of T1 and T2 or the cv-combined type of T2 and
7095     //    T1, respectively;
7096     //
7097     // The "similar type" handling covers all of this except for the "T1 is a
7098     // base class of T2" case in the definition of reference-related.
7099     else if (IsDerivedFrom(Loc, Composite1, Composite2))
7100       Composite1 = Composite2;
7101     else if (IsDerivedFrom(Loc, Composite2, Composite1))
7102       Composite2 = Composite1;
7103   }
7104 
7105   // At this point, either the inner types are the same or we have failed to
7106   // find a composite pointer type.
7107   if (!Context.hasSameType(Composite1, Composite2))
7108     return QualType();
7109 
7110   // Per C++ [conv.qual]p3, add 'const' to every level before the last
7111   // differing qualifier.
7112   for (unsigned I = 0; I != NeedConstBefore; ++I)
7113     Steps[I].Quals.addConst();
7114 
7115   // Rebuild the composite type.
7116   QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);
7117   for (auto &S : llvm::reverse(Steps))
7118     Composite = S.rebuild(Context, Composite);
7119 
7120   if (ConvertArgs) {
7121     // Convert the expressions to the composite pointer type.
7122     InitializedEntity Entity =
7123         InitializedEntity::InitializeTemporary(Composite);
7124     InitializationKind Kind =
7125         InitializationKind::CreateCopy(Loc, SourceLocation());
7126 
7127     InitializationSequence E1ToC(*this, Entity, Kind, E1);
7128     if (!E1ToC)
7129       return QualType();
7130 
7131     InitializationSequence E2ToC(*this, Entity, Kind, E2);
7132     if (!E2ToC)
7133       return QualType();
7134 
7135     // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
7136     ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
7137     if (E1Result.isInvalid())
7138       return QualType();
7139     E1 = E1Result.get();
7140 
7141     ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
7142     if (E2Result.isInvalid())
7143       return QualType();
7144     E2 = E2Result.get();
7145   }
7146 
7147   return Composite;
7148 }
7149 
7150 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
7151   if (!E)
7152     return ExprError();
7153 
7154   assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
7155 
7156   // If the result is a glvalue, we shouldn't bind it.
7157   if (E->isGLValue())
7158     return E;
7159 
7160   // In ARC, calls that return a retainable type can return retained,
7161   // in which case we have to insert a consuming cast.
7162   if (getLangOpts().ObjCAutoRefCount &&
7163       E->getType()->isObjCRetainableType()) {
7164 
7165     bool ReturnsRetained;
7166 
7167     // For actual calls, we compute this by examining the type of the
7168     // called value.
7169     if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
7170       Expr *Callee = Call->getCallee()->IgnoreParens();
7171       QualType T = Callee->getType();
7172 
7173       if (T == Context.BoundMemberTy) {
7174         // Handle pointer-to-members.
7175         if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
7176           T = BinOp->getRHS()->getType();
7177         else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
7178           T = Mem->getMemberDecl()->getType();
7179       }
7180 
7181       if (const PointerType *Ptr = T->getAs<PointerType>())
7182         T = Ptr->getPointeeType();
7183       else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
7184         T = Ptr->getPointeeType();
7185       else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
7186         T = MemPtr->getPointeeType();
7187 
7188       auto *FTy = T->castAs<FunctionType>();
7189       ReturnsRetained = FTy->getExtInfo().getProducesResult();
7190 
7191     // ActOnStmtExpr arranges things so that StmtExprs of retainable
7192     // type always produce a +1 object.
7193     } else if (isa<StmtExpr>(E)) {
7194       ReturnsRetained = true;
7195 
7196     // We hit this case with the lambda conversion-to-block optimization;
7197     // we don't want any extra casts here.
7198     } else if (isa<CastExpr>(E) &&
7199                isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
7200       return E;
7201 
7202     // For message sends and property references, we try to find an
7203     // actual method.  FIXME: we should infer retention by selector in
7204     // cases where we don't have an actual method.
7205     } else {
7206       ObjCMethodDecl *D = nullptr;
7207       if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
7208         D = Send->getMethodDecl();
7209       } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
7210         D = BoxedExpr->getBoxingMethod();
7211       } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
7212         // Don't do reclaims if we're using the zero-element array
7213         // constant.
7214         if (ArrayLit->getNumElements() == 0 &&
7215             Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
7216           return E;
7217 
7218         D = ArrayLit->getArrayWithObjectsMethod();
7219       } else if (ObjCDictionaryLiteral *DictLit
7220                                         = dyn_cast<ObjCDictionaryLiteral>(E)) {
7221         // Don't do reclaims if we're using the zero-element dictionary
7222         // constant.
7223         if (DictLit->getNumElements() == 0 &&
7224             Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
7225           return E;
7226 
7227         D = DictLit->getDictWithObjectsMethod();
7228       }
7229 
7230       ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
7231 
7232       // Don't do reclaims on performSelector calls; despite their
7233       // return type, the invoked method doesn't necessarily actually
7234       // return an object.
7235       if (!ReturnsRetained &&
7236           D && D->getMethodFamily() == OMF_performSelector)
7237         return E;
7238     }
7239 
7240     // Don't reclaim an object of Class type.
7241     if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
7242       return E;
7243 
7244     Cleanup.setExprNeedsCleanups(true);
7245 
7246     CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
7247                                    : CK_ARCReclaimReturnedObject);
7248     return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
7249                                     VK_PRValue, FPOptionsOverride());
7250   }
7251 
7252   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
7253     Cleanup.setExprNeedsCleanups(true);
7254 
7255   if (!getLangOpts().CPlusPlus)
7256     return E;
7257 
7258   // Search for the base element type (cf. ASTContext::getBaseElementType) with
7259   // a fast path for the common case that the type is directly a RecordType.
7260   const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
7261   const RecordType *RT = nullptr;
7262   while (!RT) {
7263     switch (T->getTypeClass()) {
7264     case Type::Record:
7265       RT = cast<RecordType>(T);
7266       break;
7267     case Type::ConstantArray:
7268     case Type::IncompleteArray:
7269     case Type::VariableArray:
7270     case Type::DependentSizedArray:
7271       T = cast<ArrayType>(T)->getElementType().getTypePtr();
7272       break;
7273     default:
7274       return E;
7275     }
7276   }
7277 
7278   // That should be enough to guarantee that this type is complete, if we're
7279   // not processing a decltype expression.
7280   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7281   if (RD->isInvalidDecl() || RD->isDependentContext())
7282     return E;
7283 
7284   bool IsDecltype = ExprEvalContexts.back().ExprContext ==
7285                     ExpressionEvaluationContextRecord::EK_Decltype;
7286   CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
7287 
7288   if (Destructor) {
7289     MarkFunctionReferenced(E->getExprLoc(), Destructor);
7290     CheckDestructorAccess(E->getExprLoc(), Destructor,
7291                           PDiag(diag::err_access_dtor_temp)
7292                             << E->getType());
7293     if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
7294       return ExprError();
7295 
7296     // If destructor is trivial, we can avoid the extra copy.
7297     if (Destructor->isTrivial())
7298       return E;
7299 
7300     // We need a cleanup, but we don't need to remember the temporary.
7301     Cleanup.setExprNeedsCleanups(true);
7302   }
7303 
7304   CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
7305   CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
7306 
7307   if (IsDecltype)
7308     ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
7309 
7310   return Bind;
7311 }
7312 
7313 ExprResult
7314 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
7315   if (SubExpr.isInvalid())
7316     return ExprError();
7317 
7318   return MaybeCreateExprWithCleanups(SubExpr.get());
7319 }
7320 
7321 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
7322   assert(SubExpr && "subexpression can't be null!");
7323 
7324   CleanupVarDeclMarking();
7325 
7326   unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
7327   assert(ExprCleanupObjects.size() >= FirstCleanup);
7328   assert(Cleanup.exprNeedsCleanups() ||
7329          ExprCleanupObjects.size() == FirstCleanup);
7330   if (!Cleanup.exprNeedsCleanups())
7331     return SubExpr;
7332 
7333   auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
7334                                  ExprCleanupObjects.size() - FirstCleanup);
7335 
7336   auto *E = ExprWithCleanups::Create(
7337       Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
7338   DiscardCleanupsInEvaluationContext();
7339 
7340   return E;
7341 }
7342 
7343 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
7344   assert(SubStmt && "sub-statement can't be null!");
7345 
7346   CleanupVarDeclMarking();
7347 
7348   if (!Cleanup.exprNeedsCleanups())
7349     return SubStmt;
7350 
7351   // FIXME: In order to attach the temporaries, wrap the statement into
7352   // a StmtExpr; currently this is only used for asm statements.
7353   // This is hacky, either create a new CXXStmtWithTemporaries statement or
7354   // a new AsmStmtWithTemporaries.
7355   CompoundStmt *CompStmt =
7356       CompoundStmt::Create(Context, SubStmt, FPOptionsOverride(),
7357                            SourceLocation(), SourceLocation());
7358   Expr *E = new (Context)
7359       StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),
7360                /*FIXME TemplateDepth=*/0);
7361   return MaybeCreateExprWithCleanups(E);
7362 }
7363 
7364 /// Process the expression contained within a decltype. For such expressions,
7365 /// certain semantic checks on temporaries are delayed until this point, and
7366 /// are omitted for the 'topmost' call in the decltype expression. If the
7367 /// topmost call bound a temporary, strip that temporary off the expression.
7368 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
7369   assert(ExprEvalContexts.back().ExprContext ==
7370              ExpressionEvaluationContextRecord::EK_Decltype &&
7371          "not in a decltype expression");
7372 
7373   ExprResult Result = CheckPlaceholderExpr(E);
7374   if (Result.isInvalid())
7375     return ExprError();
7376   E = Result.get();
7377 
7378   // C++11 [expr.call]p11:
7379   //   If a function call is a prvalue of object type,
7380   // -- if the function call is either
7381   //   -- the operand of a decltype-specifier, or
7382   //   -- the right operand of a comma operator that is the operand of a
7383   //      decltype-specifier,
7384   //   a temporary object is not introduced for the prvalue.
7385 
7386   // Recursively rebuild ParenExprs and comma expressions to strip out the
7387   // outermost CXXBindTemporaryExpr, if any.
7388   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7389     ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
7390     if (SubExpr.isInvalid())
7391       return ExprError();
7392     if (SubExpr.get() == PE->getSubExpr())
7393       return E;
7394     return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
7395   }
7396   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7397     if (BO->getOpcode() == BO_Comma) {
7398       ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
7399       if (RHS.isInvalid())
7400         return ExprError();
7401       if (RHS.get() == BO->getRHS())
7402         return E;
7403       return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
7404                                     BO->getType(), BO->getValueKind(),
7405                                     BO->getObjectKind(), BO->getOperatorLoc(),
7406                                     BO->getFPFeatures());
7407     }
7408   }
7409 
7410   CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
7411   CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
7412                               : nullptr;
7413   if (TopCall)
7414     E = TopCall;
7415   else
7416     TopBind = nullptr;
7417 
7418   // Disable the special decltype handling now.
7419   ExprEvalContexts.back().ExprContext =
7420       ExpressionEvaluationContextRecord::EK_Other;
7421 
7422   Result = CheckUnevaluatedOperand(E);
7423   if (Result.isInvalid())
7424     return ExprError();
7425   E = Result.get();
7426 
7427   // In MS mode, don't perform any extra checking of call return types within a
7428   // decltype expression.
7429   if (getLangOpts().MSVCCompat)
7430     return E;
7431 
7432   // Perform the semantic checks we delayed until this point.
7433   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
7434        I != N; ++I) {
7435     CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
7436     if (Call == TopCall)
7437       continue;
7438 
7439     if (CheckCallReturnType(Call->getCallReturnType(Context),
7440                             Call->getBeginLoc(), Call, Call->getDirectCallee()))
7441       return ExprError();
7442   }
7443 
7444   // Now all relevant types are complete, check the destructors are accessible
7445   // and non-deleted, and annotate them on the temporaries.
7446   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7447        I != N; ++I) {
7448     CXXBindTemporaryExpr *Bind =
7449       ExprEvalContexts.back().DelayedDecltypeBinds[I];
7450     if (Bind == TopBind)
7451       continue;
7452 
7453     CXXTemporary *Temp = Bind->getTemporary();
7454 
7455     CXXRecordDecl *RD =
7456       Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7457     CXXDestructorDecl *Destructor = LookupDestructor(RD);
7458     Temp->setDestructor(Destructor);
7459 
7460     MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7461     CheckDestructorAccess(Bind->getExprLoc(), Destructor,
7462                           PDiag(diag::err_access_dtor_temp)
7463                             << Bind->getType());
7464     if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7465       return ExprError();
7466 
7467     // We need a cleanup, but we don't need to remember the temporary.
7468     Cleanup.setExprNeedsCleanups(true);
7469   }
7470 
7471   // Possibly strip off the top CXXBindTemporaryExpr.
7472   return E;
7473 }
7474 
7475 /// Note a set of 'operator->' functions that were used for a member access.
7476 static void noteOperatorArrows(Sema &S,
7477                                ArrayRef<FunctionDecl *> OperatorArrows) {
7478   unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7479   // FIXME: Make this configurable?
7480   unsigned Limit = 9;
7481   if (OperatorArrows.size() > Limit) {
7482     // Produce Limit-1 normal notes and one 'skipping' note.
7483     SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7484     SkipCount = OperatorArrows.size() - (Limit - 1);
7485   }
7486 
7487   for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7488     if (I == SkipStart) {
7489       S.Diag(OperatorArrows[I]->getLocation(),
7490              diag::note_operator_arrows_suppressed)
7491           << SkipCount;
7492       I += SkipCount;
7493     } else {
7494       S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7495           << OperatorArrows[I]->getCallResultType();
7496       ++I;
7497     }
7498   }
7499 }
7500 
7501 ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
7502                                               SourceLocation OpLoc,
7503                                               tok::TokenKind OpKind,
7504                                               ParsedType &ObjectType,
7505                                               bool &MayBePseudoDestructor) {
7506   // Since this might be a postfix expression, get rid of ParenListExprs.
7507   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
7508   if (Result.isInvalid()) return ExprError();
7509   Base = Result.get();
7510 
7511   Result = CheckPlaceholderExpr(Base);
7512   if (Result.isInvalid()) return ExprError();
7513   Base = Result.get();
7514 
7515   QualType BaseType = Base->getType();
7516   MayBePseudoDestructor = false;
7517   if (BaseType->isDependentType()) {
7518     // If we have a pointer to a dependent type and are using the -> operator,
7519     // the object type is the type that the pointer points to. We might still
7520     // have enough information about that type to do something useful.
7521     if (OpKind == tok::arrow)
7522       if (const PointerType *Ptr = BaseType->getAs<PointerType>())
7523         BaseType = Ptr->getPointeeType();
7524 
7525     ObjectType = ParsedType::make(BaseType);
7526     MayBePseudoDestructor = true;
7527     return Base;
7528   }
7529 
7530   // C++ [over.match.oper]p8:
7531   //   [...] When operator->returns, the operator-> is applied  to the value
7532   //   returned, with the original second operand.
7533   if (OpKind == tok::arrow) {
7534     QualType StartingType = BaseType;
7535     bool NoArrowOperatorFound = false;
7536     bool FirstIteration = true;
7537     FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
7538     // The set of types we've considered so far.
7539     llvm::SmallPtrSet<CanQualType,8> CTypes;
7540     SmallVector<FunctionDecl*, 8> OperatorArrows;
7541     CTypes.insert(Context.getCanonicalType(BaseType));
7542 
7543     while (BaseType->isRecordType()) {
7544       if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
7545         Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
7546           << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
7547         noteOperatorArrows(*this, OperatorArrows);
7548         Diag(OpLoc, diag::note_operator_arrow_depth)
7549           << getLangOpts().ArrowDepth;
7550         return ExprError();
7551       }
7552 
7553       Result = BuildOverloadedArrowExpr(
7554           S, Base, OpLoc,
7555           // When in a template specialization and on the first loop iteration,
7556           // potentially give the default diagnostic (with the fixit in a
7557           // separate note) instead of having the error reported back to here
7558           // and giving a diagnostic with a fixit attached to the error itself.
7559           (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7560               ? nullptr
7561               : &NoArrowOperatorFound);
7562       if (Result.isInvalid()) {
7563         if (NoArrowOperatorFound) {
7564           if (FirstIteration) {
7565             Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7566               << BaseType << 1 << Base->getSourceRange()
7567               << FixItHint::CreateReplacement(OpLoc, ".");
7568             OpKind = tok::period;
7569             break;
7570           }
7571           Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7572             << BaseType << Base->getSourceRange();
7573           CallExpr *CE = dyn_cast<CallExpr>(Base);
7574           if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7575             Diag(CD->getBeginLoc(),
7576                  diag::note_member_reference_arrow_from_operator_arrow);
7577           }
7578         }
7579         return ExprError();
7580       }
7581       Base = Result.get();
7582       if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7583         OperatorArrows.push_back(OpCall->getDirectCallee());
7584       BaseType = Base->getType();
7585       CanQualType CBaseType = Context.getCanonicalType(BaseType);
7586       if (!CTypes.insert(CBaseType).second) {
7587         Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7588         noteOperatorArrows(*this, OperatorArrows);
7589         return ExprError();
7590       }
7591       FirstIteration = false;
7592     }
7593 
7594     if (OpKind == tok::arrow) {
7595       if (BaseType->isPointerType())
7596         BaseType = BaseType->getPointeeType();
7597       else if (auto *AT = Context.getAsArrayType(BaseType))
7598         BaseType = AT->getElementType();
7599     }
7600   }
7601 
7602   // Objective-C properties allow "." access on Objective-C pointer types,
7603   // so adjust the base type to the object type itself.
7604   if (BaseType->isObjCObjectPointerType())
7605     BaseType = BaseType->getPointeeType();
7606 
7607   // C++ [basic.lookup.classref]p2:
7608   //   [...] If the type of the object expression is of pointer to scalar
7609   //   type, the unqualified-id is looked up in the context of the complete
7610   //   postfix-expression.
7611   //
7612   // This also indicates that we could be parsing a pseudo-destructor-name.
7613   // Note that Objective-C class and object types can be pseudo-destructor
7614   // expressions or normal member (ivar or property) access expressions, and
7615   // it's legal for the type to be incomplete if this is a pseudo-destructor
7616   // call.  We'll do more incomplete-type checks later in the lookup process,
7617   // so just skip this check for ObjC types.
7618   if (!BaseType->isRecordType()) {
7619     ObjectType = ParsedType::make(BaseType);
7620     MayBePseudoDestructor = true;
7621     return Base;
7622   }
7623 
7624   // The object type must be complete (or dependent), or
7625   // C++11 [expr.prim.general]p3:
7626   //   Unlike the object expression in other contexts, *this is not required to
7627   //   be of complete type for purposes of class member access (5.2.5) outside
7628   //   the member function body.
7629   if (!BaseType->isDependentType() &&
7630       !isThisOutsideMemberFunctionBody(BaseType) &&
7631       RequireCompleteType(OpLoc, BaseType,
7632                           diag::err_incomplete_member_access)) {
7633     return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
7634   }
7635 
7636   // C++ [basic.lookup.classref]p2:
7637   //   If the id-expression in a class member access (5.2.5) is an
7638   //   unqualified-id, and the type of the object expression is of a class
7639   //   type C (or of pointer to a class type C), the unqualified-id is looked
7640   //   up in the scope of class C. [...]
7641   ObjectType = ParsedType::make(BaseType);
7642   return Base;
7643 }
7644 
7645 static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
7646                        tok::TokenKind &OpKind, SourceLocation OpLoc) {
7647   if (Base->hasPlaceholderType()) {
7648     ExprResult result = S.CheckPlaceholderExpr(Base);
7649     if (result.isInvalid()) return true;
7650     Base = result.get();
7651   }
7652   ObjectType = Base->getType();
7653 
7654   // C++ [expr.pseudo]p2:
7655   //   The left-hand side of the dot operator shall be of scalar type. The
7656   //   left-hand side of the arrow operator shall be of pointer to scalar type.
7657   //   This scalar type is the object type.
7658   // Note that this is rather different from the normal handling for the
7659   // arrow operator.
7660   if (OpKind == tok::arrow) {
7661     // The operator requires a prvalue, so perform lvalue conversions.
7662     // Only do this if we might plausibly end with a pointer, as otherwise
7663     // this was likely to be intended to be a '.'.
7664     if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
7665         ObjectType->isFunctionType()) {
7666       ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base);
7667       if (BaseResult.isInvalid())
7668         return true;
7669       Base = BaseResult.get();
7670       ObjectType = Base->getType();
7671     }
7672 
7673     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7674       ObjectType = Ptr->getPointeeType();
7675     } else if (!Base->isTypeDependent()) {
7676       // The user wrote "p->" when they probably meant "p."; fix it.
7677       S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7678         << ObjectType << true
7679         << FixItHint::CreateReplacement(OpLoc, ".");
7680       if (S.isSFINAEContext())
7681         return true;
7682 
7683       OpKind = tok::period;
7684     }
7685   }
7686 
7687   return false;
7688 }
7689 
7690 /// Check if it's ok to try and recover dot pseudo destructor calls on
7691 /// pointer objects.
7692 static bool
7693 canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
7694                                                    QualType DestructedType) {
7695   // If this is a record type, check if its destructor is callable.
7696   if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
7697     if (RD->hasDefinition())
7698       if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
7699         return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
7700     return false;
7701   }
7702 
7703   // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7704   return DestructedType->isDependentType() || DestructedType->isScalarType() ||
7705          DestructedType->isVectorType();
7706 }
7707 
7708 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
7709                                            SourceLocation OpLoc,
7710                                            tok::TokenKind OpKind,
7711                                            const CXXScopeSpec &SS,
7712                                            TypeSourceInfo *ScopeTypeInfo,
7713                                            SourceLocation CCLoc,
7714                                            SourceLocation TildeLoc,
7715                                          PseudoDestructorTypeStorage Destructed) {
7716   TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
7717 
7718   QualType ObjectType;
7719   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7720     return ExprError();
7721 
7722   if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
7723       !ObjectType->isVectorType()) {
7724     if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
7725       Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
7726     else {
7727       Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
7728         << ObjectType << Base->getSourceRange();
7729       return ExprError();
7730     }
7731   }
7732 
7733   // C++ [expr.pseudo]p2:
7734   //   [...] The cv-unqualified versions of the object type and of the type
7735   //   designated by the pseudo-destructor-name shall be the same type.
7736   if (DestructedTypeInfo) {
7737     QualType DestructedType = DestructedTypeInfo->getType();
7738     SourceLocation DestructedTypeStart =
7739         DestructedTypeInfo->getTypeLoc().getBeginLoc();
7740     if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
7741       if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
7742         // Detect dot pseudo destructor calls on pointer objects, e.g.:
7743         //   Foo *foo;
7744         //   foo.~Foo();
7745         if (OpKind == tok::period && ObjectType->isPointerType() &&
7746             Context.hasSameUnqualifiedType(DestructedType,
7747                                            ObjectType->getPointeeType())) {
7748           auto Diagnostic =
7749               Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7750               << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
7751 
7752           // Issue a fixit only when the destructor is valid.
7753           if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
7754                   *this, DestructedType))
7755             Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
7756 
7757           // Recover by setting the object type to the destructed type and the
7758           // operator to '->'.
7759           ObjectType = DestructedType;
7760           OpKind = tok::arrow;
7761         } else {
7762           Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
7763               << ObjectType << DestructedType << Base->getSourceRange()
7764               << DestructedTypeInfo->getTypeLoc().getSourceRange();
7765 
7766           // Recover by setting the destructed type to the object type.
7767           DestructedType = ObjectType;
7768           DestructedTypeInfo =
7769               Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
7770           Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7771         }
7772       } else if (DestructedType.getObjCLifetime() !=
7773                                                 ObjectType.getObjCLifetime()) {
7774 
7775         if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
7776           // Okay: just pretend that the user provided the correctly-qualified
7777           // type.
7778         } else {
7779           Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
7780               << ObjectType << DestructedType << Base->getSourceRange()
7781               << DestructedTypeInfo->getTypeLoc().getSourceRange();
7782         }
7783 
7784         // Recover by setting the destructed type to the object type.
7785         DestructedType = ObjectType;
7786         DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
7787                                                            DestructedTypeStart);
7788         Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7789       }
7790     }
7791   }
7792 
7793   // C++ [expr.pseudo]p2:
7794   //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7795   //   form
7796   //
7797   //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
7798   //
7799   //   shall designate the same scalar type.
7800   if (ScopeTypeInfo) {
7801     QualType ScopeType = ScopeTypeInfo->getType();
7802     if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
7803         !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
7804 
7805       Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
7806            diag::err_pseudo_dtor_type_mismatch)
7807           << ObjectType << ScopeType << Base->getSourceRange()
7808           << ScopeTypeInfo->getTypeLoc().getSourceRange();
7809 
7810       ScopeType = QualType();
7811       ScopeTypeInfo = nullptr;
7812     }
7813   }
7814 
7815   Expr *Result
7816     = new (Context) CXXPseudoDestructorExpr(Context, Base,
7817                                             OpKind == tok::arrow, OpLoc,
7818                                             SS.getWithLocInContext(Context),
7819                                             ScopeTypeInfo,
7820                                             CCLoc,
7821                                             TildeLoc,
7822                                             Destructed);
7823 
7824   return Result;
7825 }
7826 
7827 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7828                                            SourceLocation OpLoc,
7829                                            tok::TokenKind OpKind,
7830                                            CXXScopeSpec &SS,
7831                                            UnqualifiedId &FirstTypeName,
7832                                            SourceLocation CCLoc,
7833                                            SourceLocation TildeLoc,
7834                                            UnqualifiedId &SecondTypeName) {
7835   assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7836           FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7837          "Invalid first type name in pseudo-destructor");
7838   assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7839           SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7840          "Invalid second type name in pseudo-destructor");
7841 
7842   QualType ObjectType;
7843   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7844     return ExprError();
7845 
7846   // Compute the object type that we should use for name lookup purposes. Only
7847   // record types and dependent types matter.
7848   ParsedType ObjectTypePtrForLookup;
7849   if (!SS.isSet()) {
7850     if (ObjectType->isRecordType())
7851       ObjectTypePtrForLookup = ParsedType::make(ObjectType);
7852     else if (ObjectType->isDependentType())
7853       ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
7854   }
7855 
7856   // Convert the name of the type being destructed (following the ~) into a
7857   // type (with source-location information).
7858   QualType DestructedType;
7859   TypeSourceInfo *DestructedTypeInfo = nullptr;
7860   PseudoDestructorTypeStorage Destructed;
7861   if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7862     ParsedType T = getTypeName(*SecondTypeName.Identifier,
7863                                SecondTypeName.StartLocation,
7864                                S, &SS, true, false, ObjectTypePtrForLookup,
7865                                /*IsCtorOrDtorName*/true);
7866     if (!T &&
7867         ((SS.isSet() && !computeDeclContext(SS, false)) ||
7868          (!SS.isSet() && ObjectType->isDependentType()))) {
7869       // The name of the type being destroyed is a dependent name, and we
7870       // couldn't find anything useful in scope. Just store the identifier and
7871       // it's location, and we'll perform (qualified) name lookup again at
7872       // template instantiation time.
7873       Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7874                                                SecondTypeName.StartLocation);
7875     } else if (!T) {
7876       Diag(SecondTypeName.StartLocation,
7877            diag::err_pseudo_dtor_destructor_non_type)
7878         << SecondTypeName.Identifier << ObjectType;
7879       if (isSFINAEContext())
7880         return ExprError();
7881 
7882       // Recover by assuming we had the right type all along.
7883       DestructedType = ObjectType;
7884     } else
7885       DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
7886   } else {
7887     // Resolve the template-id to a type.
7888     TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
7889     ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7890                                        TemplateId->NumArgs);
7891     TypeResult T = ActOnTemplateIdType(S,
7892                                        SS,
7893                                        TemplateId->TemplateKWLoc,
7894                                        TemplateId->Template,
7895                                        TemplateId->Name,
7896                                        TemplateId->TemplateNameLoc,
7897                                        TemplateId->LAngleLoc,
7898                                        TemplateArgsPtr,
7899                                        TemplateId->RAngleLoc,
7900                                        /*IsCtorOrDtorName*/true);
7901     if (T.isInvalid() || !T.get()) {
7902       // Recover by assuming we had the right type all along.
7903       DestructedType = ObjectType;
7904     } else
7905       DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
7906   }
7907 
7908   // If we've performed some kind of recovery, (re-)build the type source
7909   // information.
7910   if (!DestructedType.isNull()) {
7911     if (!DestructedTypeInfo)
7912       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
7913                                                   SecondTypeName.StartLocation);
7914     Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7915   }
7916 
7917   // Convert the name of the scope type (the type prior to '::') into a type.
7918   TypeSourceInfo *ScopeTypeInfo = nullptr;
7919   QualType ScopeType;
7920   if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7921       FirstTypeName.Identifier) {
7922     if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7923       ParsedType T = getTypeName(*FirstTypeName.Identifier,
7924                                  FirstTypeName.StartLocation,
7925                                  S, &SS, true, false, ObjectTypePtrForLookup,
7926                                  /*IsCtorOrDtorName*/true);
7927       if (!T) {
7928         Diag(FirstTypeName.StartLocation,
7929              diag::err_pseudo_dtor_destructor_non_type)
7930           << FirstTypeName.Identifier << ObjectType;
7931 
7932         if (isSFINAEContext())
7933           return ExprError();
7934 
7935         // Just drop this type. It's unnecessary anyway.
7936         ScopeType = QualType();
7937       } else
7938         ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
7939     } else {
7940       // Resolve the template-id to a type.
7941       TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
7942       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7943                                          TemplateId->NumArgs);
7944       TypeResult T = ActOnTemplateIdType(S,
7945                                          SS,
7946                                          TemplateId->TemplateKWLoc,
7947                                          TemplateId->Template,
7948                                          TemplateId->Name,
7949                                          TemplateId->TemplateNameLoc,
7950                                          TemplateId->LAngleLoc,
7951                                          TemplateArgsPtr,
7952                                          TemplateId->RAngleLoc,
7953                                          /*IsCtorOrDtorName*/true);
7954       if (T.isInvalid() || !T.get()) {
7955         // Recover by dropping this type.
7956         ScopeType = QualType();
7957       } else
7958         ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
7959     }
7960   }
7961 
7962   if (!ScopeType.isNull() && !ScopeTypeInfo)
7963     ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7964                                                   FirstTypeName.StartLocation);
7965 
7966 
7967   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
7968                                    ScopeTypeInfo, CCLoc, TildeLoc,
7969                                    Destructed);
7970 }
7971 
7972 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7973                                            SourceLocation OpLoc,
7974                                            tok::TokenKind OpKind,
7975                                            SourceLocation TildeLoc,
7976                                            const DeclSpec& DS) {
7977   QualType ObjectType;
7978   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7979     return ExprError();
7980 
7981   if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
7982     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
7983     return true;
7984   }
7985 
7986   QualType T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
7987 
7988   TypeLocBuilder TLB;
7989   DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7990   DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
7991   DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
7992   TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7993   PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7994 
7995   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
7996                                    nullptr, SourceLocation(), TildeLoc,
7997                                    Destructed);
7998 }
7999 
8000 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
8001                                         CXXConversionDecl *Method,
8002                                         bool HadMultipleCandidates) {
8003   // Convert the expression to match the conversion function's implicit object
8004   // parameter.
8005   ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
8006                                           FoundDecl, Method);
8007   if (Exp.isInvalid())
8008     return true;
8009 
8010   if (Method->getParent()->isLambda() &&
8011       Method->getConversionType()->isBlockPointerType()) {
8012     // This is a lambda conversion to block pointer; check if the argument
8013     // was a LambdaExpr.
8014     Expr *SubE = E;
8015     CastExpr *CE = dyn_cast<CastExpr>(SubE);
8016     if (CE && CE->getCastKind() == CK_NoOp)
8017       SubE = CE->getSubExpr();
8018     SubE = SubE->IgnoreParens();
8019     if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
8020       SubE = BE->getSubExpr();
8021     if (isa<LambdaExpr>(SubE)) {
8022       // For the conversion to block pointer on a lambda expression, we
8023       // construct a special BlockLiteral instead; this doesn't really make
8024       // a difference in ARC, but outside of ARC the resulting block literal
8025       // follows the normal lifetime rules for block literals instead of being
8026       // autoreleased.
8027       PushExpressionEvaluationContext(
8028           ExpressionEvaluationContext::PotentiallyEvaluated);
8029       ExprResult BlockExp = BuildBlockForLambdaConversion(
8030           Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
8031       PopExpressionEvaluationContext();
8032 
8033       // FIXME: This note should be produced by a CodeSynthesisContext.
8034       if (BlockExp.isInvalid())
8035         Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
8036       return BlockExp;
8037     }
8038   }
8039 
8040   MemberExpr *ME =
8041       BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
8042                       NestedNameSpecifierLoc(), SourceLocation(), Method,
8043                       DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
8044                       HadMultipleCandidates, DeclarationNameInfo(),
8045                       Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
8046 
8047   QualType ResultType = Method->getReturnType();
8048   ExprValueKind VK = Expr::getValueKindForType(ResultType);
8049   ResultType = ResultType.getNonLValueExprType(Context);
8050 
8051   CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
8052       Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc(),
8053       CurFPFeatureOverrides());
8054 
8055   if (CheckFunctionCall(Method, CE,
8056                         Method->getType()->castAs<FunctionProtoType>()))
8057     return ExprError();
8058 
8059   return CheckForImmediateInvocation(CE, CE->getMethodDecl());
8060 }
8061 
8062 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8063                                       SourceLocation RParen) {
8064   // If the operand is an unresolved lookup expression, the expression is ill-
8065   // formed per [over.over]p1, because overloaded function names cannot be used
8066   // without arguments except in explicit contexts.
8067   ExprResult R = CheckPlaceholderExpr(Operand);
8068   if (R.isInvalid())
8069     return R;
8070 
8071   R = CheckUnevaluatedOperand(R.get());
8072   if (R.isInvalid())
8073     return ExprError();
8074 
8075   Operand = R.get();
8076 
8077   if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
8078       Operand->HasSideEffects(Context, false)) {
8079     // The expression operand for noexcept is in an unevaluated expression
8080     // context, so side effects could result in unintended consequences.
8081     Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8082   }
8083 
8084   CanThrowResult CanThrow = canThrow(Operand);
8085   return new (Context)
8086       CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
8087 }
8088 
8089 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
8090                                    Expr *Operand, SourceLocation RParen) {
8091   return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
8092 }
8093 
8094 static void MaybeDecrementCount(
8095     Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
8096   DeclRefExpr *LHS = nullptr;
8097   bool IsCompoundAssign = false;
8098   bool isIncrementDecrementUnaryOp = false;
8099   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8100     if (BO->getLHS()->getType()->isDependentType() ||
8101         BO->getRHS()->getType()->isDependentType()) {
8102       if (BO->getOpcode() != BO_Assign)
8103         return;
8104     } else if (!BO->isAssignmentOp())
8105       return;
8106     else
8107       IsCompoundAssign = BO->isCompoundAssignmentOp();
8108     LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
8109   } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
8110     if (COCE->getOperator() != OO_Equal)
8111       return;
8112     LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
8113   } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8114     if (!UO->isIncrementDecrementOp())
8115       return;
8116     isIncrementDecrementUnaryOp = true;
8117     LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());
8118   }
8119   if (!LHS)
8120     return;
8121   VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
8122   if (!VD)
8123     return;
8124   // Don't decrement RefsMinusAssignments if volatile variable with compound
8125   // assignment (+=, ...) or increment/decrement unary operator to avoid
8126   // potential unused-but-set-variable warning.
8127   if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
8128       VD->getType().isVolatileQualified())
8129     return;
8130   auto iter = RefsMinusAssignments.find(VD);
8131   if (iter == RefsMinusAssignments.end())
8132     return;
8133   iter->getSecond()--;
8134 }
8135 
8136 /// Perform the conversions required for an expression used in a
8137 /// context that ignores the result.
8138 ExprResult Sema::IgnoredValueConversions(Expr *E) {
8139   MaybeDecrementCount(E, RefsMinusAssignments);
8140 
8141   if (E->hasPlaceholderType()) {
8142     ExprResult result = CheckPlaceholderExpr(E);
8143     if (result.isInvalid()) return E;
8144     E = result.get();
8145   }
8146 
8147   // C99 6.3.2.1:
8148   //   [Except in specific positions,] an lvalue that does not have
8149   //   array type is converted to the value stored in the
8150   //   designated object (and is no longer an lvalue).
8151   if (E->isPRValue()) {
8152     // In C, function designators (i.e. expressions of function type)
8153     // are r-values, but we still want to do function-to-pointer decay
8154     // on them.  This is both technically correct and convenient for
8155     // some clients.
8156     if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
8157       return DefaultFunctionArrayConversion(E);
8158 
8159     return E;
8160   }
8161 
8162   if (getLangOpts().CPlusPlus) {
8163     // The C++11 standard defines the notion of a discarded-value expression;
8164     // normally, we don't need to do anything to handle it, but if it is a
8165     // volatile lvalue with a special form, we perform an lvalue-to-rvalue
8166     // conversion.
8167     if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) {
8168       ExprResult Res = DefaultLvalueConversion(E);
8169       if (Res.isInvalid())
8170         return E;
8171       E = Res.get();
8172     } else {
8173       // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8174       // it occurs as a discarded-value expression.
8175       CheckUnusedVolatileAssignment(E);
8176     }
8177 
8178     // C++1z:
8179     //   If the expression is a prvalue after this optional conversion, the
8180     //   temporary materialization conversion is applied.
8181     //
8182     // We skip this step: IR generation is able to synthesize the storage for
8183     // itself in the aggregate case, and adding the extra node to the AST is
8184     // just clutter.
8185     // FIXME: We don't emit lifetime markers for the temporaries due to this.
8186     // FIXME: Do any other AST consumers care about this?
8187     return E;
8188   }
8189 
8190   // GCC seems to also exclude expressions of incomplete enum type.
8191   if (const EnumType *T = E->getType()->getAs<EnumType>()) {
8192     if (!T->getDecl()->isComplete()) {
8193       // FIXME: stupid workaround for a codegen bug!
8194       E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
8195       return E;
8196     }
8197   }
8198 
8199   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
8200   if (Res.isInvalid())
8201     return E;
8202   E = Res.get();
8203 
8204   if (!E->getType()->isVoidType())
8205     RequireCompleteType(E->getExprLoc(), E->getType(),
8206                         diag::err_incomplete_type);
8207   return E;
8208 }
8209 
8210 ExprResult Sema::CheckUnevaluatedOperand(Expr *E) {
8211   // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8212   // it occurs as an unevaluated operand.
8213   CheckUnusedVolatileAssignment(E);
8214 
8215   return E;
8216 }
8217 
8218 // If we can unambiguously determine whether Var can never be used
8219 // in a constant expression, return true.
8220 //  - if the variable and its initializer are non-dependent, then
8221 //    we can unambiguously check if the variable is a constant expression.
8222 //  - if the initializer is not value dependent - we can determine whether
8223 //    it can be used to initialize a constant expression.  If Init can not
8224 //    be used to initialize a constant expression we conclude that Var can
8225 //    never be a constant expression.
8226 //  - FXIME: if the initializer is dependent, we can still do some analysis and
8227 //    identify certain cases unambiguously as non-const by using a Visitor:
8228 //      - such as those that involve odr-use of a ParmVarDecl, involve a new
8229 //        delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
8230 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
8231     ASTContext &Context) {
8232   if (isa<ParmVarDecl>(Var)) return true;
8233   const VarDecl *DefVD = nullptr;
8234 
8235   // If there is no initializer - this can not be a constant expression.
8236   if (!Var->getAnyInitializer(DefVD)) return true;
8237   assert(DefVD);
8238   if (DefVD->isWeak()) return false;
8239   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
8240 
8241   Expr *Init = cast<Expr>(Eval->Value);
8242 
8243   if (Var->getType()->isDependentType() || Init->isValueDependent()) {
8244     // FIXME: Teach the constant evaluator to deal with the non-dependent parts
8245     // of value-dependent expressions, and use it here to determine whether the
8246     // initializer is a potential constant expression.
8247     return false;
8248   }
8249 
8250   return !Var->isUsableInConstantExpressions(Context);
8251 }
8252 
8253 /// Check if the current lambda has any potential captures
8254 /// that must be captured by any of its enclosing lambdas that are ready to
8255 /// capture. If there is a lambda that can capture a nested
8256 /// potential-capture, go ahead and do so.  Also, check to see if any
8257 /// variables are uncaptureable or do not involve an odr-use so do not
8258 /// need to be captured.
8259 
8260 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
8261     Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
8262 
8263   assert(!S.isUnevaluatedContext());
8264   assert(S.CurContext->isDependentContext());
8265 #ifndef NDEBUG
8266   DeclContext *DC = S.CurContext;
8267   while (DC && isa<CapturedDecl>(DC))
8268     DC = DC->getParent();
8269   assert(
8270       CurrentLSI->CallOperator == DC &&
8271       "The current call operator must be synchronized with Sema's CurContext");
8272 #endif // NDEBUG
8273 
8274   const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
8275 
8276   // All the potentially captureable variables in the current nested
8277   // lambda (within a generic outer lambda), must be captured by an
8278   // outer lambda that is enclosed within a non-dependent context.
8279   CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {
8280     // If the variable is clearly identified as non-odr-used and the full
8281     // expression is not instantiation dependent, only then do we not
8282     // need to check enclosing lambda's for speculative captures.
8283     // For e.g.:
8284     // Even though 'x' is not odr-used, it should be captured.
8285     // int test() {
8286     //   const int x = 10;
8287     //   auto L = [=](auto a) {
8288     //     (void) +x + a;
8289     //   };
8290     // }
8291     if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
8292         !IsFullExprInstantiationDependent)
8293       return;
8294 
8295     VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();
8296     if (!UnderlyingVar)
8297       return;
8298 
8299     // If we have a capture-capable lambda for the variable, go ahead and
8300     // capture the variable in that lambda (and all its enclosing lambdas).
8301     if (const std::optional<unsigned> Index =
8302             getStackIndexOfNearestEnclosingCaptureCapableLambda(
8303                 S.FunctionScopes, Var, S))
8304       S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);
8305     const bool IsVarNeverAConstantExpression =
8306         VariableCanNeverBeAConstantExpression(UnderlyingVar, S.Context);
8307     if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
8308       // This full expression is not instantiation dependent or the variable
8309       // can not be used in a constant expression - which means
8310       // this variable must be odr-used here, so diagnose a
8311       // capture violation early, if the variable is un-captureable.
8312       // This is purely for diagnosing errors early.  Otherwise, this
8313       // error would get diagnosed when the lambda becomes capture ready.
8314       QualType CaptureType, DeclRefType;
8315       SourceLocation ExprLoc = VarExpr->getExprLoc();
8316       if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8317                           /*EllipsisLoc*/ SourceLocation(),
8318                           /*BuildAndDiagnose*/false, CaptureType,
8319                           DeclRefType, nullptr)) {
8320         // We will never be able to capture this variable, and we need
8321         // to be able to in any and all instantiations, so diagnose it.
8322         S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8323                           /*EllipsisLoc*/ SourceLocation(),
8324                           /*BuildAndDiagnose*/true, CaptureType,
8325                           DeclRefType, nullptr);
8326       }
8327     }
8328   });
8329 
8330   // Check if 'this' needs to be captured.
8331   if (CurrentLSI->hasPotentialThisCapture()) {
8332     // If we have a capture-capable lambda for 'this', go ahead and capture
8333     // 'this' in that lambda (and all its enclosing lambdas).
8334     if (const std::optional<unsigned> Index =
8335             getStackIndexOfNearestEnclosingCaptureCapableLambda(
8336                 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
8337       const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
8338       S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
8339                             /*Explicit*/ false, /*BuildAndDiagnose*/ true,
8340                             &FunctionScopeIndexOfCapturableLambda);
8341     }
8342   }
8343 
8344   // Reset all the potential captures at the end of each full-expression.
8345   CurrentLSI->clearPotentialCaptures();
8346 }
8347 
8348 static ExprResult attemptRecovery(Sema &SemaRef,
8349                                   const TypoCorrectionConsumer &Consumer,
8350                                   const TypoCorrection &TC) {
8351   LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
8352                  Consumer.getLookupResult().getLookupKind());
8353   const CXXScopeSpec *SS = Consumer.getSS();
8354   CXXScopeSpec NewSS;
8355 
8356   // Use an approprate CXXScopeSpec for building the expr.
8357   if (auto *NNS = TC.getCorrectionSpecifier())
8358     NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
8359   else if (SS && !TC.WillReplaceSpecifier())
8360     NewSS = *SS;
8361 
8362   if (auto *ND = TC.getFoundDecl()) {
8363     R.setLookupName(ND->getDeclName());
8364     R.addDecl(ND);
8365     if (ND->isCXXClassMember()) {
8366       // Figure out the correct naming class to add to the LookupResult.
8367       CXXRecordDecl *Record = nullptr;
8368       if (auto *NNS = TC.getCorrectionSpecifier())
8369         Record = NNS->getAsType()->getAsCXXRecordDecl();
8370       if (!Record)
8371         Record =
8372             dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
8373       if (Record)
8374         R.setNamingClass(Record);
8375 
8376       // Detect and handle the case where the decl might be an implicit
8377       // member.
8378       bool MightBeImplicitMember;
8379       if (!Consumer.isAddressOfOperand())
8380         MightBeImplicitMember = true;
8381       else if (!NewSS.isEmpty())
8382         MightBeImplicitMember = false;
8383       else if (R.isOverloadedResult())
8384         MightBeImplicitMember = false;
8385       else if (R.isUnresolvableResult())
8386         MightBeImplicitMember = true;
8387       else
8388         MightBeImplicitMember = isa<FieldDecl>(ND) ||
8389                                 isa<IndirectFieldDecl>(ND) ||
8390                                 isa<MSPropertyDecl>(ND);
8391 
8392       if (MightBeImplicitMember)
8393         return SemaRef.BuildPossibleImplicitMemberExpr(
8394             NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
8395             /*TemplateArgs*/ nullptr, /*S*/ nullptr);
8396     } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
8397       return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
8398                                         Ivar->getIdentifier());
8399     }
8400   }
8401 
8402   return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
8403                                           /*AcceptInvalidDecl*/ true);
8404 }
8405 
8406 namespace {
8407 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
8408   llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
8409 
8410 public:
8411   explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
8412       : TypoExprs(TypoExprs) {}
8413   bool VisitTypoExpr(TypoExpr *TE) {
8414     TypoExprs.insert(TE);
8415     return true;
8416   }
8417 };
8418 
8419 class TransformTypos : public TreeTransform<TransformTypos> {
8420   typedef TreeTransform<TransformTypos> BaseTransform;
8421 
8422   VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
8423                      // process of being initialized.
8424   llvm::function_ref<ExprResult(Expr *)> ExprFilter;
8425   llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
8426   llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
8427   llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
8428 
8429   /// Emit diagnostics for all of the TypoExprs encountered.
8430   ///
8431   /// If the TypoExprs were successfully corrected, then the diagnostics should
8432   /// suggest the corrections. Otherwise the diagnostics will not suggest
8433   /// anything (having been passed an empty TypoCorrection).
8434   ///
8435   /// If we've failed to correct due to ambiguous corrections, we need to
8436   /// be sure to pass empty corrections and replacements. Otherwise it's
8437   /// possible that the Consumer has a TypoCorrection that failed to ambiguity
8438   /// and we don't want to report those diagnostics.
8439   void EmitAllDiagnostics(bool IsAmbiguous) {
8440     for (TypoExpr *TE : TypoExprs) {
8441       auto &State = SemaRef.getTypoExprState(TE);
8442       if (State.DiagHandler) {
8443         TypoCorrection TC = IsAmbiguous
8444             ? TypoCorrection() : State.Consumer->getCurrentCorrection();
8445         ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
8446 
8447         // Extract the NamedDecl from the transformed TypoExpr and add it to the
8448         // TypoCorrection, replacing the existing decls. This ensures the right
8449         // NamedDecl is used in diagnostics e.g. in the case where overload
8450         // resolution was used to select one from several possible decls that
8451         // had been stored in the TypoCorrection.
8452         if (auto *ND = getDeclFromExpr(
8453                 Replacement.isInvalid() ? nullptr : Replacement.get()))
8454           TC.setCorrectionDecl(ND);
8455 
8456         State.DiagHandler(TC);
8457       }
8458       SemaRef.clearDelayedTypo(TE);
8459     }
8460   }
8461 
8462   /// Try to advance the typo correction state of the first unfinished TypoExpr.
8463   /// We allow advancement of the correction stream by removing it from the
8464   /// TransformCache which allows `TransformTypoExpr` to advance during the
8465   /// next transformation attempt.
8466   ///
8467   /// Any substitution attempts for the previous TypoExprs (which must have been
8468   /// finished) will need to be retried since it's possible that they will now
8469   /// be invalid given the latest advancement.
8470   ///
8471   /// We need to be sure that we're making progress - it's possible that the
8472   /// tree is so malformed that the transform never makes it to the
8473   /// `TransformTypoExpr`.
8474   ///
8475   /// Returns true if there are any untried correction combinations.
8476   bool CheckAndAdvanceTypoExprCorrectionStreams() {
8477     for (auto *TE : TypoExprs) {
8478       auto &State = SemaRef.getTypoExprState(TE);
8479       TransformCache.erase(TE);
8480       if (!State.Consumer->hasMadeAnyCorrectionProgress())
8481         return false;
8482       if (!State.Consumer->finished())
8483         return true;
8484       State.Consumer->resetCorrectionStream();
8485     }
8486     return false;
8487   }
8488 
8489   NamedDecl *getDeclFromExpr(Expr *E) {
8490     if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8491       E = OverloadResolution[OE];
8492 
8493     if (!E)
8494       return nullptr;
8495     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
8496       return DRE->getFoundDecl();
8497     if (auto *ME = dyn_cast<MemberExpr>(E))
8498       return ME->getFoundDecl();
8499     // FIXME: Add any other expr types that could be seen by the delayed typo
8500     // correction TreeTransform for which the corresponding TypoCorrection could
8501     // contain multiple decls.
8502     return nullptr;
8503   }
8504 
8505   ExprResult TryTransform(Expr *E) {
8506     Sema::SFINAETrap Trap(SemaRef);
8507     ExprResult Res = TransformExpr(E);
8508     if (Trap.hasErrorOccurred() || Res.isInvalid())
8509       return ExprError();
8510 
8511     return ExprFilter(Res.get());
8512   }
8513 
8514   // Since correcting typos may intoduce new TypoExprs, this function
8515   // checks for new TypoExprs and recurses if it finds any. Note that it will
8516   // only succeed if it is able to correct all typos in the given expression.
8517   ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8518     if (Res.isInvalid()) {
8519       return Res;
8520     }
8521     // Check to see if any new TypoExprs were created. If so, we need to recurse
8522     // to check their validity.
8523     Expr *FixedExpr = Res.get();
8524 
8525     auto SavedTypoExprs = std::move(TypoExprs);
8526     auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8527     TypoExprs.clear();
8528     AmbiguousTypoExprs.clear();
8529 
8530     FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8531     if (!TypoExprs.empty()) {
8532       // Recurse to handle newly created TypoExprs. If we're not able to
8533       // handle them, discard these TypoExprs.
8534       ExprResult RecurResult =
8535           RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8536       if (RecurResult.isInvalid()) {
8537         Res = ExprError();
8538         // Recursive corrections didn't work, wipe them away and don't add
8539         // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8540         // since we don't want to clear them twice. Note: it's possible the
8541         // TypoExprs were created recursively and thus won't be in our
8542         // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8543         auto &SemaTypoExprs = SemaRef.TypoExprs;
8544         for (auto *TE : TypoExprs) {
8545           TransformCache.erase(TE);
8546           SemaRef.clearDelayedTypo(TE);
8547 
8548           auto SI = find(SemaTypoExprs, TE);
8549           if (SI != SemaTypoExprs.end()) {
8550             SemaTypoExprs.erase(SI);
8551           }
8552         }
8553       } else {
8554         // TypoExpr is valid: add newly created TypoExprs since we were
8555         // able to correct them.
8556         Res = RecurResult;
8557         SavedTypoExprs.set_union(TypoExprs);
8558       }
8559     }
8560 
8561     TypoExprs = std::move(SavedTypoExprs);
8562     AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8563 
8564     return Res;
8565   }
8566 
8567   // Try to transform the given expression, looping through the correction
8568   // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8569   //
8570   // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8571   // true and this method immediately will return an `ExprError`.
8572   ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8573     ExprResult Res;
8574     auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8575     SemaRef.TypoExprs.clear();
8576 
8577     while (true) {
8578       Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8579 
8580       // Recursion encountered an ambiguous correction. This means that our
8581       // correction itself is ambiguous, so stop now.
8582       if (IsAmbiguous)
8583         break;
8584 
8585       // If the transform is still valid after checking for any new typos,
8586       // it's good to go.
8587       if (!Res.isInvalid())
8588         break;
8589 
8590       // The transform was invalid, see if we have any TypoExprs with untried
8591       // correction candidates.
8592       if (!CheckAndAdvanceTypoExprCorrectionStreams())
8593         break;
8594     }
8595 
8596     // If we found a valid result, double check to make sure it's not ambiguous.
8597     if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
8598       auto SavedTransformCache =
8599           llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8600 
8601       // Ensure none of the TypoExprs have multiple typo correction candidates
8602       // with the same edit length that pass all the checks and filters.
8603       while (!AmbiguousTypoExprs.empty()) {
8604         auto TE  = AmbiguousTypoExprs.back();
8605 
8606         // TryTransform itself can create new Typos, adding them to the TypoExpr map
8607         // and invalidating our TypoExprState, so always fetch it instead of storing.
8608         SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8609 
8610         TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8611         TypoCorrection Next;
8612         do {
8613           // Fetch the next correction by erasing the typo from the cache and calling
8614           // `TryTransform` which will iterate through corrections in
8615           // `TransformTypoExpr`.
8616           TransformCache.erase(TE);
8617           ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8618 
8619           if (!AmbigRes.isInvalid() || IsAmbiguous) {
8620             SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8621             SavedTransformCache.erase(TE);
8622             Res = ExprError();
8623             IsAmbiguous = true;
8624             break;
8625           }
8626         } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8627                  Next.getEditDistance(false) == TC.getEditDistance(false));
8628 
8629         if (IsAmbiguous)
8630           break;
8631 
8632         AmbiguousTypoExprs.remove(TE);
8633         SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8634         TransformCache[TE] = SavedTransformCache[TE];
8635       }
8636       TransformCache = std::move(SavedTransformCache);
8637     }
8638 
8639     // Wipe away any newly created TypoExprs that we don't know about. Since we
8640     // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8641     // possible if a `TypoExpr` is created during a transformation but then
8642     // fails before we can discover it.
8643     auto &SemaTypoExprs = SemaRef.TypoExprs;
8644     for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
8645       auto TE = *Iterator;
8646       auto FI = find(TypoExprs, TE);
8647       if (FI != TypoExprs.end()) {
8648         Iterator++;
8649         continue;
8650       }
8651       SemaRef.clearDelayedTypo(TE);
8652       Iterator = SemaTypoExprs.erase(Iterator);
8653     }
8654     SemaRef.TypoExprs = std::move(SavedTypoExprs);
8655 
8656     return Res;
8657   }
8658 
8659 public:
8660   TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
8661       : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
8662 
8663   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
8664                                    MultiExprArg Args,
8665                                    SourceLocation RParenLoc,
8666                                    Expr *ExecConfig = nullptr) {
8667     auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
8668                                                  RParenLoc, ExecConfig);
8669     if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
8670       if (Result.isUsable()) {
8671         Expr *ResultCall = Result.get();
8672         if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
8673           ResultCall = BE->getSubExpr();
8674         if (auto *CE = dyn_cast<CallExpr>(ResultCall))
8675           OverloadResolution[OE] = CE->getCallee();
8676       }
8677     }
8678     return Result;
8679   }
8680 
8681   ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
8682 
8683   ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
8684 
8685   ExprResult Transform(Expr *E) {
8686     bool IsAmbiguous = false;
8687     ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
8688 
8689     if (!Res.isUsable())
8690       FindTypoExprs(TypoExprs).TraverseStmt(E);
8691 
8692     EmitAllDiagnostics(IsAmbiguous);
8693 
8694     return Res;
8695   }
8696 
8697   ExprResult TransformTypoExpr(TypoExpr *E) {
8698     // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
8699     // cached transformation result if there is one and the TypoExpr isn't the
8700     // first one that was encountered.
8701     auto &CacheEntry = TransformCache[E];
8702     if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
8703       return CacheEntry;
8704     }
8705 
8706     auto &State = SemaRef.getTypoExprState(E);
8707     assert(State.Consumer && "Cannot transform a cleared TypoExpr");
8708 
8709     // For the first TypoExpr and an uncached TypoExpr, find the next likely
8710     // typo correction and return it.
8711     while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
8712       if (InitDecl && TC.getFoundDecl() == InitDecl)
8713         continue;
8714       // FIXME: If we would typo-correct to an invalid declaration, it's
8715       // probably best to just suppress all errors from this typo correction.
8716       ExprResult NE = State.RecoveryHandler ?
8717           State.RecoveryHandler(SemaRef, E, TC) :
8718           attemptRecovery(SemaRef, *State.Consumer, TC);
8719       if (!NE.isInvalid()) {
8720         // Check whether there may be a second viable correction with the same
8721         // edit distance; if so, remember this TypoExpr may have an ambiguous
8722         // correction so it can be more thoroughly vetted later.
8723         TypoCorrection Next;
8724         if ((Next = State.Consumer->peekNextCorrection()) &&
8725             Next.getEditDistance(false) == TC.getEditDistance(false)) {
8726           AmbiguousTypoExprs.insert(E);
8727         } else {
8728           AmbiguousTypoExprs.remove(E);
8729         }
8730         assert(!NE.isUnset() &&
8731                "Typo was transformed into a valid-but-null ExprResult");
8732         return CacheEntry = NE;
8733       }
8734     }
8735     return CacheEntry = ExprError();
8736   }
8737 };
8738 }
8739 
8740 ExprResult
8741 Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
8742                                 bool RecoverUncorrectedTypos,
8743                                 llvm::function_ref<ExprResult(Expr *)> Filter) {
8744   // If the current evaluation context indicates there are uncorrected typos
8745   // and the current expression isn't guaranteed to not have typos, try to
8746   // resolve any TypoExpr nodes that might be in the expression.
8747   if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
8748       (E->isTypeDependent() || E->isValueDependent() ||
8749        E->isInstantiationDependent())) {
8750     auto TyposResolved = DelayedTypos.size();
8751     auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
8752     TyposResolved -= DelayedTypos.size();
8753     if (Result.isInvalid() || Result.get() != E) {
8754       ExprEvalContexts.back().NumTypos -= TyposResolved;
8755       if (Result.isInvalid() && RecoverUncorrectedTypos) {
8756         struct TyposReplace : TreeTransform<TyposReplace> {
8757           TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}
8758           ExprResult TransformTypoExpr(clang::TypoExpr *E) {
8759             return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),
8760                                                     E->getEndLoc(), {});
8761           }
8762         } TT(*this);
8763         return TT.TransformExpr(E);
8764       }
8765       return Result;
8766     }
8767     assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
8768   }
8769   return E;
8770 }
8771 
8772 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
8773                                      bool DiscardedValue, bool IsConstexpr,
8774                                      bool IsTemplateArgument) {
8775   ExprResult FullExpr = FE;
8776 
8777   if (!FullExpr.get())
8778     return ExprError();
8779 
8780   if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))
8781     return ExprError();
8782 
8783   if (DiscardedValue) {
8784     // Top-level expressions default to 'id' when we're in a debugger.
8785     if (getLangOpts().DebuggerCastResultToId &&
8786         FullExpr.get()->getType() == Context.UnknownAnyTy) {
8787       FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
8788       if (FullExpr.isInvalid())
8789         return ExprError();
8790     }
8791 
8792     FullExpr = CheckPlaceholderExpr(FullExpr.get());
8793     if (FullExpr.isInvalid())
8794       return ExprError();
8795 
8796     FullExpr = IgnoredValueConversions(FullExpr.get());
8797     if (FullExpr.isInvalid())
8798       return ExprError();
8799 
8800     DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
8801   }
8802 
8803   FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,
8804                                        /*RecoverUncorrectedTypos=*/true);
8805   if (FullExpr.isInvalid())
8806     return ExprError();
8807 
8808   CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
8809 
8810   // At the end of this full expression (which could be a deeply nested
8811   // lambda), if there is a potential capture within the nested lambda,
8812   // have the outer capture-able lambda try and capture it.
8813   // Consider the following code:
8814   // void f(int, int);
8815   // void f(const int&, double);
8816   // void foo() {
8817   //  const int x = 10, y = 20;
8818   //  auto L = [=](auto a) {
8819   //      auto M = [=](auto b) {
8820   //         f(x, b); <-- requires x to be captured by L and M
8821   //         f(y, a); <-- requires y to be captured by L, but not all Ms
8822   //      };
8823   //   };
8824   // }
8825 
8826   // FIXME: Also consider what happens for something like this that involves
8827   // the gnu-extension statement-expressions or even lambda-init-captures:
8828   //   void f() {
8829   //     const int n = 0;
8830   //     auto L =  [&](auto a) {
8831   //       +n + ({ 0; a; });
8832   //     };
8833   //   }
8834   //
8835   // Here, we see +n, and then the full-expression 0; ends, so we don't
8836   // capture n (and instead remove it from our list of potential captures),
8837   // and then the full-expression +n + ({ 0; }); ends, but it's too late
8838   // for us to see that we need to capture n after all.
8839 
8840   LambdaScopeInfo *const CurrentLSI =
8841       getCurLambda(/*IgnoreCapturedRegions=*/true);
8842   // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
8843   // even if CurContext is not a lambda call operator. Refer to that Bug Report
8844   // for an example of the code that might cause this asynchrony.
8845   // By ensuring we are in the context of a lambda's call operator
8846   // we can fix the bug (we only need to check whether we need to capture
8847   // if we are within a lambda's body); but per the comments in that
8848   // PR, a proper fix would entail :
8849   //   "Alternative suggestion:
8850   //   - Add to Sema an integer holding the smallest (outermost) scope
8851   //     index that we are *lexically* within, and save/restore/set to
8852   //     FunctionScopes.size() in InstantiatingTemplate's
8853   //     constructor/destructor.
8854   //  - Teach the handful of places that iterate over FunctionScopes to
8855   //    stop at the outermost enclosing lexical scope."
8856   DeclContext *DC = CurContext;
8857   while (DC && isa<CapturedDecl>(DC))
8858     DC = DC->getParent();
8859   const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
8860   if (IsInLambdaDeclContext && CurrentLSI &&
8861       CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
8862     CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
8863                                                               *this);
8864   return MaybeCreateExprWithCleanups(FullExpr);
8865 }
8866 
8867 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
8868   if (!FullStmt) return StmtError();
8869 
8870   return MaybeCreateStmtWithCleanups(FullStmt);
8871 }
8872 
8873 Sema::IfExistsResult
8874 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
8875                                    CXXScopeSpec &SS,
8876                                    const DeclarationNameInfo &TargetNameInfo) {
8877   DeclarationName TargetName = TargetNameInfo.getName();
8878   if (!TargetName)
8879     return IER_DoesNotExist;
8880 
8881   // If the name itself is dependent, then the result is dependent.
8882   if (TargetName.isDependentName())
8883     return IER_Dependent;
8884 
8885   // Do the redeclaration lookup in the current scope.
8886   LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
8887                  Sema::NotForRedeclaration);
8888   LookupParsedName(R, S, &SS);
8889   R.suppressDiagnostics();
8890 
8891   switch (R.getResultKind()) {
8892   case LookupResult::Found:
8893   case LookupResult::FoundOverloaded:
8894   case LookupResult::FoundUnresolvedValue:
8895   case LookupResult::Ambiguous:
8896     return IER_Exists;
8897 
8898   case LookupResult::NotFound:
8899     return IER_DoesNotExist;
8900 
8901   case LookupResult::NotFoundInCurrentInstantiation:
8902     return IER_Dependent;
8903   }
8904 
8905   llvm_unreachable("Invalid LookupResult Kind!");
8906 }
8907 
8908 Sema::IfExistsResult
8909 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
8910                                    bool IsIfExists, CXXScopeSpec &SS,
8911                                    UnqualifiedId &Name) {
8912   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8913 
8914   // Check for an unexpanded parameter pack.
8915   auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
8916   if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
8917       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
8918     return IER_Error;
8919 
8920   return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
8921 }
8922 
8923 concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) {
8924   return BuildExprRequirement(E, /*IsSimple=*/true,
8925                               /*NoexceptLoc=*/SourceLocation(),
8926                               /*ReturnTypeRequirement=*/{});
8927 }
8928 
8929 concepts::Requirement *
8930 Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS,
8931                            SourceLocation NameLoc, IdentifierInfo *TypeName,
8932                            TemplateIdAnnotation *TemplateId) {
8933   assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
8934          "Exactly one of TypeName and TemplateId must be specified.");
8935   TypeSourceInfo *TSI = nullptr;
8936   if (TypeName) {
8937     QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc,
8938                                    SS.getWithLocInContext(Context), *TypeName,
8939                                    NameLoc, &TSI, /*DeducedTSTContext=*/false);
8940     if (T.isNull())
8941       return nullptr;
8942   } else {
8943     ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
8944                                TemplateId->NumArgs);
8945     TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
8946                                      TemplateId->TemplateKWLoc,
8947                                      TemplateId->Template, TemplateId->Name,
8948                                      TemplateId->TemplateNameLoc,
8949                                      TemplateId->LAngleLoc, ArgsPtr,
8950                                      TemplateId->RAngleLoc);
8951     if (T.isInvalid())
8952       return nullptr;
8953     if (GetTypeFromParser(T.get(), &TSI).isNull())
8954       return nullptr;
8955   }
8956   return BuildTypeRequirement(TSI);
8957 }
8958 
8959 concepts::Requirement *
8960 Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) {
8961   return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
8962                               /*ReturnTypeRequirement=*/{});
8963 }
8964 
8965 concepts::Requirement *
8966 Sema::ActOnCompoundRequirement(
8967     Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8968     TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
8969   // C++2a [expr.prim.req.compound] p1.3.3
8970   //   [..] the expression is deduced against an invented function template
8971   //   F [...] F is a void function template with a single type template
8972   //   parameter T declared with the constrained-parameter. Form a new
8973   //   cv-qualifier-seq cv by taking the union of const and volatile specifiers
8974   //   around the constrained-parameter. F has a single parameter whose
8975   //   type-specifier is cv T followed by the abstract-declarator. [...]
8976   //
8977   // The cv part is done in the calling function - we get the concept with
8978   // arguments and the abstract declarator with the correct CV qualification and
8979   // have to synthesize T and the single parameter of F.
8980   auto &II = Context.Idents.get("expr-type");
8981   auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext,
8982                                               SourceLocation(),
8983                                               SourceLocation(), Depth,
8984                                               /*Index=*/0, &II,
8985                                               /*Typename=*/true,
8986                                               /*ParameterPack=*/false,
8987                                               /*HasTypeConstraint=*/true);
8988 
8989   if (BuildTypeConstraint(SS, TypeConstraint, TParam,
8990                           /*EllipsisLoc=*/SourceLocation(),
8991                           /*AllowUnexpandedPack=*/true))
8992     // Just produce a requirement with no type requirements.
8993     return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
8994 
8995   auto *TPL = TemplateParameterList::Create(Context, SourceLocation(),
8996                                             SourceLocation(),
8997                                             ArrayRef<NamedDecl *>(TParam),
8998                                             SourceLocation(),
8999                                             /*RequiresClause=*/nullptr);
9000   return BuildExprRequirement(
9001       E, /*IsSimple=*/false, NoexceptLoc,
9002       concepts::ExprRequirement::ReturnTypeRequirement(TPL));
9003 }
9004 
9005 concepts::ExprRequirement *
9006 Sema::BuildExprRequirement(
9007     Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
9008     concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
9009   auto Status = concepts::ExprRequirement::SS_Satisfied;
9010   ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
9011   if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent())
9012     Status = concepts::ExprRequirement::SS_Dependent;
9013   else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
9014     Status = concepts::ExprRequirement::SS_NoexceptNotMet;
9015   else if (ReturnTypeRequirement.isSubstitutionFailure())
9016     Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure;
9017   else if (ReturnTypeRequirement.isTypeConstraint()) {
9018     // C++2a [expr.prim.req]p1.3.3
9019     //     The immediately-declared constraint ([temp]) of decltype((E)) shall
9020     //     be satisfied.
9021     TemplateParameterList *TPL =
9022         ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
9023     QualType MatchedType =
9024         Context.getReferenceQualifiedType(E).getCanonicalType();
9025     llvm::SmallVector<TemplateArgument, 1> Args;
9026     Args.push_back(TemplateArgument(MatchedType));
9027 
9028     auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));
9029 
9030     TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args);
9031     MultiLevelTemplateArgumentList MLTAL(Param, TAL.asArray(),
9032                                          /*Final=*/false);
9033     MLTAL.addOuterRetainedLevels(TPL->getDepth());
9034     Expr *IDC = Param->getTypeConstraint()->getImmediatelyDeclaredConstraint();
9035     ExprResult Constraint = SubstExpr(IDC, MLTAL);
9036     if (Constraint.isInvalid()) {
9037       Status = concepts::ExprRequirement::SS_ExprSubstitutionFailure;
9038     } else {
9039       SubstitutedConstraintExpr =
9040           cast<ConceptSpecializationExpr>(Constraint.get());
9041       if (!SubstitutedConstraintExpr->isSatisfied())
9042         Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
9043     }
9044   }
9045   return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
9046                                                  ReturnTypeRequirement, Status,
9047                                                  SubstitutedConstraintExpr);
9048 }
9049 
9050 concepts::ExprRequirement *
9051 Sema::BuildExprRequirement(
9052     concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
9053     bool IsSimple, SourceLocation NoexceptLoc,
9054     concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
9055   return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
9056                                                  IsSimple, NoexceptLoc,
9057                                                  ReturnTypeRequirement);
9058 }
9059 
9060 concepts::TypeRequirement *
9061 Sema::BuildTypeRequirement(TypeSourceInfo *Type) {
9062   return new (Context) concepts::TypeRequirement(Type);
9063 }
9064 
9065 concepts::TypeRequirement *
9066 Sema::BuildTypeRequirement(
9067     concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
9068   return new (Context) concepts::TypeRequirement(SubstDiag);
9069 }
9070 
9071 concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) {
9072   return BuildNestedRequirement(Constraint);
9073 }
9074 
9075 concepts::NestedRequirement *
9076 Sema::BuildNestedRequirement(Expr *Constraint) {
9077   ConstraintSatisfaction Satisfaction;
9078   if (!Constraint->isInstantiationDependent() &&
9079       CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
9080                                   Constraint->getSourceRange(), Satisfaction))
9081     return nullptr;
9082   return new (Context) concepts::NestedRequirement(Context, Constraint,
9083                                                    Satisfaction);
9084 }
9085 
9086 concepts::NestedRequirement *
9087 Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,
9088                        const ASTConstraintSatisfaction &Satisfaction) {
9089   return new (Context) concepts::NestedRequirement(
9090       InvalidConstraintEntity,
9091       ASTConstraintSatisfaction::Rebuild(Context, Satisfaction));
9092 }
9093 
9094 RequiresExprBodyDecl *
9095 Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
9096                              ArrayRef<ParmVarDecl *> LocalParameters,
9097                              Scope *BodyScope) {
9098   assert(BodyScope);
9099 
9100   RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext,
9101                                                             RequiresKWLoc);
9102 
9103   PushDeclContext(BodyScope, Body);
9104 
9105   for (ParmVarDecl *Param : LocalParameters) {
9106     if (Param->hasDefaultArg())
9107       // C++2a [expr.prim.req] p4
9108       //     [...] A local parameter of a requires-expression shall not have a
9109       //     default argument. [...]
9110       Diag(Param->getDefaultArgRange().getBegin(),
9111            diag::err_requires_expr_local_parameter_default_argument);
9112     // Ignore default argument and move on
9113 
9114     Param->setDeclContext(Body);
9115     // If this has an identifier, add it to the scope stack.
9116     if (Param->getIdentifier()) {
9117       CheckShadow(BodyScope, Param);
9118       PushOnScopeChains(Param, BodyScope);
9119     }
9120   }
9121   return Body;
9122 }
9123 
9124 void Sema::ActOnFinishRequiresExpr() {
9125   assert(CurContext && "DeclContext imbalance!");
9126   CurContext = CurContext->getLexicalParent();
9127   assert(CurContext && "Popped translation unit!");
9128 }
9129 
9130 ExprResult
9131 Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc,
9132                         RequiresExprBodyDecl *Body,
9133                         ArrayRef<ParmVarDecl *> LocalParameters,
9134                         ArrayRef<concepts::Requirement *> Requirements,
9135                         SourceLocation ClosingBraceLoc) {
9136   auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters,
9137                                   Requirements, ClosingBraceLoc);
9138   if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE))
9139     return ExprError();
9140   return RE;
9141 }
9142