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