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 = dyn_cast<FunctionDecl>(CurContext);
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 = dyn_cast<FunctionDecl>(S.CurContext))
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(dyn_cast<FunctionDecl>(CurContext), Matches);
2835   } else {
2836     // C++1y [expr.new]p22:
2837     //   For a non-placement allocation function, the normal deallocation
2838     //   function lookup is used
2839     //
2840     // Per [expr.delete]p10, this lookup prefers a member operator delete
2841     // without a size_t argument, but prefers a non-member operator delete
2842     // with a size_t where possible (which it always is in this case).
2843     llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2844     UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2845         *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2846         /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2847         &BestDeallocFns);
2848     if (Selected)
2849       Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2850     else {
2851       // If we failed to select an operator, all remaining functions are viable
2852       // but ambiguous.
2853       for (auto Fn : BestDeallocFns)
2854         Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2855     }
2856   }
2857 
2858   // C++ [expr.new]p20:
2859   //   [...] If the lookup finds a single matching deallocation
2860   //   function, that function will be called; otherwise, no
2861   //   deallocation function will be called.
2862   if (Matches.size() == 1) {
2863     OperatorDelete = Matches[0].second;
2864 
2865     // C++1z [expr.new]p23:
2866     //   If the lookup finds a usual deallocation function (3.7.4.2)
2867     //   with a parameter of type std::size_t and that function, considered
2868     //   as a placement deallocation function, would have been
2869     //   selected as a match for the allocation function, the program
2870     //   is ill-formed.
2871     if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2872         isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2873       UsualDeallocFnInfo Info(*this,
2874                               DeclAccessPair::make(OperatorDelete, AS_public));
2875       // Core issue, per mail to core reflector, 2016-10-09:
2876       //   If this is a member operator delete, and there is a corresponding
2877       //   non-sized member operator delete, this isn't /really/ a sized
2878       //   deallocation function, it just happens to have a size_t parameter.
2879       bool IsSizedDelete = Info.HasSizeT;
2880       if (IsSizedDelete && !FoundGlobalDelete) {
2881         auto NonSizedDelete =
2882             resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2883                                         /*WantAlign*/Info.HasAlignValT);
2884         if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2885             NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2886           IsSizedDelete = false;
2887       }
2888 
2889       if (IsSizedDelete) {
2890         SourceRange R = PlaceArgs.empty()
2891                             ? SourceRange()
2892                             : SourceRange(PlaceArgs.front()->getBeginLoc(),
2893                                           PlaceArgs.back()->getEndLoc());
2894         Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2895         if (!OperatorDelete->isImplicit())
2896           Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2897               << DeleteName;
2898       }
2899     }
2900 
2901     CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2902                           Matches[0].first);
2903   } else if (!Matches.empty()) {
2904     // We found multiple suitable operators. Per [expr.new]p20, that means we
2905     // call no 'operator delete' function, but we should at least warn the user.
2906     // FIXME: Suppress this warning if the construction cannot throw.
2907     Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2908       << DeleteName << AllocElemType;
2909 
2910     for (auto &Match : Matches)
2911       Diag(Match.second->getLocation(),
2912            diag::note_member_declared_here) << DeleteName;
2913   }
2914 
2915   return false;
2916 }
2917 
2918 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2919 /// delete. These are:
2920 /// @code
2921 ///   // C++03:
2922 ///   void* operator new(std::size_t) throw(std::bad_alloc);
2923 ///   void* operator new[](std::size_t) throw(std::bad_alloc);
2924 ///   void operator delete(void *) throw();
2925 ///   void operator delete[](void *) throw();
2926 ///   // C++11:
2927 ///   void* operator new(std::size_t);
2928 ///   void* operator new[](std::size_t);
2929 ///   void operator delete(void *) noexcept;
2930 ///   void operator delete[](void *) noexcept;
2931 ///   // C++1y:
2932 ///   void* operator new(std::size_t);
2933 ///   void* operator new[](std::size_t);
2934 ///   void operator delete(void *) noexcept;
2935 ///   void operator delete[](void *) noexcept;
2936 ///   void operator delete(void *, std::size_t) noexcept;
2937 ///   void operator delete[](void *, std::size_t) noexcept;
2938 /// @endcode
2939 /// Note that the placement and nothrow forms of new are *not* implicitly
2940 /// declared. Their use requires including \<new\>.
2941 void Sema::DeclareGlobalNewDelete() {
2942   if (GlobalNewDeleteDeclared)
2943     return;
2944 
2945   // The implicitly declared new and delete operators
2946   // are not supported in OpenCL.
2947   if (getLangOpts().OpenCLCPlusPlus)
2948     return;
2949 
2950   // C++ [basic.std.dynamic]p2:
2951   //   [...] The following allocation and deallocation functions (18.4) are
2952   //   implicitly declared in global scope in each translation unit of a
2953   //   program
2954   //
2955   //     C++03:
2956   //     void* operator new(std::size_t) throw(std::bad_alloc);
2957   //     void* operator new[](std::size_t) throw(std::bad_alloc);
2958   //     void  operator delete(void*) throw();
2959   //     void  operator delete[](void*) throw();
2960   //     C++11:
2961   //     void* operator new(std::size_t);
2962   //     void* operator new[](std::size_t);
2963   //     void  operator delete(void*) noexcept;
2964   //     void  operator delete[](void*) noexcept;
2965   //     C++1y:
2966   //     void* operator new(std::size_t);
2967   //     void* operator new[](std::size_t);
2968   //     void  operator delete(void*) noexcept;
2969   //     void  operator delete[](void*) noexcept;
2970   //     void  operator delete(void*, std::size_t) noexcept;
2971   //     void  operator delete[](void*, std::size_t) noexcept;
2972   //
2973   //   These implicit declarations introduce only the function names operator
2974   //   new, operator new[], operator delete, operator delete[].
2975   //
2976   // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2977   // "std" or "bad_alloc" as necessary to form the exception specification.
2978   // However, we do not make these implicit declarations visible to name
2979   // lookup.
2980   if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2981     // The "std::bad_alloc" class has not yet been declared, so build it
2982     // implicitly.
2983     StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2984                                         getOrCreateStdNamespace(),
2985                                         SourceLocation(), SourceLocation(),
2986                                       &PP.getIdentifierTable().get("bad_alloc"),
2987                                         nullptr);
2988     getStdBadAlloc()->setImplicit(true);
2989   }
2990   if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2991     // The "std::align_val_t" enum class has not yet been declared, so build it
2992     // implicitly.
2993     auto *AlignValT = EnumDecl::Create(
2994         Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2995         &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2996     AlignValT->setIntegerType(Context.getSizeType());
2997     AlignValT->setPromotionType(Context.getSizeType());
2998     AlignValT->setImplicit(true);
2999     StdAlignValT = AlignValT;
3000   }
3001 
3002   GlobalNewDeleteDeclared = true;
3003 
3004   QualType VoidPtr = Context.getPointerType(Context.VoidTy);
3005   QualType SizeT = Context.getSizeType();
3006 
3007   auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3008                                               QualType Return, QualType Param) {
3009     llvm::SmallVector<QualType, 3> Params;
3010     Params.push_back(Param);
3011 
3012     // Create up to four variants of the function (sized/aligned).
3013     bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3014                            (Kind == OO_Delete || Kind == OO_Array_Delete);
3015     bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3016 
3017     int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3018     int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3019     for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3020       if (Sized)
3021         Params.push_back(SizeT);
3022 
3023       for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3024         if (Aligned)
3025           Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
3026 
3027         DeclareGlobalAllocationFunction(
3028             Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3029 
3030         if (Aligned)
3031           Params.pop_back();
3032       }
3033     }
3034   };
3035 
3036   DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3037   DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3038   DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3039   DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3040 }
3041 
3042 /// DeclareGlobalAllocationFunction - Declares a single implicit global
3043 /// allocation function if it doesn't already exist.
3044 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
3045                                            QualType Return,
3046                                            ArrayRef<QualType> Params) {
3047   DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
3048 
3049   // Check if this function is already declared.
3050   DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3051   for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3052        Alloc != AllocEnd; ++Alloc) {
3053     // Only look at non-template functions, as it is the predefined,
3054     // non-templated allocation function we are trying to declare here.
3055     if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3056       if (Func->getNumParams() == Params.size()) {
3057         llvm::SmallVector<QualType, 3> FuncParams;
3058         for (auto *P : Func->parameters())
3059           FuncParams.push_back(
3060               Context.getCanonicalType(P->getType().getUnqualifiedType()));
3061         if (llvm::makeArrayRef(FuncParams) == Params) {
3062           // Make the function visible to name lookup, even if we found it in
3063           // an unimported module. It either is an implicitly-declared global
3064           // allocation function, or is suppressing that function.
3065           Func->setVisibleDespiteOwningModule();
3066           return;
3067         }
3068       }
3069     }
3070   }
3071 
3072   FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
3073       /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3074 
3075   QualType BadAllocType;
3076   bool HasBadAllocExceptionSpec
3077     = (Name.getCXXOverloadedOperator() == OO_New ||
3078        Name.getCXXOverloadedOperator() == OO_Array_New);
3079   if (HasBadAllocExceptionSpec) {
3080     if (!getLangOpts().CPlusPlus11) {
3081       BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
3082       assert(StdBadAlloc && "Must have std::bad_alloc declared");
3083       EPI.ExceptionSpec.Type = EST_Dynamic;
3084       EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
3085     }
3086     if (getLangOpts().NewInfallible) {
3087       EPI.ExceptionSpec.Type = EST_DynamicNone;
3088     }
3089   } else {
3090     EPI.ExceptionSpec =
3091         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
3092   }
3093 
3094   auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3095     QualType FnType = Context.getFunctionType(Return, Params, EPI);
3096     FunctionDecl *Alloc = FunctionDecl::Create(
3097         Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3098         /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3099         true);
3100     Alloc->setImplicit();
3101     // Global allocation functions should always be visible.
3102     Alloc->setVisibleDespiteOwningModule();
3103 
3104     if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible)
3105       Alloc->addAttr(
3106           ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3107 
3108     Alloc->addAttr(VisibilityAttr::CreateImplicit(
3109         Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
3110                      ? VisibilityAttr::Hidden
3111                      : VisibilityAttr::Default));
3112 
3113     llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
3114     for (QualType T : Params) {
3115       ParamDecls.push_back(ParmVarDecl::Create(
3116           Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3117           /*TInfo=*/nullptr, SC_None, nullptr));
3118       ParamDecls.back()->setImplicit();
3119     }
3120     Alloc->setParams(ParamDecls);
3121     if (ExtraAttr)
3122       Alloc->addAttr(ExtraAttr);
3123     AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc);
3124     Context.getTranslationUnitDecl()->addDecl(Alloc);
3125     IdResolver.tryAddTopLevelDecl(Alloc, Name);
3126   };
3127 
3128   if (!LangOpts.CUDA)
3129     CreateAllocationFunctionDecl(nullptr);
3130   else {
3131     // Host and device get their own declaration so each can be
3132     // defined or re-declared independently.
3133     CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3134     CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3135   }
3136 }
3137 
3138 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
3139                                                   bool CanProvideSize,
3140                                                   bool Overaligned,
3141                                                   DeclarationName Name) {
3142   DeclareGlobalNewDelete();
3143 
3144   LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3145   LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
3146 
3147   // FIXME: It's possible for this to result in ambiguity, through a
3148   // user-declared variadic operator delete or the enable_if attribute. We
3149   // should probably not consider those cases to be usual deallocation
3150   // functions. But for now we just make an arbitrary choice in that case.
3151   auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3152                                             Overaligned);
3153   assert(Result.FD && "operator delete missing from global scope?");
3154   return Result.FD;
3155 }
3156 
3157 FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
3158                                                           CXXRecordDecl *RD) {
3159   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
3160 
3161   FunctionDecl *OperatorDelete = nullptr;
3162   if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3163     return nullptr;
3164   if (OperatorDelete)
3165     return OperatorDelete;
3166 
3167   // If there's no class-specific operator delete, look up the global
3168   // non-array delete.
3169   return FindUsualDeallocationFunction(
3170       Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
3171       Name);
3172 }
3173 
3174 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3175                                     DeclarationName Name,
3176                                     FunctionDecl *&Operator, bool Diagnose) {
3177   LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3178   // Try to find operator delete/operator delete[] in class scope.
3179   LookupQualifiedName(Found, RD);
3180 
3181   if (Found.isAmbiguous())
3182     return true;
3183 
3184   Found.suppressDiagnostics();
3185 
3186   bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3187 
3188   // C++17 [expr.delete]p10:
3189   //   If the deallocation functions have class scope, the one without a
3190   //   parameter of type std::size_t is selected.
3191   llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
3192   resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
3193                               /*WantAlign*/ Overaligned, &Matches);
3194 
3195   // If we could find an overload, use it.
3196   if (Matches.size() == 1) {
3197     Operator = cast<CXXMethodDecl>(Matches[0].FD);
3198 
3199     // FIXME: DiagnoseUseOfDecl?
3200     if (Operator->isDeleted()) {
3201       if (Diagnose) {
3202         Diag(StartLoc, diag::err_deleted_function_use);
3203         NoteDeletedFunction(Operator);
3204       }
3205       return true;
3206     }
3207 
3208     if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3209                               Matches[0].Found, Diagnose) == AR_inaccessible)
3210       return true;
3211 
3212     return false;
3213   }
3214 
3215   // We found multiple suitable operators; complain about the ambiguity.
3216   // FIXME: The standard doesn't say to do this; it appears that the intent
3217   // is that this should never happen.
3218   if (!Matches.empty()) {
3219     if (Diagnose) {
3220       Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3221         << Name << RD;
3222       for (auto &Match : Matches)
3223         Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3224     }
3225     return true;
3226   }
3227 
3228   // We did find operator delete/operator delete[] declarations, but
3229   // none of them were suitable.
3230   if (!Found.empty()) {
3231     if (Diagnose) {
3232       Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3233         << Name << RD;
3234 
3235       for (NamedDecl *D : Found)
3236         Diag(D->getUnderlyingDecl()->getLocation(),
3237              diag::note_member_declared_here) << Name;
3238     }
3239     return true;
3240   }
3241 
3242   Operator = nullptr;
3243   return false;
3244 }
3245 
3246 namespace {
3247 /// Checks whether delete-expression, and new-expression used for
3248 ///  initializing deletee have the same array form.
3249 class MismatchingNewDeleteDetector {
3250 public:
3251   enum MismatchResult {
3252     /// Indicates that there is no mismatch or a mismatch cannot be proven.
3253     NoMismatch,
3254     /// Indicates that variable is initialized with mismatching form of \a new.
3255     VarInitMismatches,
3256     /// Indicates that member is initialized with mismatching form of \a new.
3257     MemberInitMismatches,
3258     /// Indicates that 1 or more constructors' definitions could not been
3259     /// analyzed, and they will be checked again at the end of translation unit.
3260     AnalyzeLater
3261   };
3262 
3263   /// \param EndOfTU True, if this is the final analysis at the end of
3264   /// translation unit. False, if this is the initial analysis at the point
3265   /// delete-expression was encountered.
3266   explicit MismatchingNewDeleteDetector(bool EndOfTU)
3267       : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3268         HasUndefinedConstructors(false) {}
3269 
3270   /// Checks whether pointee of a delete-expression is initialized with
3271   /// matching form of new-expression.
3272   ///
3273   /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3274   /// point where delete-expression is encountered, then a warning will be
3275   /// issued immediately. If return value is \c AnalyzeLater at the point where
3276   /// delete-expression is seen, then member will be analyzed at the end of
3277   /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3278   /// couldn't be analyzed. If at least one constructor initializes the member
3279   /// with matching type of new, the return value is \c NoMismatch.
3280   MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3281   /// Analyzes a class member.
3282   /// \param Field Class member to analyze.
3283   /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3284   /// for deleting the \p Field.
3285   MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3286   FieldDecl *Field;
3287   /// List of mismatching new-expressions used for initialization of the pointee
3288   llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3289   /// Indicates whether delete-expression was in array form.
3290   bool IsArrayForm;
3291 
3292 private:
3293   const bool EndOfTU;
3294   /// Indicates that there is at least one constructor without body.
3295   bool HasUndefinedConstructors;
3296   /// Returns \c CXXNewExpr from given initialization expression.
3297   /// \param E Expression used for initializing pointee in delete-expression.
3298   /// E can be a single-element \c InitListExpr consisting of new-expression.
3299   const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3300   /// Returns whether member is initialized with mismatching form of
3301   /// \c new either by the member initializer or in-class initialization.
3302   ///
3303   /// If bodies of all constructors are not visible at the end of translation
3304   /// unit or at least one constructor initializes member with the matching
3305   /// form of \c new, mismatch cannot be proven, and this function will return
3306   /// \c NoMismatch.
3307   MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3308   /// Returns whether variable is initialized with mismatching form of
3309   /// \c new.
3310   ///
3311   /// If variable is initialized with matching form of \c new or variable is not
3312   /// initialized with a \c new expression, this function will return true.
3313   /// If variable is initialized with mismatching form of \c new, returns false.
3314   /// \param D Variable to analyze.
3315   bool hasMatchingVarInit(const DeclRefExpr *D);
3316   /// Checks whether the constructor initializes pointee with mismatching
3317   /// form of \c new.
3318   ///
3319   /// Returns true, if member is initialized with matching form of \c new in
3320   /// member initializer list. Returns false, if member is initialized with the
3321   /// matching form of \c new in this constructor's initializer or given
3322   /// constructor isn't defined at the point where delete-expression is seen, or
3323   /// member isn't initialized by the constructor.
3324   bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3325   /// Checks whether member is initialized with matching form of
3326   /// \c new in member initializer list.
3327   bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3328   /// Checks whether member is initialized with mismatching form of \c new by
3329   /// in-class initializer.
3330   MismatchResult analyzeInClassInitializer();
3331 };
3332 }
3333 
3334 MismatchingNewDeleteDetector::MismatchResult
3335 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3336   NewExprs.clear();
3337   assert(DE && "Expected delete-expression");
3338   IsArrayForm = DE->isArrayForm();
3339   const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3340   if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3341     return analyzeMemberExpr(ME);
3342   } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3343     if (!hasMatchingVarInit(D))
3344       return VarInitMismatches;
3345   }
3346   return NoMismatch;
3347 }
3348 
3349 const CXXNewExpr *
3350 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3351   assert(E != nullptr && "Expected a valid initializer expression");
3352   E = E->IgnoreParenImpCasts();
3353   if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3354     if (ILE->getNumInits() == 1)
3355       E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3356   }
3357 
3358   return dyn_cast_or_null<const CXXNewExpr>(E);
3359 }
3360 
3361 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3362     const CXXCtorInitializer *CI) {
3363   const CXXNewExpr *NE = nullptr;
3364   if (Field == CI->getMember() &&
3365       (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3366     if (NE->isArray() == IsArrayForm)
3367       return true;
3368     else
3369       NewExprs.push_back(NE);
3370   }
3371   return false;
3372 }
3373 
3374 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3375     const CXXConstructorDecl *CD) {
3376   if (CD->isImplicit())
3377     return false;
3378   const FunctionDecl *Definition = CD;
3379   if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3380     HasUndefinedConstructors = true;
3381     return EndOfTU;
3382   }
3383   for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3384     if (hasMatchingNewInCtorInit(CI))
3385       return true;
3386   }
3387   return false;
3388 }
3389 
3390 MismatchingNewDeleteDetector::MismatchResult
3391 MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3392   assert(Field != nullptr && "This should be called only for members");
3393   const Expr *InitExpr = Field->getInClassInitializer();
3394   if (!InitExpr)
3395     return EndOfTU ? NoMismatch : AnalyzeLater;
3396   if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3397     if (NE->isArray() != IsArrayForm) {
3398       NewExprs.push_back(NE);
3399       return MemberInitMismatches;
3400     }
3401   }
3402   return NoMismatch;
3403 }
3404 
3405 MismatchingNewDeleteDetector::MismatchResult
3406 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3407                                            bool DeleteWasArrayForm) {
3408   assert(Field != nullptr && "Analysis requires a valid class member.");
3409   this->Field = Field;
3410   IsArrayForm = DeleteWasArrayForm;
3411   const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3412   for (const auto *CD : RD->ctors()) {
3413     if (hasMatchingNewInCtor(CD))
3414       return NoMismatch;
3415   }
3416   if (HasUndefinedConstructors)
3417     return EndOfTU ? NoMismatch : AnalyzeLater;
3418   if (!NewExprs.empty())
3419     return MemberInitMismatches;
3420   return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3421                                         : NoMismatch;
3422 }
3423 
3424 MismatchingNewDeleteDetector::MismatchResult
3425 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3426   assert(ME != nullptr && "Expected a member expression");
3427   if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3428     return analyzeField(F, IsArrayForm);
3429   return NoMismatch;
3430 }
3431 
3432 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3433   const CXXNewExpr *NE = nullptr;
3434   if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3435     if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3436         NE->isArray() != IsArrayForm) {
3437       NewExprs.push_back(NE);
3438     }
3439   }
3440   return NewExprs.empty();
3441 }
3442 
3443 static void
3444 DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3445                             const MismatchingNewDeleteDetector &Detector) {
3446   SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3447   FixItHint H;
3448   if (!Detector.IsArrayForm)
3449     H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3450   else {
3451     SourceLocation RSquare = Lexer::findLocationAfterToken(
3452         DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3453         SemaRef.getLangOpts(), true);
3454     if (RSquare.isValid())
3455       H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3456   }
3457   SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3458       << Detector.IsArrayForm << H;
3459 
3460   for (const auto *NE : Detector.NewExprs)
3461     SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3462         << Detector.IsArrayForm;
3463 }
3464 
3465 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3466   if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3467     return;
3468   MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3469   switch (Detector.analyzeDeleteExpr(DE)) {
3470   case MismatchingNewDeleteDetector::VarInitMismatches:
3471   case MismatchingNewDeleteDetector::MemberInitMismatches: {
3472     DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3473     break;
3474   }
3475   case MismatchingNewDeleteDetector::AnalyzeLater: {
3476     DeleteExprs[Detector.Field].push_back(
3477         std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3478     break;
3479   }
3480   case MismatchingNewDeleteDetector::NoMismatch:
3481     break;
3482   }
3483 }
3484 
3485 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3486                                      bool DeleteWasArrayForm) {
3487   MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3488   switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3489   case MismatchingNewDeleteDetector::VarInitMismatches:
3490     llvm_unreachable("This analysis should have been done for class members.");
3491   case MismatchingNewDeleteDetector::AnalyzeLater:
3492     llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3493                      "translation unit.");
3494   case MismatchingNewDeleteDetector::MemberInitMismatches:
3495     DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3496     break;
3497   case MismatchingNewDeleteDetector::NoMismatch:
3498     break;
3499   }
3500 }
3501 
3502 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3503 /// @code ::delete ptr; @endcode
3504 /// or
3505 /// @code delete [] ptr; @endcode
3506 ExprResult
3507 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3508                      bool ArrayForm, Expr *ExE) {
3509   // C++ [expr.delete]p1:
3510   //   The operand shall have a pointer type, or a class type having a single
3511   //   non-explicit conversion function to a pointer type. The result has type
3512   //   void.
3513   //
3514   // DR599 amends "pointer type" to "pointer to object type" in both cases.
3515 
3516   ExprResult Ex = ExE;
3517   FunctionDecl *OperatorDelete = nullptr;
3518   bool ArrayFormAsWritten = ArrayForm;
3519   bool UsualArrayDeleteWantsSize = false;
3520 
3521   if (!Ex.get()->isTypeDependent()) {
3522     // Perform lvalue-to-rvalue cast, if needed.
3523     Ex = DefaultLvalueConversion(Ex.get());
3524     if (Ex.isInvalid())
3525       return ExprError();
3526 
3527     QualType Type = Ex.get()->getType();
3528 
3529     class DeleteConverter : public ContextualImplicitConverter {
3530     public:
3531       DeleteConverter() : ContextualImplicitConverter(false, true) {}
3532 
3533       bool match(QualType ConvType) override {
3534         // FIXME: If we have an operator T* and an operator void*, we must pick
3535         // the operator T*.
3536         if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3537           if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3538             return true;
3539         return false;
3540       }
3541 
3542       SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3543                                             QualType T) override {
3544         return S.Diag(Loc, diag::err_delete_operand) << T;
3545       }
3546 
3547       SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3548                                                QualType T) override {
3549         return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3550       }
3551 
3552       SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3553                                                  QualType T,
3554                                                  QualType ConvTy) override {
3555         return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3556       }
3557 
3558       SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3559                                              QualType ConvTy) override {
3560         return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3561           << ConvTy;
3562       }
3563 
3564       SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3565                                               QualType T) override {
3566         return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3567       }
3568 
3569       SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3570                                           QualType ConvTy) override {
3571         return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3572           << ConvTy;
3573       }
3574 
3575       SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3576                                                QualType T,
3577                                                QualType ConvTy) override {
3578         llvm_unreachable("conversion functions are permitted");
3579       }
3580     } Converter;
3581 
3582     Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3583     if (Ex.isInvalid())
3584       return ExprError();
3585     Type = Ex.get()->getType();
3586     if (!Converter.match(Type))
3587       // FIXME: PerformContextualImplicitConversion should return ExprError
3588       //        itself in this case.
3589       return ExprError();
3590 
3591     QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3592     QualType PointeeElem = Context.getBaseElementType(Pointee);
3593 
3594     if (Pointee.getAddressSpace() != LangAS::Default &&
3595         !getLangOpts().OpenCLCPlusPlus)
3596       return Diag(Ex.get()->getBeginLoc(),
3597                   diag::err_address_space_qualified_delete)
3598              << Pointee.getUnqualifiedType()
3599              << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3600 
3601     CXXRecordDecl *PointeeRD = nullptr;
3602     if (Pointee->isVoidType() && !isSFINAEContext()) {
3603       // The C++ standard bans deleting a pointer to a non-object type, which
3604       // effectively bans deletion of "void*". However, most compilers support
3605       // this, so we treat it as a warning unless we're in a SFINAE context.
3606       Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3607         << Type << Ex.get()->getSourceRange();
3608     } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3609                Pointee->isSizelessType()) {
3610       return ExprError(Diag(StartLoc, diag::err_delete_operand)
3611         << Type << Ex.get()->getSourceRange());
3612     } else if (!Pointee->isDependentType()) {
3613       // FIXME: This can result in errors if the definition was imported from a
3614       // module but is hidden.
3615       if (!RequireCompleteType(StartLoc, Pointee,
3616                                diag::warn_delete_incomplete, Ex.get())) {
3617         if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3618           PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3619       }
3620     }
3621 
3622     if (Pointee->isArrayType() && !ArrayForm) {
3623       Diag(StartLoc, diag::warn_delete_array_type)
3624           << Type << Ex.get()->getSourceRange()
3625           << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3626       ArrayForm = true;
3627     }
3628 
3629     DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3630                                       ArrayForm ? OO_Array_Delete : OO_Delete);
3631 
3632     if (PointeeRD) {
3633       if (!UseGlobal &&
3634           FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3635                                    OperatorDelete))
3636         return ExprError();
3637 
3638       // If we're allocating an array of records, check whether the
3639       // usual operator delete[] has a size_t parameter.
3640       if (ArrayForm) {
3641         // If the user specifically asked to use the global allocator,
3642         // we'll need to do the lookup into the class.
3643         if (UseGlobal)
3644           UsualArrayDeleteWantsSize =
3645             doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3646 
3647         // Otherwise, the usual operator delete[] should be the
3648         // function we just found.
3649         else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3650           UsualArrayDeleteWantsSize =
3651             UsualDeallocFnInfo(*this,
3652                                DeclAccessPair::make(OperatorDelete, AS_public))
3653               .HasSizeT;
3654       }
3655 
3656       if (!PointeeRD->hasIrrelevantDestructor())
3657         if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3658           MarkFunctionReferenced(StartLoc,
3659                                     const_cast<CXXDestructorDecl*>(Dtor));
3660           if (DiagnoseUseOfDecl(Dtor, StartLoc))
3661             return ExprError();
3662         }
3663 
3664       CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3665                            /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3666                            /*WarnOnNonAbstractTypes=*/!ArrayForm,
3667                            SourceLocation());
3668     }
3669 
3670     if (!OperatorDelete) {
3671       if (getLangOpts().OpenCLCPlusPlus) {
3672         Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3673         return ExprError();
3674       }
3675 
3676       bool IsComplete = isCompleteType(StartLoc, Pointee);
3677       bool CanProvideSize =
3678           IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3679                          Pointee.isDestructedType());
3680       bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3681 
3682       // Look for a global declaration.
3683       OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3684                                                      Overaligned, DeleteName);
3685     }
3686 
3687     MarkFunctionReferenced(StartLoc, OperatorDelete);
3688 
3689     // Check access and ambiguity of destructor if we're going to call it.
3690     // Note that this is required even for a virtual delete.
3691     bool IsVirtualDelete = false;
3692     if (PointeeRD) {
3693       if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3694         CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3695                               PDiag(diag::err_access_dtor) << PointeeElem);
3696         IsVirtualDelete = Dtor->isVirtual();
3697       }
3698     }
3699 
3700     DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3701 
3702     // Convert the operand to the type of the first parameter of operator
3703     // delete. This is only necessary if we selected a destroying operator
3704     // delete that we are going to call (non-virtually); converting to void*
3705     // is trivial and left to AST consumers to handle.
3706     QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3707     if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3708       Qualifiers Qs = Pointee.getQualifiers();
3709       if (Qs.hasCVRQualifiers()) {
3710         // Qualifiers are irrelevant to this conversion; we're only looking
3711         // for access and ambiguity.
3712         Qs.removeCVRQualifiers();
3713         QualType Unqual = Context.getPointerType(
3714             Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3715         Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3716       }
3717       Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3718       if (Ex.isInvalid())
3719         return ExprError();
3720     }
3721   }
3722 
3723   CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3724       Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3725       UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3726   AnalyzeDeleteExprMismatch(Result);
3727   return Result;
3728 }
3729 
3730 static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3731                                             bool IsDelete,
3732                                             FunctionDecl *&Operator) {
3733 
3734   DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3735       IsDelete ? OO_Delete : OO_New);
3736 
3737   LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3738   S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3739   assert(!R.empty() && "implicitly declared allocation functions not found");
3740   assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3741 
3742   // We do our own custom access checks below.
3743   R.suppressDiagnostics();
3744 
3745   SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3746   OverloadCandidateSet Candidates(R.getNameLoc(),
3747                                   OverloadCandidateSet::CSK_Normal);
3748   for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3749        FnOvl != FnOvlEnd; ++FnOvl) {
3750     // Even member operator new/delete are implicitly treated as
3751     // static, so don't use AddMemberCandidate.
3752     NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3753 
3754     if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3755       S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3756                                      /*ExplicitTemplateArgs=*/nullptr, Args,
3757                                      Candidates,
3758                                      /*SuppressUserConversions=*/false);
3759       continue;
3760     }
3761 
3762     FunctionDecl *Fn = cast<FunctionDecl>(D);
3763     S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3764                            /*SuppressUserConversions=*/false);
3765   }
3766 
3767   SourceRange Range = TheCall->getSourceRange();
3768 
3769   // Do the resolution.
3770   OverloadCandidateSet::iterator Best;
3771   switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3772   case OR_Success: {
3773     // Got one!
3774     FunctionDecl *FnDecl = Best->Function;
3775     assert(R.getNamingClass() == nullptr &&
3776            "class members should not be considered");
3777 
3778     if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3779       S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3780           << (IsDelete ? 1 : 0) << Range;
3781       S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3782           << R.getLookupName() << FnDecl->getSourceRange();
3783       return true;
3784     }
3785 
3786     Operator = FnDecl;
3787     return false;
3788   }
3789 
3790   case OR_No_Viable_Function:
3791     Candidates.NoteCandidates(
3792         PartialDiagnosticAt(R.getNameLoc(),
3793                             S.PDiag(diag::err_ovl_no_viable_function_in_call)
3794                                 << R.getLookupName() << Range),
3795         S, OCD_AllCandidates, Args);
3796     return true;
3797 
3798   case OR_Ambiguous:
3799     Candidates.NoteCandidates(
3800         PartialDiagnosticAt(R.getNameLoc(),
3801                             S.PDiag(diag::err_ovl_ambiguous_call)
3802                                 << R.getLookupName() << Range),
3803         S, OCD_AmbiguousCandidates, Args);
3804     return true;
3805 
3806   case OR_Deleted: {
3807     Candidates.NoteCandidates(
3808         PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3809                                                 << R.getLookupName() << Range),
3810         S, OCD_AllCandidates, Args);
3811     return true;
3812   }
3813   }
3814   llvm_unreachable("Unreachable, bad result from BestViableFunction");
3815 }
3816 
3817 ExprResult
3818 Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3819                                              bool IsDelete) {
3820   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3821   if (!getLangOpts().CPlusPlus) {
3822     Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3823         << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3824         << "C++";
3825     return ExprError();
3826   }
3827   // CodeGen assumes it can find the global new and delete to call,
3828   // so ensure that they are declared.
3829   DeclareGlobalNewDelete();
3830 
3831   FunctionDecl *OperatorNewOrDelete = nullptr;
3832   if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3833                                       OperatorNewOrDelete))
3834     return ExprError();
3835   assert(OperatorNewOrDelete && "should be found");
3836 
3837   DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3838   MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3839 
3840   TheCall->setType(OperatorNewOrDelete->getReturnType());
3841   for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3842     QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3843     InitializedEntity Entity =
3844         InitializedEntity::InitializeParameter(Context, ParamTy, false);
3845     ExprResult Arg = PerformCopyInitialization(
3846         Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3847     if (Arg.isInvalid())
3848       return ExprError();
3849     TheCall->setArg(i, Arg.get());
3850   }
3851   auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3852   assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3853          "Callee expected to be implicit cast to a builtin function pointer");
3854   Callee->setType(OperatorNewOrDelete->getType());
3855 
3856   return TheCallResult;
3857 }
3858 
3859 void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3860                                 bool IsDelete, bool CallCanBeVirtual,
3861                                 bool WarnOnNonAbstractTypes,
3862                                 SourceLocation DtorLoc) {
3863   if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3864     return;
3865 
3866   // C++ [expr.delete]p3:
3867   //   In the first alternative (delete object), if the static type of the
3868   //   object to be deleted is different from its dynamic type, the static
3869   //   type shall be a base class of the dynamic type of the object to be
3870   //   deleted and the static type shall have a virtual destructor or the
3871   //   behavior is undefined.
3872   //
3873   const CXXRecordDecl *PointeeRD = dtor->getParent();
3874   // Note: a final class cannot be derived from, no issue there
3875   if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3876     return;
3877 
3878   // If the superclass is in a system header, there's nothing that can be done.
3879   // The `delete` (where we emit the warning) can be in a system header,
3880   // what matters for this warning is where the deleted type is defined.
3881   if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3882     return;
3883 
3884   QualType ClassType = dtor->getThisType()->getPointeeType();
3885   if (PointeeRD->isAbstract()) {
3886     // If the class is abstract, we warn by default, because we're
3887     // sure the code has undefined behavior.
3888     Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3889                                                            << ClassType;
3890   } else if (WarnOnNonAbstractTypes) {
3891     // Otherwise, if this is not an array delete, it's a bit suspect,
3892     // but not necessarily wrong.
3893     Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3894                                                   << ClassType;
3895   }
3896   if (!IsDelete) {
3897     std::string TypeStr;
3898     ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3899     Diag(DtorLoc, diag::note_delete_non_virtual)
3900         << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3901   }
3902 }
3903 
3904 Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3905                                                    SourceLocation StmtLoc,
3906                                                    ConditionKind CK) {
3907   ExprResult E =
3908       CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3909   if (E.isInvalid())
3910     return ConditionError();
3911   return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3912                          CK == ConditionKind::ConstexprIf);
3913 }
3914 
3915 /// Check the use of the given variable as a C++ condition in an if,
3916 /// while, do-while, or switch statement.
3917 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3918                                         SourceLocation StmtLoc,
3919                                         ConditionKind CK) {
3920   if (ConditionVar->isInvalidDecl())
3921     return ExprError();
3922 
3923   QualType T = ConditionVar->getType();
3924 
3925   // C++ [stmt.select]p2:
3926   //   The declarator shall not specify a function or an array.
3927   if (T->isFunctionType())
3928     return ExprError(Diag(ConditionVar->getLocation(),
3929                           diag::err_invalid_use_of_function_type)
3930                        << ConditionVar->getSourceRange());
3931   else if (T->isArrayType())
3932     return ExprError(Diag(ConditionVar->getLocation(),
3933                           diag::err_invalid_use_of_array_type)
3934                      << ConditionVar->getSourceRange());
3935 
3936   ExprResult Condition = BuildDeclRefExpr(
3937       ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
3938       ConditionVar->getLocation());
3939 
3940   switch (CK) {
3941   case ConditionKind::Boolean:
3942     return CheckBooleanCondition(StmtLoc, Condition.get());
3943 
3944   case ConditionKind::ConstexprIf:
3945     return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3946 
3947   case ConditionKind::Switch:
3948     return CheckSwitchCondition(StmtLoc, Condition.get());
3949   }
3950 
3951   llvm_unreachable("unexpected condition kind");
3952 }
3953 
3954 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3955 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3956   // C++11 6.4p4:
3957   // The value of a condition that is an initialized declaration in a statement
3958   // other than a switch statement is the value of the declared variable
3959   // implicitly converted to type bool. If that conversion is ill-formed, the
3960   // program is ill-formed.
3961   // The value of a condition that is an expression is the value of the
3962   // expression, implicitly converted to bool.
3963   //
3964   // C++2b 8.5.2p2
3965   // If the if statement is of the form if constexpr, the value of the condition
3966   // is contextually converted to bool and the converted expression shall be
3967   // a constant expression.
3968   //
3969 
3970   ExprResult E = PerformContextuallyConvertToBool(CondExpr);
3971   if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
3972     return E;
3973 
3974   // FIXME: Return this value to the caller so they don't need to recompute it.
3975   llvm::APSInt Cond;
3976   E = VerifyIntegerConstantExpression(
3977       E.get(), &Cond,
3978       diag::err_constexpr_if_condition_expression_is_not_constant);
3979   return E;
3980 }
3981 
3982 /// Helper function to determine whether this is the (deprecated) C++
3983 /// conversion from a string literal to a pointer to non-const char or
3984 /// non-const wchar_t (for narrow and wide string literals,
3985 /// respectively).
3986 bool
3987 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3988   // Look inside the implicit cast, if it exists.
3989   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3990     From = Cast->getSubExpr();
3991 
3992   // A string literal (2.13.4) that is not a wide string literal can
3993   // be converted to an rvalue of type "pointer to char"; a wide
3994   // string literal can be converted to an rvalue of type "pointer
3995   // to wchar_t" (C++ 4.2p2).
3996   if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3997     if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3998       if (const BuiltinType *ToPointeeType
3999           = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4000         // This conversion is considered only when there is an
4001         // explicit appropriate pointer target type (C++ 4.2p2).
4002         if (!ToPtrType->getPointeeType().hasQualifiers()) {
4003           switch (StrLit->getKind()) {
4004             case StringLiteral::UTF8:
4005             case StringLiteral::UTF16:
4006             case StringLiteral::UTF32:
4007               // We don't allow UTF literals to be implicitly converted
4008               break;
4009             case StringLiteral::Ascii:
4010               return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4011                       ToPointeeType->getKind() == BuiltinType::Char_S);
4012             case StringLiteral::Wide:
4013               return Context.typesAreCompatible(Context.getWideCharType(),
4014                                                 QualType(ToPointeeType, 0));
4015           }
4016         }
4017       }
4018 
4019   return false;
4020 }
4021 
4022 static ExprResult BuildCXXCastArgument(Sema &S,
4023                                        SourceLocation CastLoc,
4024                                        QualType Ty,
4025                                        CastKind Kind,
4026                                        CXXMethodDecl *Method,
4027                                        DeclAccessPair FoundDecl,
4028                                        bool HadMultipleCandidates,
4029                                        Expr *From) {
4030   switch (Kind) {
4031   default: llvm_unreachable("Unhandled cast kind!");
4032   case CK_ConstructorConversion: {
4033     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4034     SmallVector<Expr*, 8> ConstructorArgs;
4035 
4036     if (S.RequireNonAbstractType(CastLoc, Ty,
4037                                  diag::err_allocation_of_abstract_type))
4038       return ExprError();
4039 
4040     if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4041                                   ConstructorArgs))
4042       return ExprError();
4043 
4044     S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4045                              InitializedEntity::InitializeTemporary(Ty));
4046     if (S.DiagnoseUseOfDecl(Method, CastLoc))
4047       return ExprError();
4048 
4049     ExprResult Result = S.BuildCXXConstructExpr(
4050         CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4051         ConstructorArgs, HadMultipleCandidates,
4052         /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4053         CXXConstructExpr::CK_Complete, SourceRange());
4054     if (Result.isInvalid())
4055       return ExprError();
4056 
4057     return S.MaybeBindToTemporary(Result.getAs<Expr>());
4058   }
4059 
4060   case CK_UserDefinedConversion: {
4061     assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4062 
4063     S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4064     if (S.DiagnoseUseOfDecl(Method, CastLoc))
4065       return ExprError();
4066 
4067     // Create an implicit call expr that calls it.
4068     CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4069     ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4070                                                  HadMultipleCandidates);
4071     if (Result.isInvalid())
4072       return ExprError();
4073     // Record usage of conversion in an implicit cast.
4074     Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4075                                       CK_UserDefinedConversion, Result.get(),
4076                                       nullptr, Result.get()->getValueKind(),
4077                                       S.CurFPFeatureOverrides());
4078 
4079     return S.MaybeBindToTemporary(Result.get());
4080   }
4081   }
4082 }
4083 
4084 /// PerformImplicitConversion - Perform an implicit conversion of the
4085 /// expression From to the type ToType using the pre-computed implicit
4086 /// conversion sequence ICS. Returns the converted
4087 /// expression. Action is the kind of conversion we're performing,
4088 /// used in the error message.
4089 ExprResult
4090 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4091                                 const ImplicitConversionSequence &ICS,
4092                                 AssignmentAction Action,
4093                                 CheckedConversionKind CCK) {
4094   // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4095   if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
4096     return From;
4097 
4098   switch (ICS.getKind()) {
4099   case ImplicitConversionSequence::StandardConversion: {
4100     ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4101                                                Action, CCK);
4102     if (Res.isInvalid())
4103       return ExprError();
4104     From = Res.get();
4105     break;
4106   }
4107 
4108   case ImplicitConversionSequence::UserDefinedConversion: {
4109 
4110       FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
4111       CastKind CastKind;
4112       QualType BeforeToType;
4113       assert(FD && "no conversion function for user-defined conversion seq");
4114       if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4115         CastKind = CK_UserDefinedConversion;
4116 
4117         // If the user-defined conversion is specified by a conversion function,
4118         // the initial standard conversion sequence converts the source type to
4119         // the implicit object parameter of the conversion function.
4120         BeforeToType = Context.getTagDeclType(Conv->getParent());
4121       } else {
4122         const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4123         CastKind = CK_ConstructorConversion;
4124         // Do no conversion if dealing with ... for the first conversion.
4125         if (!ICS.UserDefined.EllipsisConversion) {
4126           // If the user-defined conversion is specified by a constructor, the
4127           // initial standard conversion sequence converts the source type to
4128           // the type required by the argument of the constructor
4129           BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4130         }
4131       }
4132       // Watch out for ellipsis conversion.
4133       if (!ICS.UserDefined.EllipsisConversion) {
4134         ExprResult Res =
4135           PerformImplicitConversion(From, BeforeToType,
4136                                     ICS.UserDefined.Before, AA_Converting,
4137                                     CCK);
4138         if (Res.isInvalid())
4139           return ExprError();
4140         From = Res.get();
4141       }
4142 
4143       ExprResult CastArg = BuildCXXCastArgument(
4144           *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4145           cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4146           ICS.UserDefined.HadMultipleCandidates, From);
4147 
4148       if (CastArg.isInvalid())
4149         return ExprError();
4150 
4151       From = CastArg.get();
4152 
4153       // C++ [over.match.oper]p7:
4154       //   [...] the second standard conversion sequence of a user-defined
4155       //   conversion sequence is not applied.
4156       if (CCK == CCK_ForBuiltinOverloadedOp)
4157         return From;
4158 
4159       return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4160                                        AA_Converting, CCK);
4161   }
4162 
4163   case ImplicitConversionSequence::AmbiguousConversion:
4164     ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4165                           PDiag(diag::err_typecheck_ambiguous_condition)
4166                             << From->getSourceRange());
4167     return ExprError();
4168 
4169   case ImplicitConversionSequence::EllipsisConversion:
4170     llvm_unreachable("Cannot perform an ellipsis conversion");
4171 
4172   case ImplicitConversionSequence::BadConversion:
4173     Sema::AssignConvertType ConvTy =
4174         CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4175     bool Diagnosed = DiagnoseAssignmentResult(
4176         ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4177         ToType, From->getType(), From, Action);
4178     assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4179     return ExprError();
4180   }
4181 
4182   // Everything went well.
4183   return From;
4184 }
4185 
4186 /// PerformImplicitConversion - Perform an implicit conversion of the
4187 /// expression From to the type ToType by following the standard
4188 /// conversion sequence SCS. Returns the converted
4189 /// expression. Flavor is the context in which we're performing this
4190 /// conversion, for use in error messages.
4191 ExprResult
4192 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4193                                 const StandardConversionSequence& SCS,
4194                                 AssignmentAction Action,
4195                                 CheckedConversionKind CCK) {
4196   bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
4197 
4198   // Overall FIXME: we are recomputing too many types here and doing far too
4199   // much extra work. What this means is that we need to keep track of more
4200   // information that is computed when we try the implicit conversion initially,
4201   // so that we don't need to recompute anything here.
4202   QualType FromType = From->getType();
4203 
4204   if (SCS.CopyConstructor) {
4205     // FIXME: When can ToType be a reference type?
4206     assert(!ToType->isReferenceType());
4207     if (SCS.Second == ICK_Derived_To_Base) {
4208       SmallVector<Expr*, 8> ConstructorArgs;
4209       if (CompleteConstructorCall(
4210               cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4211               /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4212         return ExprError();
4213       return BuildCXXConstructExpr(
4214           /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4215           SCS.FoundCopyConstructor, SCS.CopyConstructor,
4216           ConstructorArgs, /*HadMultipleCandidates*/ false,
4217           /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4218           CXXConstructExpr::CK_Complete, SourceRange());
4219     }
4220     return BuildCXXConstructExpr(
4221         /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4222         SCS.FoundCopyConstructor, SCS.CopyConstructor,
4223         From, /*HadMultipleCandidates*/ false,
4224         /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4225         CXXConstructExpr::CK_Complete, SourceRange());
4226   }
4227 
4228   // Resolve overloaded function references.
4229   if (Context.hasSameType(FromType, Context.OverloadTy)) {
4230     DeclAccessPair Found;
4231     FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
4232                                                           true, Found);
4233     if (!Fn)
4234       return ExprError();
4235 
4236     if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4237       return ExprError();
4238 
4239     From = FixOverloadedFunctionReference(From, Found, Fn);
4240     FromType = From->getType();
4241   }
4242 
4243   // If we're converting to an atomic type, first convert to the corresponding
4244   // non-atomic type.
4245   QualType ToAtomicType;
4246   if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4247     ToAtomicType = ToType;
4248     ToType = ToAtomic->getValueType();
4249   }
4250 
4251   QualType InitialFromType = FromType;
4252   // Perform the first implicit conversion.
4253   switch (SCS.First) {
4254   case ICK_Identity:
4255     if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4256       FromType = FromAtomic->getValueType().getUnqualifiedType();
4257       From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4258                                       From, /*BasePath=*/nullptr, VK_PRValue,
4259                                       FPOptionsOverride());
4260     }
4261     break;
4262 
4263   case ICK_Lvalue_To_Rvalue: {
4264     assert(From->getObjectKind() != OK_ObjCProperty);
4265     ExprResult FromRes = DefaultLvalueConversion(From);
4266     if (FromRes.isInvalid())
4267       return ExprError();
4268 
4269     From = FromRes.get();
4270     FromType = From->getType();
4271     break;
4272   }
4273 
4274   case ICK_Array_To_Pointer:
4275     FromType = Context.getArrayDecayedType(FromType);
4276     From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4277                              /*BasePath=*/nullptr, CCK)
4278                .get();
4279     break;
4280 
4281   case ICK_Function_To_Pointer:
4282     FromType = Context.getPointerType(FromType);
4283     From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4284                              VK_PRValue, /*BasePath=*/nullptr, CCK)
4285                .get();
4286     break;
4287 
4288   default:
4289     llvm_unreachable("Improper first standard conversion");
4290   }
4291 
4292   // Perform the second implicit conversion
4293   switch (SCS.Second) {
4294   case ICK_Identity:
4295     // C++ [except.spec]p5:
4296     //   [For] assignment to and initialization of pointers to functions,
4297     //   pointers to member functions, and references to functions: the
4298     //   target entity shall allow at least the exceptions allowed by the
4299     //   source value in the assignment or initialization.
4300     switch (Action) {
4301     case AA_Assigning:
4302     case AA_Initializing:
4303       // Note, function argument passing and returning are initialization.
4304     case AA_Passing:
4305     case AA_Returning:
4306     case AA_Sending:
4307     case AA_Passing_CFAudited:
4308       if (CheckExceptionSpecCompatibility(From, ToType))
4309         return ExprError();
4310       break;
4311 
4312     case AA_Casting:
4313     case AA_Converting:
4314       // Casts and implicit conversions are not initialization, so are not
4315       // checked for exception specification mismatches.
4316       break;
4317     }
4318     // Nothing else to do.
4319     break;
4320 
4321   case ICK_Integral_Promotion:
4322   case ICK_Integral_Conversion:
4323     if (ToType->isBooleanType()) {
4324       assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4325              SCS.Second == ICK_Integral_Promotion &&
4326              "only enums with fixed underlying type can promote to bool");
4327       From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue,
4328                                /*BasePath=*/nullptr, CCK)
4329                  .get();
4330     } else {
4331       From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue,
4332                                /*BasePath=*/nullptr, CCK)
4333                  .get();
4334     }
4335     break;
4336 
4337   case ICK_Floating_Promotion:
4338   case ICK_Floating_Conversion:
4339     From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue,
4340                              /*BasePath=*/nullptr, CCK)
4341                .get();
4342     break;
4343 
4344   case ICK_Complex_Promotion:
4345   case ICK_Complex_Conversion: {
4346     QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4347     QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4348     CastKind CK;
4349     if (FromEl->isRealFloatingType()) {
4350       if (ToEl->isRealFloatingType())
4351         CK = CK_FloatingComplexCast;
4352       else
4353         CK = CK_FloatingComplexToIntegralComplex;
4354     } else if (ToEl->isRealFloatingType()) {
4355       CK = CK_IntegralComplexToFloatingComplex;
4356     } else {
4357       CK = CK_IntegralComplexCast;
4358     }
4359     From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4360                              CCK)
4361                .get();
4362     break;
4363   }
4364 
4365   case ICK_Floating_Integral:
4366     if (ToType->isRealFloatingType())
4367       From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue,
4368                                /*BasePath=*/nullptr, CCK)
4369                  .get();
4370     else
4371       From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue,
4372                                /*BasePath=*/nullptr, CCK)
4373                  .get();
4374     break;
4375 
4376   case ICK_Compatible_Conversion:
4377     From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4378                              /*BasePath=*/nullptr, CCK).get();
4379     break;
4380 
4381   case ICK_Writeback_Conversion:
4382   case ICK_Pointer_Conversion: {
4383     if (SCS.IncompatibleObjC && Action != AA_Casting) {
4384       // Diagnose incompatible Objective-C conversions
4385       if (Action == AA_Initializing || Action == AA_Assigning)
4386         Diag(From->getBeginLoc(),
4387              diag::ext_typecheck_convert_incompatible_pointer)
4388             << ToType << From->getType() << Action << From->getSourceRange()
4389             << 0;
4390       else
4391         Diag(From->getBeginLoc(),
4392              diag::ext_typecheck_convert_incompatible_pointer)
4393             << From->getType() << ToType << Action << From->getSourceRange()
4394             << 0;
4395 
4396       if (From->getType()->isObjCObjectPointerType() &&
4397           ToType->isObjCObjectPointerType())
4398         EmitRelatedResultTypeNote(From);
4399     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4400                !CheckObjCARCUnavailableWeakConversion(ToType,
4401                                                       From->getType())) {
4402       if (Action == AA_Initializing)
4403         Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4404       else
4405         Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4406             << (Action == AA_Casting) << From->getType() << ToType
4407             << From->getSourceRange();
4408     }
4409 
4410     // Defer address space conversion to the third conversion.
4411     QualType FromPteeType = From->getType()->getPointeeType();
4412     QualType ToPteeType = ToType->getPointeeType();
4413     QualType NewToType = ToType;
4414     if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4415         FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4416       NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4417       NewToType = Context.getAddrSpaceQualType(NewToType,
4418                                                FromPteeType.getAddressSpace());
4419       if (ToType->isObjCObjectPointerType())
4420         NewToType = Context.getObjCObjectPointerType(NewToType);
4421       else if (ToType->isBlockPointerType())
4422         NewToType = Context.getBlockPointerType(NewToType);
4423       else
4424         NewToType = Context.getPointerType(NewToType);
4425     }
4426 
4427     CastKind Kind;
4428     CXXCastPath BasePath;
4429     if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4430       return ExprError();
4431 
4432     // Make sure we extend blocks if necessary.
4433     // FIXME: doing this here is really ugly.
4434     if (Kind == CK_BlockPointerToObjCPointerCast) {
4435       ExprResult E = From;
4436       (void) PrepareCastToObjCObjectPointer(E);
4437       From = E.get();
4438     }
4439     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4440       CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4441     From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4442                .get();
4443     break;
4444   }
4445 
4446   case ICK_Pointer_Member: {
4447     CastKind Kind;
4448     CXXCastPath BasePath;
4449     if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4450       return ExprError();
4451     if (CheckExceptionSpecCompatibility(From, ToType))
4452       return ExprError();
4453 
4454     // We may not have been able to figure out what this member pointer resolved
4455     // to up until this exact point.  Attempt to lock-in it's inheritance model.
4456     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4457       (void)isCompleteType(From->getExprLoc(), From->getType());
4458       (void)isCompleteType(From->getExprLoc(), ToType);
4459     }
4460 
4461     From =
4462         ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4463     break;
4464   }
4465 
4466   case ICK_Boolean_Conversion:
4467     // Perform half-to-boolean conversion via float.
4468     if (From->getType()->isHalfType()) {
4469       From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4470       FromType = Context.FloatTy;
4471     }
4472 
4473     From = ImpCastExprToType(From, Context.BoolTy,
4474                              ScalarTypeToBooleanCastKind(FromType), VK_PRValue,
4475                              /*BasePath=*/nullptr, CCK)
4476                .get();
4477     break;
4478 
4479   case ICK_Derived_To_Base: {
4480     CXXCastPath BasePath;
4481     if (CheckDerivedToBaseConversion(
4482             From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4483             From->getSourceRange(), &BasePath, CStyle))
4484       return ExprError();
4485 
4486     From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4487                       CK_DerivedToBase, From->getValueKind(),
4488                       &BasePath, CCK).get();
4489     break;
4490   }
4491 
4492   case ICK_Vector_Conversion:
4493     From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4494                              /*BasePath=*/nullptr, CCK)
4495                .get();
4496     break;
4497 
4498   case ICK_SVE_Vector_Conversion:
4499     From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4500                              /*BasePath=*/nullptr, CCK)
4501                .get();
4502     break;
4503 
4504   case ICK_Vector_Splat: {
4505     // Vector splat from any arithmetic type to a vector.
4506     Expr *Elem = prepareVectorSplat(ToType, From).get();
4507     From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4508                              /*BasePath=*/nullptr, CCK)
4509                .get();
4510     break;
4511   }
4512 
4513   case ICK_Complex_Real:
4514     // Case 1.  x -> _Complex y
4515     if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4516       QualType ElType = ToComplex->getElementType();
4517       bool isFloatingComplex = ElType->isRealFloatingType();
4518 
4519       // x -> y
4520       if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4521         // do nothing
4522       } else if (From->getType()->isRealFloatingType()) {
4523         From = ImpCastExprToType(From, ElType,
4524                 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4525       } else {
4526         assert(From->getType()->isIntegerType());
4527         From = ImpCastExprToType(From, ElType,
4528                 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4529       }
4530       // y -> _Complex y
4531       From = ImpCastExprToType(From, ToType,
4532                    isFloatingComplex ? CK_FloatingRealToComplex
4533                                      : CK_IntegralRealToComplex).get();
4534 
4535     // Case 2.  _Complex x -> y
4536     } else {
4537       auto *FromComplex = From->getType()->castAs<ComplexType>();
4538       QualType ElType = FromComplex->getElementType();
4539       bool isFloatingComplex = ElType->isRealFloatingType();
4540 
4541       // _Complex x -> x
4542       From = ImpCastExprToType(From, ElType,
4543                                isFloatingComplex ? CK_FloatingComplexToReal
4544                                                  : CK_IntegralComplexToReal,
4545                                VK_PRValue, /*BasePath=*/nullptr, CCK)
4546                  .get();
4547 
4548       // x -> y
4549       if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4550         // do nothing
4551       } else if (ToType->isRealFloatingType()) {
4552         From = ImpCastExprToType(From, ToType,
4553                                  isFloatingComplex ? CK_FloatingCast
4554                                                    : CK_IntegralToFloating,
4555                                  VK_PRValue, /*BasePath=*/nullptr, CCK)
4556                    .get();
4557       } else {
4558         assert(ToType->isIntegerType());
4559         From = ImpCastExprToType(From, ToType,
4560                                  isFloatingComplex ? CK_FloatingToIntegral
4561                                                    : CK_IntegralCast,
4562                                  VK_PRValue, /*BasePath=*/nullptr, CCK)
4563                    .get();
4564       }
4565     }
4566     break;
4567 
4568   case ICK_Block_Pointer_Conversion: {
4569     LangAS AddrSpaceL =
4570         ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4571     LangAS AddrSpaceR =
4572         FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4573     assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4574            "Invalid cast");
4575     CastKind Kind =
4576         AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4577     From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4578                              VK_PRValue, /*BasePath=*/nullptr, CCK)
4579                .get();
4580     break;
4581   }
4582 
4583   case ICK_TransparentUnionConversion: {
4584     ExprResult FromRes = From;
4585     Sema::AssignConvertType ConvTy =
4586       CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4587     if (FromRes.isInvalid())
4588       return ExprError();
4589     From = FromRes.get();
4590     assert ((ConvTy == Sema::Compatible) &&
4591             "Improper transparent union conversion");
4592     (void)ConvTy;
4593     break;
4594   }
4595 
4596   case ICK_Zero_Event_Conversion:
4597   case ICK_Zero_Queue_Conversion:
4598     From = ImpCastExprToType(From, ToType,
4599                              CK_ZeroToOCLOpaqueType,
4600                              From->getValueKind()).get();
4601     break;
4602 
4603   case ICK_Lvalue_To_Rvalue:
4604   case ICK_Array_To_Pointer:
4605   case ICK_Function_To_Pointer:
4606   case ICK_Function_Conversion:
4607   case ICK_Qualification:
4608   case ICK_Num_Conversion_Kinds:
4609   case ICK_C_Only_Conversion:
4610   case ICK_Incompatible_Pointer_Conversion:
4611     llvm_unreachable("Improper second standard conversion");
4612   }
4613 
4614   switch (SCS.Third) {
4615   case ICK_Identity:
4616     // Nothing to do.
4617     break;
4618 
4619   case ICK_Function_Conversion:
4620     // If both sides are functions (or pointers/references to them), there could
4621     // be incompatible exception declarations.
4622     if (CheckExceptionSpecCompatibility(From, ToType))
4623       return ExprError();
4624 
4625     From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
4626                              /*BasePath=*/nullptr, CCK)
4627                .get();
4628     break;
4629 
4630   case ICK_Qualification: {
4631     ExprValueKind VK = From->getValueKind();
4632     CastKind CK = CK_NoOp;
4633 
4634     if (ToType->isReferenceType() &&
4635         ToType->getPointeeType().getAddressSpace() !=
4636             From->getType().getAddressSpace())
4637       CK = CK_AddressSpaceConversion;
4638 
4639     if (ToType->isPointerType() &&
4640         ToType->getPointeeType().getAddressSpace() !=
4641             From->getType()->getPointeeType().getAddressSpace())
4642       CK = CK_AddressSpaceConversion;
4643 
4644     From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4645                              /*BasePath=*/nullptr, CCK)
4646                .get();
4647 
4648     if (SCS.DeprecatedStringLiteralToCharPtr &&
4649         !getLangOpts().WritableStrings) {
4650       Diag(From->getBeginLoc(),
4651            getLangOpts().CPlusPlus11
4652                ? diag::ext_deprecated_string_literal_conversion
4653                : diag::warn_deprecated_string_literal_conversion)
4654           << ToType.getNonReferenceType();
4655     }
4656 
4657     break;
4658   }
4659 
4660   default:
4661     llvm_unreachable("Improper third standard conversion");
4662   }
4663 
4664   // If this conversion sequence involved a scalar -> atomic conversion, perform
4665   // that conversion now.
4666   if (!ToAtomicType.isNull()) {
4667     assert(Context.hasSameType(
4668         ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4669     From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4670                              VK_PRValue, nullptr, CCK)
4671                .get();
4672   }
4673 
4674   // Materialize a temporary if we're implicitly converting to a reference
4675   // type. This is not required by the C++ rules but is necessary to maintain
4676   // AST invariants.
4677   if (ToType->isReferenceType() && From->isPRValue()) {
4678     ExprResult Res = TemporaryMaterializationConversion(From);
4679     if (Res.isInvalid())
4680       return ExprError();
4681     From = Res.get();
4682   }
4683 
4684   // If this conversion sequence succeeded and involved implicitly converting a
4685   // _Nullable type to a _Nonnull one, complain.
4686   if (!isCast(CCK))
4687     diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4688                                         From->getBeginLoc());
4689 
4690   return From;
4691 }
4692 
4693 /// Check the completeness of a type in a unary type trait.
4694 ///
4695 /// If the particular type trait requires a complete type, tries to complete
4696 /// it. If completing the type fails, a diagnostic is emitted and false
4697 /// returned. If completing the type succeeds or no completion was required,
4698 /// returns true.
4699 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4700                                                 SourceLocation Loc,
4701                                                 QualType ArgTy) {
4702   // C++0x [meta.unary.prop]p3:
4703   //   For all of the class templates X declared in this Clause, instantiating
4704   //   that template with a template argument that is a class template
4705   //   specialization may result in the implicit instantiation of the template
4706   //   argument if and only if the semantics of X require that the argument
4707   //   must be a complete type.
4708   // We apply this rule to all the type trait expressions used to implement
4709   // these class templates. We also try to follow any GCC documented behavior
4710   // in these expressions to ensure portability of standard libraries.
4711   switch (UTT) {
4712   default: llvm_unreachable("not a UTT");
4713     // is_complete_type somewhat obviously cannot require a complete type.
4714   case UTT_IsCompleteType:
4715     // Fall-through
4716 
4717     // These traits are modeled on the type predicates in C++0x
4718     // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4719     // requiring a complete type, as whether or not they return true cannot be
4720     // impacted by the completeness of the type.
4721   case UTT_IsVoid:
4722   case UTT_IsIntegral:
4723   case UTT_IsFloatingPoint:
4724   case UTT_IsArray:
4725   case UTT_IsPointer:
4726   case UTT_IsLvalueReference:
4727   case UTT_IsRvalueReference:
4728   case UTT_IsMemberFunctionPointer:
4729   case UTT_IsMemberObjectPointer:
4730   case UTT_IsEnum:
4731   case UTT_IsUnion:
4732   case UTT_IsClass:
4733   case UTT_IsFunction:
4734   case UTT_IsReference:
4735   case UTT_IsArithmetic:
4736   case UTT_IsFundamental:
4737   case UTT_IsObject:
4738   case UTT_IsScalar:
4739   case UTT_IsCompound:
4740   case UTT_IsMemberPointer:
4741     // Fall-through
4742 
4743     // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4744     // which requires some of its traits to have the complete type. However,
4745     // the completeness of the type cannot impact these traits' semantics, and
4746     // so they don't require it. This matches the comments on these traits in
4747     // Table 49.
4748   case UTT_IsConst:
4749   case UTT_IsVolatile:
4750   case UTT_IsSigned:
4751   case UTT_IsUnsigned:
4752 
4753   // This type trait always returns false, checking the type is moot.
4754   case UTT_IsInterfaceClass:
4755     return true;
4756 
4757   // C++14 [meta.unary.prop]:
4758   //   If T is a non-union class type, T shall be a complete type.
4759   case UTT_IsEmpty:
4760   case UTT_IsPolymorphic:
4761   case UTT_IsAbstract:
4762     if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4763       if (!RD->isUnion())
4764         return !S.RequireCompleteType(
4765             Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4766     return true;
4767 
4768   // C++14 [meta.unary.prop]:
4769   //   If T is a class type, T shall be a complete type.
4770   case UTT_IsFinal:
4771   case UTT_IsSealed:
4772     if (ArgTy->getAsCXXRecordDecl())
4773       return !S.RequireCompleteType(
4774           Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4775     return true;
4776 
4777   // C++1z [meta.unary.prop]:
4778   //   remove_all_extents_t<T> shall be a complete type or cv void.
4779   case UTT_IsAggregate:
4780   case UTT_IsTrivial:
4781   case UTT_IsTriviallyCopyable:
4782   case UTT_IsStandardLayout:
4783   case UTT_IsPOD:
4784   case UTT_IsLiteral:
4785   // By analogy, is_trivially_relocatable imposes the same constraints.
4786   case UTT_IsTriviallyRelocatable:
4787   // Per the GCC type traits documentation, T shall be a complete type, cv void,
4788   // or an array of unknown bound. But GCC actually imposes the same constraints
4789   // as above.
4790   case UTT_HasNothrowAssign:
4791   case UTT_HasNothrowMoveAssign:
4792   case UTT_HasNothrowConstructor:
4793   case UTT_HasNothrowCopy:
4794   case UTT_HasTrivialAssign:
4795   case UTT_HasTrivialMoveAssign:
4796   case UTT_HasTrivialDefaultConstructor:
4797   case UTT_HasTrivialMoveConstructor:
4798   case UTT_HasTrivialCopy:
4799   case UTT_HasTrivialDestructor:
4800   case UTT_HasVirtualDestructor:
4801     ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4802     LLVM_FALLTHROUGH;
4803 
4804   // C++1z [meta.unary.prop]:
4805   //   T shall be a complete type, cv void, or an array of unknown bound.
4806   case UTT_IsDestructible:
4807   case UTT_IsNothrowDestructible:
4808   case UTT_IsTriviallyDestructible:
4809   case UTT_HasUniqueObjectRepresentations:
4810     if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4811       return true;
4812 
4813     return !S.RequireCompleteType(
4814         Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4815   }
4816 }
4817 
4818 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4819                                Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4820                                bool (CXXRecordDecl::*HasTrivial)() const,
4821                                bool (CXXRecordDecl::*HasNonTrivial)() const,
4822                                bool (CXXMethodDecl::*IsDesiredOp)() const)
4823 {
4824   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4825   if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4826     return true;
4827 
4828   DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4829   DeclarationNameInfo NameInfo(Name, KeyLoc);
4830   LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4831   if (Self.LookupQualifiedName(Res, RD)) {
4832     bool FoundOperator = false;
4833     Res.suppressDiagnostics();
4834     for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4835          Op != OpEnd; ++Op) {
4836       if (isa<FunctionTemplateDecl>(*Op))
4837         continue;
4838 
4839       CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4840       if((Operator->*IsDesiredOp)()) {
4841         FoundOperator = true;
4842         auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
4843         CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4844         if (!CPT || !CPT->isNothrow())
4845           return false;
4846       }
4847     }
4848     return FoundOperator;
4849   }
4850   return false;
4851 }
4852 
4853 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4854                                    SourceLocation KeyLoc, QualType T) {
4855   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4856 
4857   ASTContext &C = Self.Context;
4858   switch(UTT) {
4859   default: llvm_unreachable("not a UTT");
4860     // Type trait expressions corresponding to the primary type category
4861     // predicates in C++0x [meta.unary.cat].
4862   case UTT_IsVoid:
4863     return T->isVoidType();
4864   case UTT_IsIntegral:
4865     return T->isIntegralType(C);
4866   case UTT_IsFloatingPoint:
4867     return T->isFloatingType();
4868   case UTT_IsArray:
4869     return T->isArrayType();
4870   case UTT_IsPointer:
4871     return T->isAnyPointerType();
4872   case UTT_IsLvalueReference:
4873     return T->isLValueReferenceType();
4874   case UTT_IsRvalueReference:
4875     return T->isRValueReferenceType();
4876   case UTT_IsMemberFunctionPointer:
4877     return T->isMemberFunctionPointerType();
4878   case UTT_IsMemberObjectPointer:
4879     return T->isMemberDataPointerType();
4880   case UTT_IsEnum:
4881     return T->isEnumeralType();
4882   case UTT_IsUnion:
4883     return T->isUnionType();
4884   case UTT_IsClass:
4885     return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4886   case UTT_IsFunction:
4887     return T->isFunctionType();
4888 
4889     // Type trait expressions which correspond to the convenient composition
4890     // predicates in C++0x [meta.unary.comp].
4891   case UTT_IsReference:
4892     return T->isReferenceType();
4893   case UTT_IsArithmetic:
4894     return T->isArithmeticType() && !T->isEnumeralType();
4895   case UTT_IsFundamental:
4896     return T->isFundamentalType();
4897   case UTT_IsObject:
4898     return T->isObjectType();
4899   case UTT_IsScalar:
4900     // Note: semantic analysis depends on Objective-C lifetime types to be
4901     // considered scalar types. However, such types do not actually behave
4902     // like scalar types at run time (since they may require retain/release
4903     // operations), so we report them as non-scalar.
4904     if (T->isObjCLifetimeType()) {
4905       switch (T.getObjCLifetime()) {
4906       case Qualifiers::OCL_None:
4907       case Qualifiers::OCL_ExplicitNone:
4908         return true;
4909 
4910       case Qualifiers::OCL_Strong:
4911       case Qualifiers::OCL_Weak:
4912       case Qualifiers::OCL_Autoreleasing:
4913         return false;
4914       }
4915     }
4916 
4917     return T->isScalarType();
4918   case UTT_IsCompound:
4919     return T->isCompoundType();
4920   case UTT_IsMemberPointer:
4921     return T->isMemberPointerType();
4922 
4923     // Type trait expressions which correspond to the type property predicates
4924     // in C++0x [meta.unary.prop].
4925   case UTT_IsConst:
4926     return T.isConstQualified();
4927   case UTT_IsVolatile:
4928     return T.isVolatileQualified();
4929   case UTT_IsTrivial:
4930     return T.isTrivialType(C);
4931   case UTT_IsTriviallyCopyable:
4932     return T.isTriviallyCopyableType(C);
4933   case UTT_IsStandardLayout:
4934     return T->isStandardLayoutType();
4935   case UTT_IsPOD:
4936     return T.isPODType(C);
4937   case UTT_IsLiteral:
4938     return T->isLiteralType(C);
4939   case UTT_IsEmpty:
4940     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4941       return !RD->isUnion() && RD->isEmpty();
4942     return false;
4943   case UTT_IsPolymorphic:
4944     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4945       return !RD->isUnion() && RD->isPolymorphic();
4946     return false;
4947   case UTT_IsAbstract:
4948     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4949       return !RD->isUnion() && RD->isAbstract();
4950     return false;
4951   case UTT_IsAggregate:
4952     // Report vector extensions and complex types as aggregates because they
4953     // support aggregate initialization. GCC mirrors this behavior for vectors
4954     // but not _Complex.
4955     return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4956            T->isAnyComplexType();
4957   // __is_interface_class only returns true when CL is invoked in /CLR mode and
4958   // even then only when it is used with the 'interface struct ...' syntax
4959   // Clang doesn't support /CLR which makes this type trait moot.
4960   case UTT_IsInterfaceClass:
4961     return false;
4962   case UTT_IsFinal:
4963   case UTT_IsSealed:
4964     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4965       return RD->hasAttr<FinalAttr>();
4966     return false;
4967   case UTT_IsSigned:
4968     // Enum types should always return false.
4969     // Floating points should always return true.
4970     return T->isFloatingType() ||
4971            (T->isSignedIntegerType() && !T->isEnumeralType());
4972   case UTT_IsUnsigned:
4973     // Enum types should always return false.
4974     return T->isUnsignedIntegerType() && !T->isEnumeralType();
4975 
4976     // Type trait expressions which query classes regarding their construction,
4977     // destruction, and copying. Rather than being based directly on the
4978     // related type predicates in the standard, they are specified by both
4979     // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4980     // specifications.
4981     //
4982     //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4983     //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4984     //
4985     // Note that these builtins do not behave as documented in g++: if a class
4986     // has both a trivial and a non-trivial special member of a particular kind,
4987     // they return false! For now, we emulate this behavior.
4988     // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4989     // does not correctly compute triviality in the presence of multiple special
4990     // members of the same kind. Revisit this once the g++ bug is fixed.
4991   case UTT_HasTrivialDefaultConstructor:
4992     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4993     //   If __is_pod (type) is true then the trait is true, else if type is
4994     //   a cv class or union type (or array thereof) with a trivial default
4995     //   constructor ([class.ctor]) then the trait is true, else it is false.
4996     if (T.isPODType(C))
4997       return true;
4998     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4999       return RD->hasTrivialDefaultConstructor() &&
5000              !RD->hasNonTrivialDefaultConstructor();
5001     return false;
5002   case UTT_HasTrivialMoveConstructor:
5003     //  This trait is implemented by MSVC 2012 and needed to parse the
5004     //  standard library headers. Specifically this is used as the logic
5005     //  behind std::is_trivially_move_constructible (20.9.4.3).
5006     if (T.isPODType(C))
5007       return true;
5008     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5009       return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
5010     return false;
5011   case UTT_HasTrivialCopy:
5012     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5013     //   If __is_pod (type) is true or type is a reference type then
5014     //   the trait is true, else if type is a cv class or union type
5015     //   with a trivial copy constructor ([class.copy]) then the trait
5016     //   is true, else it is false.
5017     if (T.isPODType(C) || T->isReferenceType())
5018       return true;
5019     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5020       return RD->hasTrivialCopyConstructor() &&
5021              !RD->hasNonTrivialCopyConstructor();
5022     return false;
5023   case UTT_HasTrivialMoveAssign:
5024     //  This trait is implemented by MSVC 2012 and needed to parse the
5025     //  standard library headers. Specifically it is used as the logic
5026     //  behind std::is_trivially_move_assignable (20.9.4.3)
5027     if (T.isPODType(C))
5028       return true;
5029     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5030       return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
5031     return false;
5032   case UTT_HasTrivialAssign:
5033     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5034     //   If type is const qualified or is a reference type then the
5035     //   trait is false. Otherwise if __is_pod (type) is true then the
5036     //   trait is true, else if type is a cv class or union type with
5037     //   a trivial copy assignment ([class.copy]) then the trait is
5038     //   true, else it is false.
5039     // Note: the const and reference restrictions are interesting,
5040     // given that const and reference members don't prevent a class
5041     // from having a trivial copy assignment operator (but do cause
5042     // errors if the copy assignment operator is actually used, q.v.
5043     // [class.copy]p12).
5044 
5045     if (T.isConstQualified())
5046       return false;
5047     if (T.isPODType(C))
5048       return true;
5049     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5050       return RD->hasTrivialCopyAssignment() &&
5051              !RD->hasNonTrivialCopyAssignment();
5052     return false;
5053   case UTT_IsDestructible:
5054   case UTT_IsTriviallyDestructible:
5055   case UTT_IsNothrowDestructible:
5056     // C++14 [meta.unary.prop]:
5057     //   For reference types, is_destructible<T>::value is true.
5058     if (T->isReferenceType())
5059       return true;
5060 
5061     // Objective-C++ ARC: autorelease types don't require destruction.
5062     if (T->isObjCLifetimeType() &&
5063         T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5064       return true;
5065 
5066     // C++14 [meta.unary.prop]:
5067     //   For incomplete types and function types, is_destructible<T>::value is
5068     //   false.
5069     if (T->isIncompleteType() || T->isFunctionType())
5070       return false;
5071 
5072     // A type that requires destruction (via a non-trivial destructor or ARC
5073     // lifetime semantics) is not trivially-destructible.
5074     if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
5075       return false;
5076 
5077     // C++14 [meta.unary.prop]:
5078     //   For object types and given U equal to remove_all_extents_t<T>, if the
5079     //   expression std::declval<U&>().~U() is well-formed when treated as an
5080     //   unevaluated operand (Clause 5), then is_destructible<T>::value is true
5081     if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5082       CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
5083       if (!Destructor)
5084         return false;
5085       //  C++14 [dcl.fct.def.delete]p2:
5086       //    A program that refers to a deleted function implicitly or
5087       //    explicitly, other than to declare it, is ill-formed.
5088       if (Destructor->isDeleted())
5089         return false;
5090       if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
5091         return false;
5092       if (UTT == UTT_IsNothrowDestructible) {
5093         auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
5094         CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5095         if (!CPT || !CPT->isNothrow())
5096           return false;
5097       }
5098     }
5099     return true;
5100 
5101   case UTT_HasTrivialDestructor:
5102     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5103     //   If __is_pod (type) is true or type is a reference type
5104     //   then the trait is true, else if type is a cv class or union
5105     //   type (or array thereof) with a trivial destructor
5106     //   ([class.dtor]) then the trait is true, else it is
5107     //   false.
5108     if (T.isPODType(C) || T->isReferenceType())
5109       return true;
5110 
5111     // Objective-C++ ARC: autorelease types don't require destruction.
5112     if (T->isObjCLifetimeType() &&
5113         T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5114       return true;
5115 
5116     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5117       return RD->hasTrivialDestructor();
5118     return false;
5119   // TODO: Propagate nothrowness for implicitly declared special members.
5120   case UTT_HasNothrowAssign:
5121     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5122     //   If type is const qualified or is a reference type then the
5123     //   trait is false. Otherwise if __has_trivial_assign (type)
5124     //   is true then the trait is true, else if type is a cv class
5125     //   or union type with copy assignment operators that are known
5126     //   not to throw an exception then the trait is true, else it is
5127     //   false.
5128     if (C.getBaseElementType(T).isConstQualified())
5129       return false;
5130     if (T->isReferenceType())
5131       return false;
5132     if (T.isPODType(C) || T->isObjCLifetimeType())
5133       return true;
5134 
5135     if (const RecordType *RT = T->getAs<RecordType>())
5136       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5137                                 &CXXRecordDecl::hasTrivialCopyAssignment,
5138                                 &CXXRecordDecl::hasNonTrivialCopyAssignment,
5139                                 &CXXMethodDecl::isCopyAssignmentOperator);
5140     return false;
5141   case UTT_HasNothrowMoveAssign:
5142     //  This trait is implemented by MSVC 2012 and needed to parse the
5143     //  standard library headers. Specifically this is used as the logic
5144     //  behind std::is_nothrow_move_assignable (20.9.4.3).
5145     if (T.isPODType(C))
5146       return true;
5147 
5148     if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
5149       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5150                                 &CXXRecordDecl::hasTrivialMoveAssignment,
5151                                 &CXXRecordDecl::hasNonTrivialMoveAssignment,
5152                                 &CXXMethodDecl::isMoveAssignmentOperator);
5153     return false;
5154   case UTT_HasNothrowCopy:
5155     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5156     //   If __has_trivial_copy (type) is true then the trait is true, else
5157     //   if type is a cv class or union type with copy constructors that are
5158     //   known not to throw an exception then the trait is true, else it is
5159     //   false.
5160     if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
5161       return true;
5162     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
5163       if (RD->hasTrivialCopyConstructor() &&
5164           !RD->hasNonTrivialCopyConstructor())
5165         return true;
5166 
5167       bool FoundConstructor = false;
5168       unsigned FoundTQs;
5169       for (const auto *ND : Self.LookupConstructors(RD)) {
5170         // A template constructor is never a copy constructor.
5171         // FIXME: However, it may actually be selected at the actual overload
5172         // resolution point.
5173         if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5174           continue;
5175         // UsingDecl itself is not a constructor
5176         if (isa<UsingDecl>(ND))
5177           continue;
5178         auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5179         if (Constructor->isCopyConstructor(FoundTQs)) {
5180           FoundConstructor = true;
5181           auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5182           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5183           if (!CPT)
5184             return false;
5185           // TODO: check whether evaluating default arguments can throw.
5186           // For now, we'll be conservative and assume that they can throw.
5187           if (!CPT->isNothrow() || CPT->getNumParams() > 1)
5188             return false;
5189         }
5190       }
5191 
5192       return FoundConstructor;
5193     }
5194     return false;
5195   case UTT_HasNothrowConstructor:
5196     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5197     //   If __has_trivial_constructor (type) is true then the trait is
5198     //   true, else if type is a cv class or union type (or array
5199     //   thereof) with a default constructor that is known not to
5200     //   throw an exception then the trait is true, else it is false.
5201     if (T.isPODType(C) || T->isObjCLifetimeType())
5202       return true;
5203     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5204       if (RD->hasTrivialDefaultConstructor() &&
5205           !RD->hasNonTrivialDefaultConstructor())
5206         return true;
5207 
5208       bool FoundConstructor = false;
5209       for (const auto *ND : Self.LookupConstructors(RD)) {
5210         // FIXME: In C++0x, a constructor template can be a default constructor.
5211         if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5212           continue;
5213         // UsingDecl itself is not a constructor
5214         if (isa<UsingDecl>(ND))
5215           continue;
5216         auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5217         if (Constructor->isDefaultConstructor()) {
5218           FoundConstructor = true;
5219           auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5220           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5221           if (!CPT)
5222             return false;
5223           // FIXME: check whether evaluating default arguments can throw.
5224           // For now, we'll be conservative and assume that they can throw.
5225           if (!CPT->isNothrow() || CPT->getNumParams() > 0)
5226             return false;
5227         }
5228       }
5229       return FoundConstructor;
5230     }
5231     return false;
5232   case UTT_HasVirtualDestructor:
5233     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5234     //   If type is a class type with a virtual destructor ([class.dtor])
5235     //   then the trait is true, else it is false.
5236     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5237       if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5238         return Destructor->isVirtual();
5239     return false;
5240 
5241     // These type trait expressions are modeled on the specifications for the
5242     // Embarcadero C++0x type trait functions:
5243     //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5244   case UTT_IsCompleteType:
5245     // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5246     //   Returns True if and only if T is a complete type at the point of the
5247     //   function call.
5248     return !T->isIncompleteType();
5249   case UTT_HasUniqueObjectRepresentations:
5250     return C.hasUniqueObjectRepresentations(T);
5251   case UTT_IsTriviallyRelocatable:
5252     return T.isTriviallyRelocatableType(C);
5253   }
5254 }
5255 
5256 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5257                                     QualType RhsT, SourceLocation KeyLoc);
5258 
5259 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
5260                               ArrayRef<TypeSourceInfo *> Args,
5261                               SourceLocation RParenLoc) {
5262   if (Kind <= UTT_Last)
5263     return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
5264 
5265   // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
5266   // traits to avoid duplication.
5267   if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
5268     return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
5269                                    Args[1]->getType(), RParenLoc);
5270 
5271   switch (Kind) {
5272   case clang::BTT_ReferenceBindsToTemporary:
5273   case clang::TT_IsConstructible:
5274   case clang::TT_IsNothrowConstructible:
5275   case clang::TT_IsTriviallyConstructible: {
5276     // C++11 [meta.unary.prop]:
5277     //   is_trivially_constructible is defined as:
5278     //
5279     //     is_constructible<T, Args...>::value is true and the variable
5280     //     definition for is_constructible, as defined below, is known to call
5281     //     no operation that is not trivial.
5282     //
5283     //   The predicate condition for a template specialization
5284     //   is_constructible<T, Args...> shall be satisfied if and only if the
5285     //   following variable definition would be well-formed for some invented
5286     //   variable t:
5287     //
5288     //     T t(create<Args>()...);
5289     assert(!Args.empty());
5290 
5291     // Precondition: T and all types in the parameter pack Args shall be
5292     // complete types, (possibly cv-qualified) void, or arrays of
5293     // unknown bound.
5294     for (const auto *TSI : Args) {
5295       QualType ArgTy = TSI->getType();
5296       if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
5297         continue;
5298 
5299       if (S.RequireCompleteType(KWLoc, ArgTy,
5300           diag::err_incomplete_type_used_in_type_trait_expr))
5301         return false;
5302     }
5303 
5304     // Make sure the first argument is not incomplete nor a function type.
5305     QualType T = Args[0]->getType();
5306     if (T->isIncompleteType() || T->isFunctionType())
5307       return false;
5308 
5309     // Make sure the first argument is not an abstract type.
5310     CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5311     if (RD && RD->isAbstract())
5312       return false;
5313 
5314     llvm::BumpPtrAllocator OpaqueExprAllocator;
5315     SmallVector<Expr *, 2> ArgExprs;
5316     ArgExprs.reserve(Args.size() - 1);
5317     for (unsigned I = 1, N = Args.size(); I != N; ++I) {
5318       QualType ArgTy = Args[I]->getType();
5319       if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5320         ArgTy = S.Context.getRValueReferenceType(ArgTy);
5321       ArgExprs.push_back(
5322           new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5323               OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
5324                               ArgTy.getNonLValueExprType(S.Context),
5325                               Expr::getValueKindForType(ArgTy)));
5326     }
5327 
5328     // Perform the initialization in an unevaluated context within a SFINAE
5329     // trap at translation unit scope.
5330     EnterExpressionEvaluationContext Unevaluated(
5331         S, Sema::ExpressionEvaluationContext::Unevaluated);
5332     Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5333     Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
5334     InitializedEntity To(
5335         InitializedEntity::InitializeTemporary(S.Context, Args[0]));
5336     InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
5337                                                                  RParenLoc));
5338     InitializationSequence Init(S, To, InitKind, ArgExprs);
5339     if (Init.Failed())
5340       return false;
5341 
5342     ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5343     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5344       return false;
5345 
5346     if (Kind == clang::TT_IsConstructible)
5347       return true;
5348 
5349     if (Kind == clang::BTT_ReferenceBindsToTemporary) {
5350       if (!T->isReferenceType())
5351         return false;
5352 
5353       return !Init.isDirectReferenceBinding();
5354     }
5355 
5356     if (Kind == clang::TT_IsNothrowConstructible)
5357       return S.canThrow(Result.get()) == CT_Cannot;
5358 
5359     if (Kind == clang::TT_IsTriviallyConstructible) {
5360       // Under Objective-C ARC and Weak, if the destination has non-trivial
5361       // Objective-C lifetime, this is a non-trivial construction.
5362       if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5363         return false;
5364 
5365       // The initialization succeeded; now make sure there are no non-trivial
5366       // calls.
5367       return !Result.get()->hasNonTrivialCall(S.Context);
5368     }
5369 
5370     llvm_unreachable("unhandled type trait");
5371     return false;
5372   }
5373     default: llvm_unreachable("not a TT");
5374   }
5375 
5376   return false;
5377 }
5378 
5379 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5380                                 ArrayRef<TypeSourceInfo *> Args,
5381                                 SourceLocation RParenLoc) {
5382   QualType ResultType = Context.getLogicalOperationType();
5383 
5384   if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5385                                *this, Kind, KWLoc, Args[0]->getType()))
5386     return ExprError();
5387 
5388   bool Dependent = false;
5389   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5390     if (Args[I]->getType()->isDependentType()) {
5391       Dependent = true;
5392       break;
5393     }
5394   }
5395 
5396   bool Result = false;
5397   if (!Dependent)
5398     Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5399 
5400   return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5401                                RParenLoc, Result);
5402 }
5403 
5404 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5405                                 ArrayRef<ParsedType> Args,
5406                                 SourceLocation RParenLoc) {
5407   SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5408   ConvertedArgs.reserve(Args.size());
5409 
5410   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5411     TypeSourceInfo *TInfo;
5412     QualType T = GetTypeFromParser(Args[I], &TInfo);
5413     if (!TInfo)
5414       TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5415 
5416     ConvertedArgs.push_back(TInfo);
5417   }
5418 
5419   return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5420 }
5421 
5422 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5423                                     QualType RhsT, SourceLocation KeyLoc) {
5424   assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5425          "Cannot evaluate traits of dependent types");
5426 
5427   switch(BTT) {
5428   case BTT_IsBaseOf: {
5429     // C++0x [meta.rel]p2
5430     // Base is a base class of Derived without regard to cv-qualifiers or
5431     // Base and Derived are not unions and name the same class type without
5432     // regard to cv-qualifiers.
5433 
5434     const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5435     const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5436     if (!rhsRecord || !lhsRecord) {
5437       const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5438       const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5439       if (!LHSObjTy || !RHSObjTy)
5440         return false;
5441 
5442       ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5443       ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5444       if (!BaseInterface || !DerivedInterface)
5445         return false;
5446 
5447       if (Self.RequireCompleteType(
5448               KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5449         return false;
5450 
5451       return BaseInterface->isSuperClassOf(DerivedInterface);
5452     }
5453 
5454     assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5455              == (lhsRecord == rhsRecord));
5456 
5457     // Unions are never base classes, and never have base classes.
5458     // It doesn't matter if they are complete or not. See PR#41843
5459     if (lhsRecord && lhsRecord->getDecl()->isUnion())
5460       return false;
5461     if (rhsRecord && rhsRecord->getDecl()->isUnion())
5462       return false;
5463 
5464     if (lhsRecord == rhsRecord)
5465       return true;
5466 
5467     // C++0x [meta.rel]p2:
5468     //   If Base and Derived are class types and are different types
5469     //   (ignoring possible cv-qualifiers) then Derived shall be a
5470     //   complete type.
5471     if (Self.RequireCompleteType(KeyLoc, RhsT,
5472                           diag::err_incomplete_type_used_in_type_trait_expr))
5473       return false;
5474 
5475     return cast<CXXRecordDecl>(rhsRecord->getDecl())
5476       ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5477   }
5478   case BTT_IsSame:
5479     return Self.Context.hasSameType(LhsT, RhsT);
5480   case BTT_TypeCompatible: {
5481     // GCC ignores cv-qualifiers on arrays for this builtin.
5482     Qualifiers LhsQuals, RhsQuals;
5483     QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5484     QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5485     return Self.Context.typesAreCompatible(Lhs, Rhs);
5486   }
5487   case BTT_IsConvertible:
5488   case BTT_IsConvertibleTo: {
5489     // C++0x [meta.rel]p4:
5490     //   Given the following function prototype:
5491     //
5492     //     template <class T>
5493     //       typename add_rvalue_reference<T>::type create();
5494     //
5495     //   the predicate condition for a template specialization
5496     //   is_convertible<From, To> shall be satisfied if and only if
5497     //   the return expression in the following code would be
5498     //   well-formed, including any implicit conversions to the return
5499     //   type of the function:
5500     //
5501     //     To test() {
5502     //       return create<From>();
5503     //     }
5504     //
5505     //   Access checking is performed as if in a context unrelated to To and
5506     //   From. Only the validity of the immediate context of the expression
5507     //   of the return-statement (including conversions to the return type)
5508     //   is considered.
5509     //
5510     // We model the initialization as a copy-initialization of a temporary
5511     // of the appropriate type, which for this expression is identical to the
5512     // return statement (since NRVO doesn't apply).
5513 
5514     // Functions aren't allowed to return function or array types.
5515     if (RhsT->isFunctionType() || RhsT->isArrayType())
5516       return false;
5517 
5518     // A return statement in a void function must have void type.
5519     if (RhsT->isVoidType())
5520       return LhsT->isVoidType();
5521 
5522     // A function definition requires a complete, non-abstract return type.
5523     if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5524       return false;
5525 
5526     // Compute the result of add_rvalue_reference.
5527     if (LhsT->isObjectType() || LhsT->isFunctionType())
5528       LhsT = Self.Context.getRValueReferenceType(LhsT);
5529 
5530     // Build a fake source and destination for initialization.
5531     InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
5532     OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5533                          Expr::getValueKindForType(LhsT));
5534     Expr *FromPtr = &From;
5535     InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
5536                                                            SourceLocation()));
5537 
5538     // Perform the initialization in an unevaluated context within a SFINAE
5539     // trap at translation unit scope.
5540     EnterExpressionEvaluationContext Unevaluated(
5541         Self, Sema::ExpressionEvaluationContext::Unevaluated);
5542     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5543     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5544     InitializationSequence Init(Self, To, Kind, FromPtr);
5545     if (Init.Failed())
5546       return false;
5547 
5548     ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5549     return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5550   }
5551 
5552   case BTT_IsAssignable:
5553   case BTT_IsNothrowAssignable:
5554   case BTT_IsTriviallyAssignable: {
5555     // C++11 [meta.unary.prop]p3:
5556     //   is_trivially_assignable is defined as:
5557     //     is_assignable<T, U>::value is true and the assignment, as defined by
5558     //     is_assignable, is known to call no operation that is not trivial
5559     //
5560     //   is_assignable is defined as:
5561     //     The expression declval<T>() = declval<U>() is well-formed when
5562     //     treated as an unevaluated operand (Clause 5).
5563     //
5564     //   For both, T and U shall be complete types, (possibly cv-qualified)
5565     //   void, or arrays of unknown bound.
5566     if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5567         Self.RequireCompleteType(KeyLoc, LhsT,
5568           diag::err_incomplete_type_used_in_type_trait_expr))
5569       return false;
5570     if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5571         Self.RequireCompleteType(KeyLoc, RhsT,
5572           diag::err_incomplete_type_used_in_type_trait_expr))
5573       return false;
5574 
5575     // cv void is never assignable.
5576     if (LhsT->isVoidType() || RhsT->isVoidType())
5577       return false;
5578 
5579     // Build expressions that emulate the effect of declval<T>() and
5580     // declval<U>().
5581     if (LhsT->isObjectType() || LhsT->isFunctionType())
5582       LhsT = Self.Context.getRValueReferenceType(LhsT);
5583     if (RhsT->isObjectType() || RhsT->isFunctionType())
5584       RhsT = Self.Context.getRValueReferenceType(RhsT);
5585     OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5586                         Expr::getValueKindForType(LhsT));
5587     OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5588                         Expr::getValueKindForType(RhsT));
5589 
5590     // Attempt the assignment in an unevaluated context within a SFINAE
5591     // trap at translation unit scope.
5592     EnterExpressionEvaluationContext Unevaluated(
5593         Self, Sema::ExpressionEvaluationContext::Unevaluated);
5594     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5595     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5596     ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5597                                         &Rhs);
5598     if (Result.isInvalid())
5599       return false;
5600 
5601     // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
5602     Self.CheckUnusedVolatileAssignment(Result.get());
5603 
5604     if (SFINAE.hasErrorOccurred())
5605       return false;
5606 
5607     if (BTT == BTT_IsAssignable)
5608       return true;
5609 
5610     if (BTT == BTT_IsNothrowAssignable)
5611       return Self.canThrow(Result.get()) == CT_Cannot;
5612 
5613     if (BTT == BTT_IsTriviallyAssignable) {
5614       // Under Objective-C ARC and Weak, if the destination has non-trivial
5615       // Objective-C lifetime, this is a non-trivial assignment.
5616       if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
5617         return false;
5618 
5619       return !Result.get()->hasNonTrivialCall(Self.Context);
5620     }
5621 
5622     llvm_unreachable("unhandled type trait");
5623     return false;
5624   }
5625     default: llvm_unreachable("not a BTT");
5626   }
5627   llvm_unreachable("Unknown type trait or not implemented");
5628 }
5629 
5630 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5631                                      SourceLocation KWLoc,
5632                                      ParsedType Ty,
5633                                      Expr* DimExpr,
5634                                      SourceLocation RParen) {
5635   TypeSourceInfo *TSInfo;
5636   QualType T = GetTypeFromParser(Ty, &TSInfo);
5637   if (!TSInfo)
5638     TSInfo = Context.getTrivialTypeSourceInfo(T);
5639 
5640   return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5641 }
5642 
5643 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5644                                            QualType T, Expr *DimExpr,
5645                                            SourceLocation KeyLoc) {
5646   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5647 
5648   switch(ATT) {
5649   case ATT_ArrayRank:
5650     if (T->isArrayType()) {
5651       unsigned Dim = 0;
5652       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5653         ++Dim;
5654         T = AT->getElementType();
5655       }
5656       return Dim;
5657     }
5658     return 0;
5659 
5660   case ATT_ArrayExtent: {
5661     llvm::APSInt Value;
5662     uint64_t Dim;
5663     if (Self.VerifyIntegerConstantExpression(
5664                 DimExpr, &Value, diag::err_dimension_expr_not_constant_integer)
5665             .isInvalid())
5666       return 0;
5667     if (Value.isSigned() && Value.isNegative()) {
5668       Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5669         << DimExpr->getSourceRange();
5670       return 0;
5671     }
5672     Dim = Value.getLimitedValue();
5673 
5674     if (T->isArrayType()) {
5675       unsigned D = 0;
5676       bool Matched = false;
5677       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5678         if (Dim == D) {
5679           Matched = true;
5680           break;
5681         }
5682         ++D;
5683         T = AT->getElementType();
5684       }
5685 
5686       if (Matched && T->isArrayType()) {
5687         if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5688           return CAT->getSize().getLimitedValue();
5689       }
5690     }
5691     return 0;
5692   }
5693   }
5694   llvm_unreachable("Unknown type trait or not implemented");
5695 }
5696 
5697 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5698                                      SourceLocation KWLoc,
5699                                      TypeSourceInfo *TSInfo,
5700                                      Expr* DimExpr,
5701                                      SourceLocation RParen) {
5702   QualType T = TSInfo->getType();
5703 
5704   // FIXME: This should likely be tracked as an APInt to remove any host
5705   // assumptions about the width of size_t on the target.
5706   uint64_t Value = 0;
5707   if (!T->isDependentType())
5708     Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5709 
5710   // While the specification for these traits from the Embarcadero C++
5711   // compiler's documentation says the return type is 'unsigned int', Clang
5712   // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5713   // compiler, there is no difference. On several other platforms this is an
5714   // important distinction.
5715   return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5716                                           RParen, Context.getSizeType());
5717 }
5718 
5719 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
5720                                       SourceLocation KWLoc,
5721                                       Expr *Queried,
5722                                       SourceLocation RParen) {
5723   // If error parsing the expression, ignore.
5724   if (!Queried)
5725     return ExprError();
5726 
5727   ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5728 
5729   return Result;
5730 }
5731 
5732 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5733   switch (ET) {
5734   case ET_IsLValueExpr: return E->isLValue();
5735   case ET_IsRValueExpr:
5736     return E->isPRValue();
5737   }
5738   llvm_unreachable("Expression trait not covered by switch");
5739 }
5740 
5741 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5742                                       SourceLocation KWLoc,
5743                                       Expr *Queried,
5744                                       SourceLocation RParen) {
5745   if (Queried->isTypeDependent()) {
5746     // Delay type-checking for type-dependent expressions.
5747   } else if (Queried->hasPlaceholderType()) {
5748     ExprResult PE = CheckPlaceholderExpr(Queried);
5749     if (PE.isInvalid()) return ExprError();
5750     return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5751   }
5752 
5753   bool Value = EvaluateExpressionTrait(ET, Queried);
5754 
5755   return new (Context)
5756       ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5757 }
5758 
5759 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5760                                             ExprValueKind &VK,
5761                                             SourceLocation Loc,
5762                                             bool isIndirect) {
5763   assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
5764          "placeholders should have been weeded out by now");
5765 
5766   // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5767   // temporary materialization conversion otherwise.
5768   if (isIndirect)
5769     LHS = DefaultLvalueConversion(LHS.get());
5770   else if (LHS.get()->isPRValue())
5771     LHS = TemporaryMaterializationConversion(LHS.get());
5772   if (LHS.isInvalid())
5773     return QualType();
5774 
5775   // The RHS always undergoes lvalue conversions.
5776   RHS = DefaultLvalueConversion(RHS.get());
5777   if (RHS.isInvalid()) return QualType();
5778 
5779   const char *OpSpelling = isIndirect ? "->*" : ".*";
5780   // C++ 5.5p2
5781   //   The binary operator .* [p3: ->*] binds its second operand, which shall
5782   //   be of type "pointer to member of T" (where T is a completely-defined
5783   //   class type) [...]
5784   QualType RHSType = RHS.get()->getType();
5785   const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5786   if (!MemPtr) {
5787     Diag(Loc, diag::err_bad_memptr_rhs)
5788       << OpSpelling << RHSType << RHS.get()->getSourceRange();
5789     return QualType();
5790   }
5791 
5792   QualType Class(MemPtr->getClass(), 0);
5793 
5794   // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5795   // member pointer points must be completely-defined. However, there is no
5796   // reason for this semantic distinction, and the rule is not enforced by
5797   // other compilers. Therefore, we do not check this property, as it is
5798   // likely to be considered a defect.
5799 
5800   // C++ 5.5p2
5801   //   [...] to its first operand, which shall be of class T or of a class of
5802   //   which T is an unambiguous and accessible base class. [p3: a pointer to
5803   //   such a class]
5804   QualType LHSType = LHS.get()->getType();
5805   if (isIndirect) {
5806     if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5807       LHSType = Ptr->getPointeeType();
5808     else {
5809       Diag(Loc, diag::err_bad_memptr_lhs)
5810         << OpSpelling << 1 << LHSType
5811         << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5812       return QualType();
5813     }
5814   }
5815 
5816   if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5817     // If we want to check the hierarchy, we need a complete type.
5818     if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5819                             OpSpelling, (int)isIndirect)) {
5820       return QualType();
5821     }
5822 
5823     if (!IsDerivedFrom(Loc, LHSType, Class)) {
5824       Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5825         << (int)isIndirect << LHS.get()->getType();
5826       return QualType();
5827     }
5828 
5829     CXXCastPath BasePath;
5830     if (CheckDerivedToBaseConversion(
5831             LHSType, Class, Loc,
5832             SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
5833             &BasePath))
5834       return QualType();
5835 
5836     // Cast LHS to type of use.
5837     QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5838     if (isIndirect)
5839       UseType = Context.getPointerType(UseType);
5840     ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
5841     LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5842                             &BasePath);
5843   }
5844 
5845   if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5846     // Diagnose use of pointer-to-member type which when used as
5847     // the functional cast in a pointer-to-member expression.
5848     Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5849      return QualType();
5850   }
5851 
5852   // C++ 5.5p2
5853   //   The result is an object or a function of the type specified by the
5854   //   second operand.
5855   // The cv qualifiers are the union of those in the pointer and the left side,
5856   // in accordance with 5.5p5 and 5.2.5.
5857   QualType Result = MemPtr->getPointeeType();
5858   Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5859 
5860   // C++0x [expr.mptr.oper]p6:
5861   //   In a .* expression whose object expression is an rvalue, the program is
5862   //   ill-formed if the second operand is a pointer to member function with
5863   //   ref-qualifier &. In a ->* expression or in a .* expression whose object
5864   //   expression is an lvalue, the program is ill-formed if the second operand
5865   //   is a pointer to member function with ref-qualifier &&.
5866   if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5867     switch (Proto->getRefQualifier()) {
5868     case RQ_None:
5869       // Do nothing
5870       break;
5871 
5872     case RQ_LValue:
5873       if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5874         // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5875         // is (exactly) 'const'.
5876         if (Proto->isConst() && !Proto->isVolatile())
5877           Diag(Loc, getLangOpts().CPlusPlus20
5878                         ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5879                         : diag::ext_pointer_to_const_ref_member_on_rvalue);
5880         else
5881           Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5882               << RHSType << 1 << LHS.get()->getSourceRange();
5883       }
5884       break;
5885 
5886     case RQ_RValue:
5887       if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5888         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5889           << RHSType << 0 << LHS.get()->getSourceRange();
5890       break;
5891     }
5892   }
5893 
5894   // C++ [expr.mptr.oper]p6:
5895   //   The result of a .* expression whose second operand is a pointer
5896   //   to a data member is of the same value category as its
5897   //   first operand. The result of a .* expression whose second
5898   //   operand is a pointer to a member function is a prvalue. The
5899   //   result of an ->* expression is an lvalue if its second operand
5900   //   is a pointer to data member and a prvalue otherwise.
5901   if (Result->isFunctionType()) {
5902     VK = VK_PRValue;
5903     return Context.BoundMemberTy;
5904   } else if (isIndirect) {
5905     VK = VK_LValue;
5906   } else {
5907     VK = LHS.get()->getValueKind();
5908   }
5909 
5910   return Result;
5911 }
5912 
5913 /// Try to convert a type to another according to C++11 5.16p3.
5914 ///
5915 /// This is part of the parameter validation for the ? operator. If either
5916 /// value operand is a class type, the two operands are attempted to be
5917 /// converted to each other. This function does the conversion in one direction.
5918 /// It returns true if the program is ill-formed and has already been diagnosed
5919 /// as such.
5920 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5921                                 SourceLocation QuestionLoc,
5922                                 bool &HaveConversion,
5923                                 QualType &ToType) {
5924   HaveConversion = false;
5925   ToType = To->getType();
5926 
5927   InitializationKind Kind =
5928       InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
5929   // C++11 5.16p3
5930   //   The process for determining whether an operand expression E1 of type T1
5931   //   can be converted to match an operand expression E2 of type T2 is defined
5932   //   as follows:
5933   //   -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5934   //      implicitly converted to type "lvalue reference to T2", subject to the
5935   //      constraint that in the conversion the reference must bind directly to
5936   //      an lvalue.
5937   //   -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5938   //      implicitly converted to the type "rvalue reference to R2", subject to
5939   //      the constraint that the reference must bind directly.
5940   if (To->isGLValue()) {
5941     QualType T = Self.Context.getReferenceQualifiedType(To);
5942     InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5943 
5944     InitializationSequence InitSeq(Self, Entity, Kind, From);
5945     if (InitSeq.isDirectReferenceBinding()) {
5946       ToType = T;
5947       HaveConversion = true;
5948       return false;
5949     }
5950 
5951     if (InitSeq.isAmbiguous())
5952       return InitSeq.Diagnose(Self, Entity, Kind, From);
5953   }
5954 
5955   //   -- If E2 is an rvalue, or if the conversion above cannot be done:
5956   //      -- if E1 and E2 have class type, and the underlying class types are
5957   //         the same or one is a base class of the other:
5958   QualType FTy = From->getType();
5959   QualType TTy = To->getType();
5960   const RecordType *FRec = FTy->getAs<RecordType>();
5961   const RecordType *TRec = TTy->getAs<RecordType>();
5962   bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5963                        Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5964   if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5965                        Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5966     //         E1 can be converted to match E2 if the class of T2 is the
5967     //         same type as, or a base class of, the class of T1, and
5968     //         [cv2 > cv1].
5969     if (FRec == TRec || FDerivedFromT) {
5970       if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5971         InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5972         InitializationSequence InitSeq(Self, Entity, Kind, From);
5973         if (InitSeq) {
5974           HaveConversion = true;
5975           return false;
5976         }
5977 
5978         if (InitSeq.isAmbiguous())
5979           return InitSeq.Diagnose(Self, Entity, Kind, From);
5980       }
5981     }
5982 
5983     return false;
5984   }
5985 
5986   //     -- Otherwise: E1 can be converted to match E2 if E1 can be
5987   //        implicitly converted to the type that expression E2 would have
5988   //        if E2 were converted to an rvalue (or the type it has, if E2 is
5989   //        an rvalue).
5990   //
5991   // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5992   // to the array-to-pointer or function-to-pointer conversions.
5993   TTy = TTy.getNonLValueExprType(Self.Context);
5994 
5995   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5996   InitializationSequence InitSeq(Self, Entity, Kind, From);
5997   HaveConversion = !InitSeq.Failed();
5998   ToType = TTy;
5999   if (InitSeq.isAmbiguous())
6000     return InitSeq.Diagnose(Self, Entity, Kind, From);
6001 
6002   return false;
6003 }
6004 
6005 /// Try to find a common type for two according to C++0x 5.16p5.
6006 ///
6007 /// This is part of the parameter validation for the ? operator. If either
6008 /// value operand is a class type, overload resolution is used to find a
6009 /// conversion to a common type.
6010 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
6011                                     SourceLocation QuestionLoc) {
6012   Expr *Args[2] = { LHS.get(), RHS.get() };
6013   OverloadCandidateSet CandidateSet(QuestionLoc,
6014                                     OverloadCandidateSet::CSK_Operator);
6015   Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
6016                                     CandidateSet);
6017 
6018   OverloadCandidateSet::iterator Best;
6019   switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
6020     case OR_Success: {
6021       // We found a match. Perform the conversions on the arguments and move on.
6022       ExprResult LHSRes = Self.PerformImplicitConversion(
6023           LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
6024           Sema::AA_Converting);
6025       if (LHSRes.isInvalid())
6026         break;
6027       LHS = LHSRes;
6028 
6029       ExprResult RHSRes = Self.PerformImplicitConversion(
6030           RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
6031           Sema::AA_Converting);
6032       if (RHSRes.isInvalid())
6033         break;
6034       RHS = RHSRes;
6035       if (Best->Function)
6036         Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
6037       return false;
6038     }
6039 
6040     case OR_No_Viable_Function:
6041 
6042       // Emit a better diagnostic if one of the expressions is a null pointer
6043       // constant and the other is a pointer type. In this case, the user most
6044       // likely forgot to take the address of the other expression.
6045       if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6046         return true;
6047 
6048       Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6049         << LHS.get()->getType() << RHS.get()->getType()
6050         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6051       return true;
6052 
6053     case OR_Ambiguous:
6054       Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
6055         << LHS.get()->getType() << RHS.get()->getType()
6056         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6057       // FIXME: Print the possible common types by printing the return types of
6058       // the viable candidates.
6059       break;
6060 
6061     case OR_Deleted:
6062       llvm_unreachable("Conditional operator has only built-in overloads");
6063   }
6064   return true;
6065 }
6066 
6067 /// Perform an "extended" implicit conversion as returned by
6068 /// TryClassUnification.
6069 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
6070   InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
6071   InitializationKind Kind =
6072       InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
6073   Expr *Arg = E.get();
6074   InitializationSequence InitSeq(Self, Entity, Kind, Arg);
6075   ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
6076   if (Result.isInvalid())
6077     return true;
6078 
6079   E = Result;
6080   return false;
6081 }
6082 
6083 // Check the condition operand of ?: to see if it is valid for the GCC
6084 // extension.
6085 static bool isValidVectorForConditionalCondition(ASTContext &Ctx,
6086                                                  QualType CondTy) {
6087   if (!CondTy->isVectorType() && !CondTy->isExtVectorType())
6088     return false;
6089   const QualType EltTy =
6090       cast<VectorType>(CondTy.getCanonicalType())->getElementType();
6091   assert(!EltTy->isBooleanType() && !EltTy->isEnumeralType() &&
6092          "Vectors cant be boolean or enum types");
6093   return EltTy->isIntegralType(Ctx);
6094 }
6095 
6096 QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
6097                                            ExprResult &RHS,
6098                                            SourceLocation QuestionLoc) {
6099   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6100   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6101 
6102   QualType CondType = Cond.get()->getType();
6103   const auto *CondVT = CondType->castAs<VectorType>();
6104   QualType CondElementTy = CondVT->getElementType();
6105   unsigned CondElementCount = CondVT->getNumElements();
6106   QualType LHSType = LHS.get()->getType();
6107   const auto *LHSVT = LHSType->getAs<VectorType>();
6108   QualType RHSType = RHS.get()->getType();
6109   const auto *RHSVT = RHSType->getAs<VectorType>();
6110 
6111   QualType ResultType;
6112 
6113 
6114   if (LHSVT && RHSVT) {
6115     if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {
6116       Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
6117           << /*isExtVector*/ isa<ExtVectorType>(CondVT);
6118       return {};
6119     }
6120 
6121     // If both are vector types, they must be the same type.
6122     if (!Context.hasSameType(LHSType, RHSType)) {
6123       Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6124           << LHSType << RHSType;
6125       return {};
6126     }
6127     ResultType = LHSType;
6128   } else if (LHSVT || RHSVT) {
6129     ResultType = CheckVectorOperands(
6130         LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
6131         /*AllowBoolConversions*/ false);
6132     if (ResultType.isNull())
6133       return {};
6134   } else {
6135     // Both are scalar.
6136     QualType ResultElementTy;
6137     LHSType = LHSType.getCanonicalType().getUnqualifiedType();
6138     RHSType = RHSType.getCanonicalType().getUnqualifiedType();
6139 
6140     if (Context.hasSameType(LHSType, RHSType))
6141       ResultElementTy = LHSType;
6142     else
6143       ResultElementTy =
6144           UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6145 
6146     if (ResultElementTy->isEnumeralType()) {
6147       Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6148           << ResultElementTy;
6149       return {};
6150     }
6151     if (CondType->isExtVectorType())
6152       ResultType =
6153           Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());
6154     else
6155       ResultType = Context.getVectorType(
6156           ResultElementTy, CondVT->getNumElements(), VectorType::GenericVector);
6157 
6158     LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6159     RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6160   }
6161 
6162   assert(!ResultType.isNull() && ResultType->isVectorType() &&
6163          (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
6164          "Result should have been a vector type");
6165   auto *ResultVectorTy = ResultType->castAs<VectorType>();
6166   QualType ResultElementTy = ResultVectorTy->getElementType();
6167   unsigned ResultElementCount = ResultVectorTy->getNumElements();
6168 
6169   if (ResultElementCount != CondElementCount) {
6170     Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
6171                                                          << ResultType;
6172     return {};
6173   }
6174 
6175   if (Context.getTypeSize(ResultElementTy) !=
6176       Context.getTypeSize(CondElementTy)) {
6177     Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
6178                                                                  << ResultType;
6179     return {};
6180   }
6181 
6182   return ResultType;
6183 }
6184 
6185 /// Check the operands of ?: under C++ semantics.
6186 ///
6187 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
6188 /// extension. In this case, LHS == Cond. (But they're not aliases.)
6189 ///
6190 /// This function also implements GCC's vector extension and the
6191 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
6192 /// permit the use of a?b:c where the type of a is that of a integer vector with
6193 /// the same number of elements and size as the vectors of b and c. If one of
6194 /// either b or c is a scalar it is implicitly converted to match the type of
6195 /// the vector. Otherwise the expression is ill-formed. If both b and c are
6196 /// scalars, then b and c are checked and converted to the type of a if
6197 /// possible.
6198 ///
6199 /// The expressions are evaluated differently for GCC's and OpenCL's extensions.
6200 /// For the GCC extension, the ?: operator is evaluated as
6201 ///   (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
6202 /// For the OpenCL extensions, the ?: operator is evaluated as
6203 ///   (most-significant-bit-set(a[0])  ? b[0] : c[0], .. ,
6204 ///    most-significant-bit-set(a[n]) ? b[n] : c[n]).
6205 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6206                                            ExprResult &RHS, ExprValueKind &VK,
6207                                            ExprObjectKind &OK,
6208                                            SourceLocation QuestionLoc) {
6209   // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6210   // pointers.
6211 
6212   // Assume r-value.
6213   VK = VK_PRValue;
6214   OK = OK_Ordinary;
6215   bool IsVectorConditional =
6216       isValidVectorForConditionalCondition(Context, Cond.get()->getType());
6217 
6218   // C++11 [expr.cond]p1
6219   //   The first expression is contextually converted to bool.
6220   if (!Cond.get()->isTypeDependent()) {
6221     ExprResult CondRes = IsVectorConditional
6222                              ? DefaultFunctionArrayLvalueConversion(Cond.get())
6223                              : CheckCXXBooleanCondition(Cond.get());
6224     if (CondRes.isInvalid())
6225       return QualType();
6226     Cond = CondRes;
6227   } else {
6228     // To implement C++, the first expression typically doesn't alter the result
6229     // type of the conditional, however the GCC compatible vector extension
6230     // changes the result type to be that of the conditional. Since we cannot
6231     // know if this is a vector extension here, delay the conversion of the
6232     // LHS/RHS below until later.
6233     return Context.DependentTy;
6234   }
6235 
6236 
6237   // Either of the arguments dependent?
6238   if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
6239     return Context.DependentTy;
6240 
6241   // C++11 [expr.cond]p2
6242   //   If either the second or the third operand has type (cv) void, ...
6243   QualType LTy = LHS.get()->getType();
6244   QualType RTy = RHS.get()->getType();
6245   bool LVoid = LTy->isVoidType();
6246   bool RVoid = RTy->isVoidType();
6247   if (LVoid || RVoid) {
6248     //   ... one of the following shall hold:
6249     //   -- The second or the third operand (but not both) is a (possibly
6250     //      parenthesized) throw-expression; the result is of the type
6251     //      and value category of the other.
6252     bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
6253     bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
6254 
6255     // Void expressions aren't legal in the vector-conditional expressions.
6256     if (IsVectorConditional) {
6257       SourceRange DiagLoc =
6258           LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
6259       bool IsThrow = LVoid ? LThrow : RThrow;
6260       Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
6261           << DiagLoc << IsThrow;
6262       return QualType();
6263     }
6264 
6265     if (LThrow != RThrow) {
6266       Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
6267       VK = NonThrow->getValueKind();
6268       // DR (no number yet): the result is a bit-field if the
6269       // non-throw-expression operand is a bit-field.
6270       OK = NonThrow->getObjectKind();
6271       return NonThrow->getType();
6272     }
6273 
6274     //   -- Both the second and third operands have type void; the result is of
6275     //      type void and is a prvalue.
6276     if (LVoid && RVoid)
6277       return Context.VoidTy;
6278 
6279     // Neither holds, error.
6280     Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
6281       << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
6282       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6283     return QualType();
6284   }
6285 
6286   // Neither is void.
6287   if (IsVectorConditional)
6288     return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6289 
6290   // C++11 [expr.cond]p3
6291   //   Otherwise, if the second and third operand have different types, and
6292   //   either has (cv) class type [...] an attempt is made to convert each of
6293   //   those operands to the type of the other.
6294   if (!Context.hasSameType(LTy, RTy) &&
6295       (LTy->isRecordType() || RTy->isRecordType())) {
6296     // These return true if a single direction is already ambiguous.
6297     QualType L2RType, R2LType;
6298     bool HaveL2R, HaveR2L;
6299     if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
6300       return QualType();
6301     if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
6302       return QualType();
6303 
6304     //   If both can be converted, [...] the program is ill-formed.
6305     if (HaveL2R && HaveR2L) {
6306       Diag(QuestionLoc, diag::err_conditional_ambiguous)
6307         << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6308       return QualType();
6309     }
6310 
6311     //   If exactly one conversion is possible, that conversion is applied to
6312     //   the chosen operand and the converted operands are used in place of the
6313     //   original operands for the remainder of this section.
6314     if (HaveL2R) {
6315       if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
6316         return QualType();
6317       LTy = LHS.get()->getType();
6318     } else if (HaveR2L) {
6319       if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
6320         return QualType();
6321       RTy = RHS.get()->getType();
6322     }
6323   }
6324 
6325   // C++11 [expr.cond]p3
6326   //   if both are glvalues of the same value category and the same type except
6327   //   for cv-qualification, an attempt is made to convert each of those
6328   //   operands to the type of the other.
6329   // FIXME:
6330   //   Resolving a defect in P0012R1: we extend this to cover all cases where
6331   //   one of the operands is reference-compatible with the other, in order
6332   //   to support conditionals between functions differing in noexcept. This
6333   //   will similarly cover difference in array bounds after P0388R4.
6334   // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6335   //   that instead?
6336   ExprValueKind LVK = LHS.get()->getValueKind();
6337   ExprValueKind RVK = RHS.get()->getValueKind();
6338   if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
6339     // DerivedToBase was already handled by the class-specific case above.
6340     // FIXME: Should we allow ObjC conversions here?
6341     const ReferenceConversions AllowedConversions =
6342         ReferenceConversions::Qualification |
6343         ReferenceConversions::NestedQualification |
6344         ReferenceConversions::Function;
6345 
6346     ReferenceConversions RefConv;
6347     if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6348             Ref_Compatible &&
6349         !(RefConv & ~AllowedConversions) &&
6350         // [...] subject to the constraint that the reference must bind
6351         // directly [...]
6352         !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6353       RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6354       RTy = RHS.get()->getType();
6355     } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6356                    Ref_Compatible &&
6357                !(RefConv & ~AllowedConversions) &&
6358                !LHS.get()->refersToBitField() &&
6359                !LHS.get()->refersToVectorElement()) {
6360       LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6361       LTy = LHS.get()->getType();
6362     }
6363   }
6364 
6365   // C++11 [expr.cond]p4
6366   //   If the second and third operands are glvalues of the same value
6367   //   category and have the same type, the result is of that type and
6368   //   value category and it is a bit-field if the second or the third
6369   //   operand is a bit-field, or if both are bit-fields.
6370   // We only extend this to bitfields, not to the crazy other kinds of
6371   // l-values.
6372   bool Same = Context.hasSameType(LTy, RTy);
6373   if (Same && LVK == RVK && LVK != VK_PRValue &&
6374       LHS.get()->isOrdinaryOrBitFieldObject() &&
6375       RHS.get()->isOrdinaryOrBitFieldObject()) {
6376     VK = LHS.get()->getValueKind();
6377     if (LHS.get()->getObjectKind() == OK_BitField ||
6378         RHS.get()->getObjectKind() == OK_BitField)
6379       OK = OK_BitField;
6380 
6381     // If we have function pointer types, unify them anyway to unify their
6382     // exception specifications, if any.
6383     if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
6384       Qualifiers Qs = LTy.getQualifiers();
6385       LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
6386                                      /*ConvertArgs*/false);
6387       LTy = Context.getQualifiedType(LTy, Qs);
6388 
6389       assert(!LTy.isNull() && "failed to find composite pointer type for "
6390                               "canonically equivalent function ptr types");
6391       assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
6392     }
6393 
6394     return LTy;
6395   }
6396 
6397   // C++11 [expr.cond]p5
6398   //   Otherwise, the result is a prvalue. If the second and third operands
6399   //   do not have the same type, and either has (cv) class type, ...
6400   if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6401     //   ... overload resolution is used to determine the conversions (if any)
6402     //   to be applied to the operands. If the overload resolution fails, the
6403     //   program is ill-formed.
6404     if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
6405       return QualType();
6406   }
6407 
6408   // C++11 [expr.cond]p6
6409   //   Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
6410   //   conversions are performed on the second and third operands.
6411   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6412   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6413   if (LHS.isInvalid() || RHS.isInvalid())
6414     return QualType();
6415   LTy = LHS.get()->getType();
6416   RTy = RHS.get()->getType();
6417 
6418   //   After those conversions, one of the following shall hold:
6419   //   -- The second and third operands have the same type; the result
6420   //      is of that type. If the operands have class type, the result
6421   //      is a prvalue temporary of the result type, which is
6422   //      copy-initialized from either the second operand or the third
6423   //      operand depending on the value of the first operand.
6424   if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
6425     if (LTy->isRecordType()) {
6426       // The operands have class type. Make a temporary copy.
6427       InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
6428 
6429       ExprResult LHSCopy = PerformCopyInitialization(Entity,
6430                                                      SourceLocation(),
6431                                                      LHS);
6432       if (LHSCopy.isInvalid())
6433         return QualType();
6434 
6435       ExprResult RHSCopy = PerformCopyInitialization(Entity,
6436                                                      SourceLocation(),
6437                                                      RHS);
6438       if (RHSCopy.isInvalid())
6439         return QualType();
6440 
6441       LHS = LHSCopy;
6442       RHS = RHSCopy;
6443     }
6444 
6445     // If we have function pointer types, unify them anyway to unify their
6446     // exception specifications, if any.
6447     if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
6448       LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
6449       assert(!LTy.isNull() && "failed to find composite pointer type for "
6450                               "canonically equivalent function ptr types");
6451     }
6452 
6453     return LTy;
6454   }
6455 
6456   // Extension: conditional operator involving vector types.
6457   if (LTy->isVectorType() || RTy->isVectorType())
6458     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6459                                /*AllowBothBool*/true,
6460                                /*AllowBoolConversions*/false);
6461 
6462   //   -- The second and third operands have arithmetic or enumeration type;
6463   //      the usual arithmetic conversions are performed to bring them to a
6464   //      common type, and the result is of that type.
6465   if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
6466     QualType ResTy =
6467         UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6468     if (LHS.isInvalid() || RHS.isInvalid())
6469       return QualType();
6470     if (ResTy.isNull()) {
6471       Diag(QuestionLoc,
6472            diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
6473         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6474       return QualType();
6475     }
6476 
6477     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6478     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6479 
6480     return ResTy;
6481   }
6482 
6483   //   -- The second and third operands have pointer type, or one has pointer
6484   //      type and the other is a null pointer constant, or both are null
6485   //      pointer constants, at least one of which is non-integral; pointer
6486   //      conversions and qualification conversions are performed to bring them
6487   //      to their composite pointer type. The result is of the composite
6488   //      pointer type.
6489   //   -- The second and third operands have pointer to member type, or one has
6490   //      pointer to member type and the other is a null pointer constant;
6491   //      pointer to member conversions and qualification conversions are
6492   //      performed to bring them to a common type, whose cv-qualification
6493   //      shall match the cv-qualification of either the second or the third
6494   //      operand. The result is of the common type.
6495   QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
6496   if (!Composite.isNull())
6497     return Composite;
6498 
6499   // Similarly, attempt to find composite type of two objective-c pointers.
6500   Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6501   if (LHS.isInvalid() || RHS.isInvalid())
6502     return QualType();
6503   if (!Composite.isNull())
6504     return Composite;
6505 
6506   // Check if we are using a null with a non-pointer type.
6507   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6508     return QualType();
6509 
6510   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6511     << LHS.get()->getType() << RHS.get()->getType()
6512     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6513   return QualType();
6514 }
6515 
6516 static FunctionProtoType::ExceptionSpecInfo
6517 mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
6518                     FunctionProtoType::ExceptionSpecInfo ESI2,
6519                     SmallVectorImpl<QualType> &ExceptionTypeStorage) {
6520   ExceptionSpecificationType EST1 = ESI1.Type;
6521   ExceptionSpecificationType EST2 = ESI2.Type;
6522 
6523   // If either of them can throw anything, that is the result.
6524   if (EST1 == EST_None) return ESI1;
6525   if (EST2 == EST_None) return ESI2;
6526   if (EST1 == EST_MSAny) return ESI1;
6527   if (EST2 == EST_MSAny) return ESI2;
6528   if (EST1 == EST_NoexceptFalse) return ESI1;
6529   if (EST2 == EST_NoexceptFalse) return ESI2;
6530 
6531   // If either of them is non-throwing, the result is the other.
6532   if (EST1 == EST_NoThrow) return ESI2;
6533   if (EST2 == EST_NoThrow) return ESI1;
6534   if (EST1 == EST_DynamicNone) return ESI2;
6535   if (EST2 == EST_DynamicNone) return ESI1;
6536   if (EST1 == EST_BasicNoexcept) return ESI2;
6537   if (EST2 == EST_BasicNoexcept) return ESI1;
6538   if (EST1 == EST_NoexceptTrue) return ESI2;
6539   if (EST2 == EST_NoexceptTrue) return ESI1;
6540 
6541   // If we're left with value-dependent computed noexcept expressions, we're
6542   // stuck. Before C++17, we can just drop the exception specification entirely,
6543   // since it's not actually part of the canonical type. And this should never
6544   // happen in C++17, because it would mean we were computing the composite
6545   // pointer type of dependent types, which should never happen.
6546   if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
6547     assert(!S.getLangOpts().CPlusPlus17 &&
6548            "computing composite pointer type of dependent types");
6549     return FunctionProtoType::ExceptionSpecInfo();
6550   }
6551 
6552   // Switch over the possibilities so that people adding new values know to
6553   // update this function.
6554   switch (EST1) {
6555   case EST_None:
6556   case EST_DynamicNone:
6557   case EST_MSAny:
6558   case EST_BasicNoexcept:
6559   case EST_DependentNoexcept:
6560   case EST_NoexceptFalse:
6561   case EST_NoexceptTrue:
6562   case EST_NoThrow:
6563     llvm_unreachable("handled above");
6564 
6565   case EST_Dynamic: {
6566     // This is the fun case: both exception specifications are dynamic. Form
6567     // the union of the two lists.
6568     assert(EST2 == EST_Dynamic && "other cases should already be handled");
6569     llvm::SmallPtrSet<QualType, 8> Found;
6570     for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6571       for (QualType E : Exceptions)
6572         if (Found.insert(S.Context.getCanonicalType(E)).second)
6573           ExceptionTypeStorage.push_back(E);
6574 
6575     FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6576     Result.Exceptions = ExceptionTypeStorage;
6577     return Result;
6578   }
6579 
6580   case EST_Unevaluated:
6581   case EST_Uninstantiated:
6582   case EST_Unparsed:
6583     llvm_unreachable("shouldn't see unresolved exception specifications here");
6584   }
6585 
6586   llvm_unreachable("invalid ExceptionSpecificationType");
6587 }
6588 
6589 /// Find a merged pointer type and convert the two expressions to it.
6590 ///
6591 /// This finds the composite pointer type for \p E1 and \p E2 according to
6592 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
6593 /// it.  It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs
6594 /// is \c true).
6595 ///
6596 /// \param Loc The location of the operator requiring these two expressions to
6597 /// be converted to the composite pointer type.
6598 ///
6599 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
6600 QualType Sema::FindCompositePointerType(SourceLocation Loc,
6601                                         Expr *&E1, Expr *&E2,
6602                                         bool ConvertArgs) {
6603   assert(getLangOpts().CPlusPlus && "This function assumes C++");
6604 
6605   // C++1z [expr]p14:
6606   //   The composite pointer type of two operands p1 and p2 having types T1
6607   //   and T2
6608   QualType T1 = E1->getType(), T2 = E2->getType();
6609 
6610   //   where at least one is a pointer or pointer to member type or
6611   //   std::nullptr_t is:
6612   bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6613                          T1->isNullPtrType();
6614   bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6615                          T2->isNullPtrType();
6616   if (!T1IsPointerLike && !T2IsPointerLike)
6617     return QualType();
6618 
6619   //   - if both p1 and p2 are null pointer constants, std::nullptr_t;
6620   // This can't actually happen, following the standard, but we also use this
6621   // to implement the end of [expr.conv], which hits this case.
6622   //
6623   //   - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6624   if (T1IsPointerLike &&
6625       E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6626     if (ConvertArgs)
6627       E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6628                                          ? CK_NullToMemberPointer
6629                                          : CK_NullToPointer).get();
6630     return T1;
6631   }
6632   if (T2IsPointerLike &&
6633       E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6634     if (ConvertArgs)
6635       E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6636                                          ? CK_NullToMemberPointer
6637                                          : CK_NullToPointer).get();
6638     return T2;
6639   }
6640 
6641   // Now both have to be pointers or member pointers.
6642   if (!T1IsPointerLike || !T2IsPointerLike)
6643     return QualType();
6644   assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6645          "nullptr_t should be a null pointer constant");
6646 
6647   struct Step {
6648     enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
6649     // Qualifiers to apply under the step kind.
6650     Qualifiers Quals;
6651     /// The class for a pointer-to-member; a constant array type with a bound
6652     /// (if any) for an array.
6653     const Type *ClassOrBound;
6654 
6655     Step(Kind K, const Type *ClassOrBound = nullptr)
6656         : K(K), ClassOrBound(ClassOrBound) {}
6657     QualType rebuild(ASTContext &Ctx, QualType T) const {
6658       T = Ctx.getQualifiedType(T, Quals);
6659       switch (K) {
6660       case Pointer:
6661         return Ctx.getPointerType(T);
6662       case MemberPointer:
6663         return Ctx.getMemberPointerType(T, ClassOrBound);
6664       case ObjCPointer:
6665         return Ctx.getObjCObjectPointerType(T);
6666       case Array:
6667         if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
6668           return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
6669                                           ArrayType::Normal, 0);
6670         else
6671           return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0);
6672       }
6673       llvm_unreachable("unknown step kind");
6674     }
6675   };
6676 
6677   SmallVector<Step, 8> Steps;
6678 
6679   //  - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6680   //    is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6681   //    the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6682   //    respectively;
6683   //  - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6684   //    to member of C2 of type cv2 U2" for some non-function type U, where
6685   //    C1 is reference-related to C2 or C2 is reference-related to C1, the
6686   //    cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6687   //    respectively;
6688   //  - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6689   //    T2;
6690   //
6691   // Dismantle T1 and T2 to simultaneously determine whether they are similar
6692   // and to prepare to form the cv-combined type if so.
6693   QualType Composite1 = T1;
6694   QualType Composite2 = T2;
6695   unsigned NeedConstBefore = 0;
6696   while (true) {
6697     assert(!Composite1.isNull() && !Composite2.isNull());
6698 
6699     Qualifiers Q1, Q2;
6700     Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
6701     Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
6702 
6703     // Top-level qualifiers are ignored. Merge at all lower levels.
6704     if (!Steps.empty()) {
6705       // Find the qualifier union: (approximately) the unique minimal set of
6706       // qualifiers that is compatible with both types.
6707       Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() |
6708                                                   Q2.getCVRUQualifiers());
6709 
6710       // Under one level of pointer or pointer-to-member, we can change to an
6711       // unambiguous compatible address space.
6712       if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
6713         Quals.setAddressSpace(Q1.getAddressSpace());
6714       } else if (Steps.size() == 1) {
6715         bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
6716         bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
6717         if (MaybeQ1 == MaybeQ2) {
6718           // Exception for ptr size address spaces. Should be able to choose
6719           // either address space during comparison.
6720           if (isPtrSizeAddressSpace(Q1.getAddressSpace()) ||
6721               isPtrSizeAddressSpace(Q2.getAddressSpace()))
6722             MaybeQ1 = true;
6723           else
6724             return QualType(); // No unique best address space.
6725         }
6726         Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
6727                                       : Q2.getAddressSpace());
6728       } else {
6729         return QualType();
6730       }
6731 
6732       // FIXME: In C, we merge __strong and none to __strong at the top level.
6733       if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
6734         Quals.setObjCGCAttr(Q1.getObjCGCAttr());
6735       else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6736         assert(Steps.size() == 1);
6737       else
6738         return QualType();
6739 
6740       // Mismatched lifetime qualifiers never compatibly include each other.
6741       if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
6742         Quals.setObjCLifetime(Q1.getObjCLifetime());
6743       else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6744         assert(Steps.size() == 1);
6745       else
6746         return QualType();
6747 
6748       Steps.back().Quals = Quals;
6749       if (Q1 != Quals || Q2 != Quals)
6750         NeedConstBefore = Steps.size() - 1;
6751     }
6752 
6753     // FIXME: Can we unify the following with UnwrapSimilarTypes?
6754 
6755     const ArrayType *Arr1, *Arr2;
6756     if ((Arr1 = Context.getAsArrayType(Composite1)) &&
6757         (Arr2 = Context.getAsArrayType(Composite2))) {
6758       auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
6759       auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
6760       if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
6761         Composite1 = Arr1->getElementType();
6762         Composite2 = Arr2->getElementType();
6763         Steps.emplace_back(Step::Array, CAT1);
6764         continue;
6765       }
6766       bool IAT1 = isa<IncompleteArrayType>(Arr1);
6767       bool IAT2 = isa<IncompleteArrayType>(Arr2);
6768       if ((IAT1 && IAT2) ||
6769           (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
6770            ((bool)CAT1 != (bool)CAT2) &&
6771            (Steps.empty() || Steps.back().K != Step::Array))) {
6772         // In C++20 onwards, we can unify an array of N T with an array of
6773         // a different or unknown bound. But we can't form an array whose
6774         // element type is an array of unknown bound by doing so.
6775         Composite1 = Arr1->getElementType();
6776         Composite2 = Arr2->getElementType();
6777         Steps.emplace_back(Step::Array);
6778         if (CAT1 || CAT2)
6779           NeedConstBefore = Steps.size();
6780         continue;
6781       }
6782     }
6783 
6784     const PointerType *Ptr1, *Ptr2;
6785     if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6786         (Ptr2 = Composite2->getAs<PointerType>())) {
6787       Composite1 = Ptr1->getPointeeType();
6788       Composite2 = Ptr2->getPointeeType();
6789       Steps.emplace_back(Step::Pointer);
6790       continue;
6791     }
6792 
6793     const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
6794     if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
6795         (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
6796       Composite1 = ObjPtr1->getPointeeType();
6797       Composite2 = ObjPtr2->getPointeeType();
6798       Steps.emplace_back(Step::ObjCPointer);
6799       continue;
6800     }
6801 
6802     const MemberPointerType *MemPtr1, *MemPtr2;
6803     if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6804         (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6805       Composite1 = MemPtr1->getPointeeType();
6806       Composite2 = MemPtr2->getPointeeType();
6807 
6808       // At the top level, we can perform a base-to-derived pointer-to-member
6809       // conversion:
6810       //
6811       //  - [...] where C1 is reference-related to C2 or C2 is
6812       //    reference-related to C1
6813       //
6814       // (Note that the only kinds of reference-relatedness in scope here are
6815       // "same type or derived from".) At any other level, the class must
6816       // exactly match.
6817       const Type *Class = nullptr;
6818       QualType Cls1(MemPtr1->getClass(), 0);
6819       QualType Cls2(MemPtr2->getClass(), 0);
6820       if (Context.hasSameType(Cls1, Cls2))
6821         Class = MemPtr1->getClass();
6822       else if (Steps.empty())
6823         Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
6824                 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
6825       if (!Class)
6826         return QualType();
6827 
6828       Steps.emplace_back(Step::MemberPointer, Class);
6829       continue;
6830     }
6831 
6832     // Special case: at the top level, we can decompose an Objective-C pointer
6833     // and a 'cv void *'. Unify the qualifiers.
6834     if (Steps.empty() && ((Composite1->isVoidPointerType() &&
6835                            Composite2->isObjCObjectPointerType()) ||
6836                           (Composite1->isObjCObjectPointerType() &&
6837                            Composite2->isVoidPointerType()))) {
6838       Composite1 = Composite1->getPointeeType();
6839       Composite2 = Composite2->getPointeeType();
6840       Steps.emplace_back(Step::Pointer);
6841       continue;
6842     }
6843 
6844     // FIXME: block pointer types?
6845 
6846     // Cannot unwrap any more types.
6847     break;
6848   }
6849 
6850   //  - if T1 or T2 is "pointer to noexcept function" and the other type is
6851   //    "pointer to function", where the function types are otherwise the same,
6852   //    "pointer to function";
6853   //  - if T1 or T2 is "pointer to member of C1 of type function", the other
6854   //    type is "pointer to member of C2 of type noexcept function", and C1
6855   //    is reference-related to C2 or C2 is reference-related to C1, where
6856   //    the function types are otherwise the same, "pointer to member of C2 of
6857   //    type function" or "pointer to member of C1 of type function",
6858   //    respectively;
6859   //
6860   // We also support 'noreturn' here, so as a Clang extension we generalize the
6861   // above to:
6862   //
6863   //  - [Clang] If T1 and T2 are both of type "pointer to function" or
6864   //    "pointer to member function" and the pointee types can be unified
6865   //    by a function pointer conversion, that conversion is applied
6866   //    before checking the following rules.
6867   //
6868   // We've already unwrapped down to the function types, and we want to merge
6869   // rather than just convert, so do this ourselves rather than calling
6870   // IsFunctionConversion.
6871   //
6872   // FIXME: In order to match the standard wording as closely as possible, we
6873   // currently only do this under a single level of pointers. Ideally, we would
6874   // allow this in general, and set NeedConstBefore to the relevant depth on
6875   // the side(s) where we changed anything. If we permit that, we should also
6876   // consider this conversion when determining type similarity and model it as
6877   // a qualification conversion.
6878   if (Steps.size() == 1) {
6879     if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6880       if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6881         FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6882         FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6883 
6884         // The result is noreturn if both operands are.
6885         bool Noreturn =
6886             EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6887         EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6888         EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6889 
6890         // The result is nothrow if both operands are.
6891         SmallVector<QualType, 8> ExceptionTypeStorage;
6892         EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6893             mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6894                                 ExceptionTypeStorage);
6895 
6896         Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6897                                              FPT1->getParamTypes(), EPI1);
6898         Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6899                                              FPT2->getParamTypes(), EPI2);
6900       }
6901     }
6902   }
6903 
6904   // There are some more conversions we can perform under exactly one pointer.
6905   if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
6906       !Context.hasSameType(Composite1, Composite2)) {
6907     //  - if T1 or T2 is "pointer to cv1 void" and the other type is
6908     //    "pointer to cv2 T", where T is an object type or void,
6909     //    "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
6910     if (Composite1->isVoidType() && Composite2->isObjectType())
6911       Composite2 = Composite1;
6912     else if (Composite2->isVoidType() && Composite1->isObjectType())
6913       Composite1 = Composite2;
6914     //  - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6915     //    is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6916     //    the cv-combined type of T1 and T2 or the cv-combined type of T2 and
6917     //    T1, respectively;
6918     //
6919     // The "similar type" handling covers all of this except for the "T1 is a
6920     // base class of T2" case in the definition of reference-related.
6921     else if (IsDerivedFrom(Loc, Composite1, Composite2))
6922       Composite1 = Composite2;
6923     else if (IsDerivedFrom(Loc, Composite2, Composite1))
6924       Composite2 = Composite1;
6925   }
6926 
6927   // At this point, either the inner types are the same or we have failed to
6928   // find a composite pointer type.
6929   if (!Context.hasSameType(Composite1, Composite2))
6930     return QualType();
6931 
6932   // Per C++ [conv.qual]p3, add 'const' to every level before the last
6933   // differing qualifier.
6934   for (unsigned I = 0; I != NeedConstBefore; ++I)
6935     Steps[I].Quals.addConst();
6936 
6937   // Rebuild the composite type.
6938   QualType Composite = Composite1;
6939   for (auto &S : llvm::reverse(Steps))
6940     Composite = S.rebuild(Context, Composite);
6941 
6942   if (ConvertArgs) {
6943     // Convert the expressions to the composite pointer type.
6944     InitializedEntity Entity =
6945         InitializedEntity::InitializeTemporary(Composite);
6946     InitializationKind Kind =
6947         InitializationKind::CreateCopy(Loc, SourceLocation());
6948 
6949     InitializationSequence E1ToC(*this, Entity, Kind, E1);
6950     if (!E1ToC)
6951       return QualType();
6952 
6953     InitializationSequence E2ToC(*this, Entity, Kind, E2);
6954     if (!E2ToC)
6955       return QualType();
6956 
6957     // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
6958     ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
6959     if (E1Result.isInvalid())
6960       return QualType();
6961     E1 = E1Result.get();
6962 
6963     ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
6964     if (E2Result.isInvalid())
6965       return QualType();
6966     E2 = E2Result.get();
6967   }
6968 
6969   return Composite;
6970 }
6971 
6972 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
6973   if (!E)
6974     return ExprError();
6975 
6976   assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6977 
6978   // If the result is a glvalue, we shouldn't bind it.
6979   if (E->isGLValue())
6980     return E;
6981 
6982   // In ARC, calls that return a retainable type can return retained,
6983   // in which case we have to insert a consuming cast.
6984   if (getLangOpts().ObjCAutoRefCount &&
6985       E->getType()->isObjCRetainableType()) {
6986 
6987     bool ReturnsRetained;
6988 
6989     // For actual calls, we compute this by examining the type of the
6990     // called value.
6991     if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6992       Expr *Callee = Call->getCallee()->IgnoreParens();
6993       QualType T = Callee->getType();
6994 
6995       if (T == Context.BoundMemberTy) {
6996         // Handle pointer-to-members.
6997         if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6998           T = BinOp->getRHS()->getType();
6999         else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
7000           T = Mem->getMemberDecl()->getType();
7001       }
7002 
7003       if (const PointerType *Ptr = T->getAs<PointerType>())
7004         T = Ptr->getPointeeType();
7005       else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
7006         T = Ptr->getPointeeType();
7007       else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
7008         T = MemPtr->getPointeeType();
7009 
7010       auto *FTy = T->castAs<FunctionType>();
7011       ReturnsRetained = FTy->getExtInfo().getProducesResult();
7012 
7013     // ActOnStmtExpr arranges things so that StmtExprs of retainable
7014     // type always produce a +1 object.
7015     } else if (isa<StmtExpr>(E)) {
7016       ReturnsRetained = true;
7017 
7018     // We hit this case with the lambda conversion-to-block optimization;
7019     // we don't want any extra casts here.
7020     } else if (isa<CastExpr>(E) &&
7021                isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
7022       return E;
7023 
7024     // For message sends and property references, we try to find an
7025     // actual method.  FIXME: we should infer retention by selector in
7026     // cases where we don't have an actual method.
7027     } else {
7028       ObjCMethodDecl *D = nullptr;
7029       if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
7030         D = Send->getMethodDecl();
7031       } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
7032         D = BoxedExpr->getBoxingMethod();
7033       } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
7034         // Don't do reclaims if we're using the zero-element array
7035         // constant.
7036         if (ArrayLit->getNumElements() == 0 &&
7037             Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
7038           return E;
7039 
7040         D = ArrayLit->getArrayWithObjectsMethod();
7041       } else if (ObjCDictionaryLiteral *DictLit
7042                                         = dyn_cast<ObjCDictionaryLiteral>(E)) {
7043         // Don't do reclaims if we're using the zero-element dictionary
7044         // constant.
7045         if (DictLit->getNumElements() == 0 &&
7046             Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
7047           return E;
7048 
7049         D = DictLit->getDictWithObjectsMethod();
7050       }
7051 
7052       ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
7053 
7054       // Don't do reclaims on performSelector calls; despite their
7055       // return type, the invoked method doesn't necessarily actually
7056       // return an object.
7057       if (!ReturnsRetained &&
7058           D && D->getMethodFamily() == OMF_performSelector)
7059         return E;
7060     }
7061 
7062     // Don't reclaim an object of Class type.
7063     if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
7064       return E;
7065 
7066     Cleanup.setExprNeedsCleanups(true);
7067 
7068     CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
7069                                    : CK_ARCReclaimReturnedObject);
7070     return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
7071                                     VK_PRValue, FPOptionsOverride());
7072   }
7073 
7074   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
7075     Cleanup.setExprNeedsCleanups(true);
7076 
7077   if (!getLangOpts().CPlusPlus)
7078     return E;
7079 
7080   // Search for the base element type (cf. ASTContext::getBaseElementType) with
7081   // a fast path for the common case that the type is directly a RecordType.
7082   const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
7083   const RecordType *RT = nullptr;
7084   while (!RT) {
7085     switch (T->getTypeClass()) {
7086     case Type::Record:
7087       RT = cast<RecordType>(T);
7088       break;
7089     case Type::ConstantArray:
7090     case Type::IncompleteArray:
7091     case Type::VariableArray:
7092     case Type::DependentSizedArray:
7093       T = cast<ArrayType>(T)->getElementType().getTypePtr();
7094       break;
7095     default:
7096       return E;
7097     }
7098   }
7099 
7100   // That should be enough to guarantee that this type is complete, if we're
7101   // not processing a decltype expression.
7102   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7103   if (RD->isInvalidDecl() || RD->isDependentContext())
7104     return E;
7105 
7106   bool IsDecltype = ExprEvalContexts.back().ExprContext ==
7107                     ExpressionEvaluationContextRecord::EK_Decltype;
7108   CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
7109 
7110   if (Destructor) {
7111     MarkFunctionReferenced(E->getExprLoc(), Destructor);
7112     CheckDestructorAccess(E->getExprLoc(), Destructor,
7113                           PDiag(diag::err_access_dtor_temp)
7114                             << E->getType());
7115     if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
7116       return ExprError();
7117 
7118     // If destructor is trivial, we can avoid the extra copy.
7119     if (Destructor->isTrivial())
7120       return E;
7121 
7122     // We need a cleanup, but we don't need to remember the temporary.
7123     Cleanup.setExprNeedsCleanups(true);
7124   }
7125 
7126   CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
7127   CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
7128 
7129   if (IsDecltype)
7130     ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
7131 
7132   return Bind;
7133 }
7134 
7135 ExprResult
7136 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
7137   if (SubExpr.isInvalid())
7138     return ExprError();
7139 
7140   return MaybeCreateExprWithCleanups(SubExpr.get());
7141 }
7142 
7143 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
7144   assert(SubExpr && "subexpression can't be null!");
7145 
7146   CleanupVarDeclMarking();
7147 
7148   unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
7149   assert(ExprCleanupObjects.size() >= FirstCleanup);
7150   assert(Cleanup.exprNeedsCleanups() ||
7151          ExprCleanupObjects.size() == FirstCleanup);
7152   if (!Cleanup.exprNeedsCleanups())
7153     return SubExpr;
7154 
7155   auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
7156                                      ExprCleanupObjects.size() - FirstCleanup);
7157 
7158   auto *E = ExprWithCleanups::Create(
7159       Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
7160   DiscardCleanupsInEvaluationContext();
7161 
7162   return E;
7163 }
7164 
7165 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
7166   assert(SubStmt && "sub-statement can't be null!");
7167 
7168   CleanupVarDeclMarking();
7169 
7170   if (!Cleanup.exprNeedsCleanups())
7171     return SubStmt;
7172 
7173   // FIXME: In order to attach the temporaries, wrap the statement into
7174   // a StmtExpr; currently this is only used for asm statements.
7175   // This is hacky, either create a new CXXStmtWithTemporaries statement or
7176   // a new AsmStmtWithTemporaries.
7177   CompoundStmt *CompStmt = CompoundStmt::Create(
7178       Context, SubStmt, SourceLocation(), SourceLocation());
7179   Expr *E = new (Context)
7180       StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),
7181                /*FIXME TemplateDepth=*/0);
7182   return MaybeCreateExprWithCleanups(E);
7183 }
7184 
7185 /// Process the expression contained within a decltype. For such expressions,
7186 /// certain semantic checks on temporaries are delayed until this point, and
7187 /// are omitted for the 'topmost' call in the decltype expression. If the
7188 /// topmost call bound a temporary, strip that temporary off the expression.
7189 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
7190   assert(ExprEvalContexts.back().ExprContext ==
7191              ExpressionEvaluationContextRecord::EK_Decltype &&
7192          "not in a decltype expression");
7193 
7194   ExprResult Result = CheckPlaceholderExpr(E);
7195   if (Result.isInvalid())
7196     return ExprError();
7197   E = Result.get();
7198 
7199   // C++11 [expr.call]p11:
7200   //   If a function call is a prvalue of object type,
7201   // -- if the function call is either
7202   //   -- the operand of a decltype-specifier, or
7203   //   -- the right operand of a comma operator that is the operand of a
7204   //      decltype-specifier,
7205   //   a temporary object is not introduced for the prvalue.
7206 
7207   // Recursively rebuild ParenExprs and comma expressions to strip out the
7208   // outermost CXXBindTemporaryExpr, if any.
7209   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7210     ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
7211     if (SubExpr.isInvalid())
7212       return ExprError();
7213     if (SubExpr.get() == PE->getSubExpr())
7214       return E;
7215     return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
7216   }
7217   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7218     if (BO->getOpcode() == BO_Comma) {
7219       ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
7220       if (RHS.isInvalid())
7221         return ExprError();
7222       if (RHS.get() == BO->getRHS())
7223         return E;
7224       return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
7225                                     BO->getType(), BO->getValueKind(),
7226                                     BO->getObjectKind(), BO->getOperatorLoc(),
7227                                     BO->getFPFeatures(getLangOpts()));
7228     }
7229   }
7230 
7231   CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
7232   CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
7233                               : nullptr;
7234   if (TopCall)
7235     E = TopCall;
7236   else
7237     TopBind = nullptr;
7238 
7239   // Disable the special decltype handling now.
7240   ExprEvalContexts.back().ExprContext =
7241       ExpressionEvaluationContextRecord::EK_Other;
7242 
7243   Result = CheckUnevaluatedOperand(E);
7244   if (Result.isInvalid())
7245     return ExprError();
7246   E = Result.get();
7247 
7248   // In MS mode, don't perform any extra checking of call return types within a
7249   // decltype expression.
7250   if (getLangOpts().MSVCCompat)
7251     return E;
7252 
7253   // Perform the semantic checks we delayed until this point.
7254   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
7255        I != N; ++I) {
7256     CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
7257     if (Call == TopCall)
7258       continue;
7259 
7260     if (CheckCallReturnType(Call->getCallReturnType(Context),
7261                             Call->getBeginLoc(), Call, Call->getDirectCallee()))
7262       return ExprError();
7263   }
7264 
7265   // Now all relevant types are complete, check the destructors are accessible
7266   // and non-deleted, and annotate them on the temporaries.
7267   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7268        I != N; ++I) {
7269     CXXBindTemporaryExpr *Bind =
7270       ExprEvalContexts.back().DelayedDecltypeBinds[I];
7271     if (Bind == TopBind)
7272       continue;
7273 
7274     CXXTemporary *Temp = Bind->getTemporary();
7275 
7276     CXXRecordDecl *RD =
7277       Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7278     CXXDestructorDecl *Destructor = LookupDestructor(RD);
7279     Temp->setDestructor(Destructor);
7280 
7281     MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7282     CheckDestructorAccess(Bind->getExprLoc(), Destructor,
7283                           PDiag(diag::err_access_dtor_temp)
7284                             << Bind->getType());
7285     if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7286       return ExprError();
7287 
7288     // We need a cleanup, but we don't need to remember the temporary.
7289     Cleanup.setExprNeedsCleanups(true);
7290   }
7291 
7292   // Possibly strip off the top CXXBindTemporaryExpr.
7293   return E;
7294 }
7295 
7296 /// Note a set of 'operator->' functions that were used for a member access.
7297 static void noteOperatorArrows(Sema &S,
7298                                ArrayRef<FunctionDecl *> OperatorArrows) {
7299   unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7300   // FIXME: Make this configurable?
7301   unsigned Limit = 9;
7302   if (OperatorArrows.size() > Limit) {
7303     // Produce Limit-1 normal notes and one 'skipping' note.
7304     SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7305     SkipCount = OperatorArrows.size() - (Limit - 1);
7306   }
7307 
7308   for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7309     if (I == SkipStart) {
7310       S.Diag(OperatorArrows[I]->getLocation(),
7311              diag::note_operator_arrows_suppressed)
7312           << SkipCount;
7313       I += SkipCount;
7314     } else {
7315       S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7316           << OperatorArrows[I]->getCallResultType();
7317       ++I;
7318     }
7319   }
7320 }
7321 
7322 ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
7323                                               SourceLocation OpLoc,
7324                                               tok::TokenKind OpKind,
7325                                               ParsedType &ObjectType,
7326                                               bool &MayBePseudoDestructor) {
7327   // Since this might be a postfix expression, get rid of ParenListExprs.
7328   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
7329   if (Result.isInvalid()) return ExprError();
7330   Base = Result.get();
7331 
7332   Result = CheckPlaceholderExpr(Base);
7333   if (Result.isInvalid()) return ExprError();
7334   Base = Result.get();
7335 
7336   QualType BaseType = Base->getType();
7337   MayBePseudoDestructor = false;
7338   if (BaseType->isDependentType()) {
7339     // If we have a pointer to a dependent type and are using the -> operator,
7340     // the object type is the type that the pointer points to. We might still
7341     // have enough information about that type to do something useful.
7342     if (OpKind == tok::arrow)
7343       if (const PointerType *Ptr = BaseType->getAs<PointerType>())
7344         BaseType = Ptr->getPointeeType();
7345 
7346     ObjectType = ParsedType::make(BaseType);
7347     MayBePseudoDestructor = true;
7348     return Base;
7349   }
7350 
7351   // C++ [over.match.oper]p8:
7352   //   [...] When operator->returns, the operator-> is applied  to the value
7353   //   returned, with the original second operand.
7354   if (OpKind == tok::arrow) {
7355     QualType StartingType = BaseType;
7356     bool NoArrowOperatorFound = false;
7357     bool FirstIteration = true;
7358     FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
7359     // The set of types we've considered so far.
7360     llvm::SmallPtrSet<CanQualType,8> CTypes;
7361     SmallVector<FunctionDecl*, 8> OperatorArrows;
7362     CTypes.insert(Context.getCanonicalType(BaseType));
7363 
7364     while (BaseType->isRecordType()) {
7365       if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
7366         Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
7367           << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
7368         noteOperatorArrows(*this, OperatorArrows);
7369         Diag(OpLoc, diag::note_operator_arrow_depth)
7370           << getLangOpts().ArrowDepth;
7371         return ExprError();
7372       }
7373 
7374       Result = BuildOverloadedArrowExpr(
7375           S, Base, OpLoc,
7376           // When in a template specialization and on the first loop iteration,
7377           // potentially give the default diagnostic (with the fixit in a
7378           // separate note) instead of having the error reported back to here
7379           // and giving a diagnostic with a fixit attached to the error itself.
7380           (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7381               ? nullptr
7382               : &NoArrowOperatorFound);
7383       if (Result.isInvalid()) {
7384         if (NoArrowOperatorFound) {
7385           if (FirstIteration) {
7386             Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7387               << BaseType << 1 << Base->getSourceRange()
7388               << FixItHint::CreateReplacement(OpLoc, ".");
7389             OpKind = tok::period;
7390             break;
7391           }
7392           Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7393             << BaseType << Base->getSourceRange();
7394           CallExpr *CE = dyn_cast<CallExpr>(Base);
7395           if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7396             Diag(CD->getBeginLoc(),
7397                  diag::note_member_reference_arrow_from_operator_arrow);
7398           }
7399         }
7400         return ExprError();
7401       }
7402       Base = Result.get();
7403       if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7404         OperatorArrows.push_back(OpCall->getDirectCallee());
7405       BaseType = Base->getType();
7406       CanQualType CBaseType = Context.getCanonicalType(BaseType);
7407       if (!CTypes.insert(CBaseType).second) {
7408         Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7409         noteOperatorArrows(*this, OperatorArrows);
7410         return ExprError();
7411       }
7412       FirstIteration = false;
7413     }
7414 
7415     if (OpKind == tok::arrow) {
7416       if (BaseType->isPointerType())
7417         BaseType = BaseType->getPointeeType();
7418       else if (auto *AT = Context.getAsArrayType(BaseType))
7419         BaseType = AT->getElementType();
7420     }
7421   }
7422 
7423   // Objective-C properties allow "." access on Objective-C pointer types,
7424   // so adjust the base type to the object type itself.
7425   if (BaseType->isObjCObjectPointerType())
7426     BaseType = BaseType->getPointeeType();
7427 
7428   // C++ [basic.lookup.classref]p2:
7429   //   [...] If the type of the object expression is of pointer to scalar
7430   //   type, the unqualified-id is looked up in the context of the complete
7431   //   postfix-expression.
7432   //
7433   // This also indicates that we could be parsing a pseudo-destructor-name.
7434   // Note that Objective-C class and object types can be pseudo-destructor
7435   // expressions or normal member (ivar or property) access expressions, and
7436   // it's legal for the type to be incomplete if this is a pseudo-destructor
7437   // call.  We'll do more incomplete-type checks later in the lookup process,
7438   // so just skip this check for ObjC types.
7439   if (!BaseType->isRecordType()) {
7440     ObjectType = ParsedType::make(BaseType);
7441     MayBePseudoDestructor = true;
7442     return Base;
7443   }
7444 
7445   // The object type must be complete (or dependent), or
7446   // C++11 [expr.prim.general]p3:
7447   //   Unlike the object expression in other contexts, *this is not required to
7448   //   be of complete type for purposes of class member access (5.2.5) outside
7449   //   the member function body.
7450   if (!BaseType->isDependentType() &&
7451       !isThisOutsideMemberFunctionBody(BaseType) &&
7452       RequireCompleteType(OpLoc, BaseType,
7453                           diag::err_incomplete_member_access)) {
7454     return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
7455   }
7456 
7457   // C++ [basic.lookup.classref]p2:
7458   //   If the id-expression in a class member access (5.2.5) is an
7459   //   unqualified-id, and the type of the object expression is of a class
7460   //   type C (or of pointer to a class type C), the unqualified-id is looked
7461   //   up in the scope of class C. [...]
7462   ObjectType = ParsedType::make(BaseType);
7463   return Base;
7464 }
7465 
7466 static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
7467                        tok::TokenKind &OpKind, SourceLocation OpLoc) {
7468   if (Base->hasPlaceholderType()) {
7469     ExprResult result = S.CheckPlaceholderExpr(Base);
7470     if (result.isInvalid()) return true;
7471     Base = result.get();
7472   }
7473   ObjectType = Base->getType();
7474 
7475   // C++ [expr.pseudo]p2:
7476   //   The left-hand side of the dot operator shall be of scalar type. The
7477   //   left-hand side of the arrow operator shall be of pointer to scalar type.
7478   //   This scalar type is the object type.
7479   // Note that this is rather different from the normal handling for the
7480   // arrow operator.
7481   if (OpKind == tok::arrow) {
7482     // The operator requires a prvalue, so perform lvalue conversions.
7483     // Only do this if we might plausibly end with a pointer, as otherwise
7484     // this was likely to be intended to be a '.'.
7485     if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
7486         ObjectType->isFunctionType()) {
7487       ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base);
7488       if (BaseResult.isInvalid())
7489         return true;
7490       Base = BaseResult.get();
7491       ObjectType = Base->getType();
7492     }
7493 
7494     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7495       ObjectType = Ptr->getPointeeType();
7496     } else if (!Base->isTypeDependent()) {
7497       // The user wrote "p->" when they probably meant "p."; fix it.
7498       S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7499         << ObjectType << true
7500         << FixItHint::CreateReplacement(OpLoc, ".");
7501       if (S.isSFINAEContext())
7502         return true;
7503 
7504       OpKind = tok::period;
7505     }
7506   }
7507 
7508   return false;
7509 }
7510 
7511 /// Check if it's ok to try and recover dot pseudo destructor calls on
7512 /// pointer objects.
7513 static bool
7514 canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
7515                                                    QualType DestructedType) {
7516   // If this is a record type, check if its destructor is callable.
7517   if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
7518     if (RD->hasDefinition())
7519       if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
7520         return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
7521     return false;
7522   }
7523 
7524   // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7525   return DestructedType->isDependentType() || DestructedType->isScalarType() ||
7526          DestructedType->isVectorType();
7527 }
7528 
7529 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
7530                                            SourceLocation OpLoc,
7531                                            tok::TokenKind OpKind,
7532                                            const CXXScopeSpec &SS,
7533                                            TypeSourceInfo *ScopeTypeInfo,
7534                                            SourceLocation CCLoc,
7535                                            SourceLocation TildeLoc,
7536                                          PseudoDestructorTypeStorage Destructed) {
7537   TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
7538 
7539   QualType ObjectType;
7540   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7541     return ExprError();
7542 
7543   if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
7544       !ObjectType->isVectorType()) {
7545     if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
7546       Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
7547     else {
7548       Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
7549         << ObjectType << Base->getSourceRange();
7550       return ExprError();
7551     }
7552   }
7553 
7554   // C++ [expr.pseudo]p2:
7555   //   [...] The cv-unqualified versions of the object type and of the type
7556   //   designated by the pseudo-destructor-name shall be the same type.
7557   if (DestructedTypeInfo) {
7558     QualType DestructedType = DestructedTypeInfo->getType();
7559     SourceLocation DestructedTypeStart
7560       = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
7561     if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
7562       if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
7563         // Detect dot pseudo destructor calls on pointer objects, e.g.:
7564         //   Foo *foo;
7565         //   foo.~Foo();
7566         if (OpKind == tok::period && ObjectType->isPointerType() &&
7567             Context.hasSameUnqualifiedType(DestructedType,
7568                                            ObjectType->getPointeeType())) {
7569           auto Diagnostic =
7570               Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7571               << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
7572 
7573           // Issue a fixit only when the destructor is valid.
7574           if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
7575                   *this, DestructedType))
7576             Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
7577 
7578           // Recover by setting the object type to the destructed type and the
7579           // operator to '->'.
7580           ObjectType = DestructedType;
7581           OpKind = tok::arrow;
7582         } else {
7583           Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
7584               << ObjectType << DestructedType << Base->getSourceRange()
7585               << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
7586 
7587           // Recover by setting the destructed type to the object type.
7588           DestructedType = ObjectType;
7589           DestructedTypeInfo =
7590               Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
7591           Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7592         }
7593       } else if (DestructedType.getObjCLifetime() !=
7594                                                 ObjectType.getObjCLifetime()) {
7595 
7596         if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
7597           // Okay: just pretend that the user provided the correctly-qualified
7598           // type.
7599         } else {
7600           Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
7601             << ObjectType << DestructedType << Base->getSourceRange()
7602             << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
7603         }
7604 
7605         // Recover by setting the destructed type to the object type.
7606         DestructedType = ObjectType;
7607         DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
7608                                                            DestructedTypeStart);
7609         Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7610       }
7611     }
7612   }
7613 
7614   // C++ [expr.pseudo]p2:
7615   //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7616   //   form
7617   //
7618   //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
7619   //
7620   //   shall designate the same scalar type.
7621   if (ScopeTypeInfo) {
7622     QualType ScopeType = ScopeTypeInfo->getType();
7623     if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
7624         !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
7625 
7626       Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
7627            diag::err_pseudo_dtor_type_mismatch)
7628         << ObjectType << ScopeType << Base->getSourceRange()
7629         << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
7630 
7631       ScopeType = QualType();
7632       ScopeTypeInfo = nullptr;
7633     }
7634   }
7635 
7636   Expr *Result
7637     = new (Context) CXXPseudoDestructorExpr(Context, Base,
7638                                             OpKind == tok::arrow, OpLoc,
7639                                             SS.getWithLocInContext(Context),
7640                                             ScopeTypeInfo,
7641                                             CCLoc,
7642                                             TildeLoc,
7643                                             Destructed);
7644 
7645   return Result;
7646 }
7647 
7648 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7649                                            SourceLocation OpLoc,
7650                                            tok::TokenKind OpKind,
7651                                            CXXScopeSpec &SS,
7652                                            UnqualifiedId &FirstTypeName,
7653                                            SourceLocation CCLoc,
7654                                            SourceLocation TildeLoc,
7655                                            UnqualifiedId &SecondTypeName) {
7656   assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7657           FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7658          "Invalid first type name in pseudo-destructor");
7659   assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7660           SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7661          "Invalid second type name in pseudo-destructor");
7662 
7663   QualType ObjectType;
7664   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7665     return ExprError();
7666 
7667   // Compute the object type that we should use for name lookup purposes. Only
7668   // record types and dependent types matter.
7669   ParsedType ObjectTypePtrForLookup;
7670   if (!SS.isSet()) {
7671     if (ObjectType->isRecordType())
7672       ObjectTypePtrForLookup = ParsedType::make(ObjectType);
7673     else if (ObjectType->isDependentType())
7674       ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
7675   }
7676 
7677   // Convert the name of the type being destructed (following the ~) into a
7678   // type (with source-location information).
7679   QualType DestructedType;
7680   TypeSourceInfo *DestructedTypeInfo = nullptr;
7681   PseudoDestructorTypeStorage Destructed;
7682   if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7683     ParsedType T = getTypeName(*SecondTypeName.Identifier,
7684                                SecondTypeName.StartLocation,
7685                                S, &SS, true, false, ObjectTypePtrForLookup,
7686                                /*IsCtorOrDtorName*/true);
7687     if (!T &&
7688         ((SS.isSet() && !computeDeclContext(SS, false)) ||
7689          (!SS.isSet() && ObjectType->isDependentType()))) {
7690       // The name of the type being destroyed is a dependent name, and we
7691       // couldn't find anything useful in scope. Just store the identifier and
7692       // it's location, and we'll perform (qualified) name lookup again at
7693       // template instantiation time.
7694       Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7695                                                SecondTypeName.StartLocation);
7696     } else if (!T) {
7697       Diag(SecondTypeName.StartLocation,
7698            diag::err_pseudo_dtor_destructor_non_type)
7699         << SecondTypeName.Identifier << ObjectType;
7700       if (isSFINAEContext())
7701         return ExprError();
7702 
7703       // Recover by assuming we had the right type all along.
7704       DestructedType = ObjectType;
7705     } else
7706       DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
7707   } else {
7708     // Resolve the template-id to a type.
7709     TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
7710     ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7711                                        TemplateId->NumArgs);
7712     TypeResult T = ActOnTemplateIdType(S,
7713                                        SS,
7714                                        TemplateId->TemplateKWLoc,
7715                                        TemplateId->Template,
7716                                        TemplateId->Name,
7717                                        TemplateId->TemplateNameLoc,
7718                                        TemplateId->LAngleLoc,
7719                                        TemplateArgsPtr,
7720                                        TemplateId->RAngleLoc,
7721                                        /*IsCtorOrDtorName*/true);
7722     if (T.isInvalid() || !T.get()) {
7723       // Recover by assuming we had the right type all along.
7724       DestructedType = ObjectType;
7725     } else
7726       DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
7727   }
7728 
7729   // If we've performed some kind of recovery, (re-)build the type source
7730   // information.
7731   if (!DestructedType.isNull()) {
7732     if (!DestructedTypeInfo)
7733       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
7734                                                   SecondTypeName.StartLocation);
7735     Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7736   }
7737 
7738   // Convert the name of the scope type (the type prior to '::') into a type.
7739   TypeSourceInfo *ScopeTypeInfo = nullptr;
7740   QualType ScopeType;
7741   if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7742       FirstTypeName.Identifier) {
7743     if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7744       ParsedType T = getTypeName(*FirstTypeName.Identifier,
7745                                  FirstTypeName.StartLocation,
7746                                  S, &SS, true, false, ObjectTypePtrForLookup,
7747                                  /*IsCtorOrDtorName*/true);
7748       if (!T) {
7749         Diag(FirstTypeName.StartLocation,
7750              diag::err_pseudo_dtor_destructor_non_type)
7751           << FirstTypeName.Identifier << ObjectType;
7752 
7753         if (isSFINAEContext())
7754           return ExprError();
7755 
7756         // Just drop this type. It's unnecessary anyway.
7757         ScopeType = QualType();
7758       } else
7759         ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
7760     } else {
7761       // Resolve the template-id to a type.
7762       TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
7763       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7764                                          TemplateId->NumArgs);
7765       TypeResult T = ActOnTemplateIdType(S,
7766                                          SS,
7767                                          TemplateId->TemplateKWLoc,
7768                                          TemplateId->Template,
7769                                          TemplateId->Name,
7770                                          TemplateId->TemplateNameLoc,
7771                                          TemplateId->LAngleLoc,
7772                                          TemplateArgsPtr,
7773                                          TemplateId->RAngleLoc,
7774                                          /*IsCtorOrDtorName*/true);
7775       if (T.isInvalid() || !T.get()) {
7776         // Recover by dropping this type.
7777         ScopeType = QualType();
7778       } else
7779         ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
7780     }
7781   }
7782 
7783   if (!ScopeType.isNull() && !ScopeTypeInfo)
7784     ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7785                                                   FirstTypeName.StartLocation);
7786 
7787 
7788   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
7789                                    ScopeTypeInfo, CCLoc, TildeLoc,
7790                                    Destructed);
7791 }
7792 
7793 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7794                                            SourceLocation OpLoc,
7795                                            tok::TokenKind OpKind,
7796                                            SourceLocation TildeLoc,
7797                                            const DeclSpec& DS) {
7798   QualType ObjectType;
7799   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7800     return ExprError();
7801 
7802   if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
7803     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
7804     return true;
7805   }
7806 
7807   QualType T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
7808 
7809   TypeLocBuilder TLB;
7810   DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7811   DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
7812   DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
7813   TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7814   PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7815 
7816   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
7817                                    nullptr, SourceLocation(), TildeLoc,
7818                                    Destructed);
7819 }
7820 
7821 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
7822                                         CXXConversionDecl *Method,
7823                                         bool HadMultipleCandidates) {
7824   // Convert the expression to match the conversion function's implicit object
7825   // parameter.
7826   ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7827                                           FoundDecl, Method);
7828   if (Exp.isInvalid())
7829     return true;
7830 
7831   if (Method->getParent()->isLambda() &&
7832       Method->getConversionType()->isBlockPointerType()) {
7833     // This is a lambda conversion to block pointer; check if the argument
7834     // was a LambdaExpr.
7835     Expr *SubE = E;
7836     CastExpr *CE = dyn_cast<CastExpr>(SubE);
7837     if (CE && CE->getCastKind() == CK_NoOp)
7838       SubE = CE->getSubExpr();
7839     SubE = SubE->IgnoreParens();
7840     if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7841       SubE = BE->getSubExpr();
7842     if (isa<LambdaExpr>(SubE)) {
7843       // For the conversion to block pointer on a lambda expression, we
7844       // construct a special BlockLiteral instead; this doesn't really make
7845       // a difference in ARC, but outside of ARC the resulting block literal
7846       // follows the normal lifetime rules for block literals instead of being
7847       // autoreleased.
7848       PushExpressionEvaluationContext(
7849           ExpressionEvaluationContext::PotentiallyEvaluated);
7850       ExprResult BlockExp = BuildBlockForLambdaConversion(
7851           Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
7852       PopExpressionEvaluationContext();
7853 
7854       // FIXME: This note should be produced by a CodeSynthesisContext.
7855       if (BlockExp.isInvalid())
7856         Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7857       return BlockExp;
7858     }
7859   }
7860 
7861   MemberExpr *ME =
7862       BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
7863                       NestedNameSpecifierLoc(), SourceLocation(), Method,
7864                       DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
7865                       HadMultipleCandidates, DeclarationNameInfo(),
7866                       Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
7867 
7868   QualType ResultType = Method->getReturnType();
7869   ExprValueKind VK = Expr::getValueKindForType(ResultType);
7870   ResultType = ResultType.getNonLValueExprType(Context);
7871 
7872   CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
7873       Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc(),
7874       CurFPFeatureOverrides());
7875 
7876   if (CheckFunctionCall(Method, CE,
7877                         Method->getType()->castAs<FunctionProtoType>()))
7878     return ExprError();
7879 
7880   return CheckForImmediateInvocation(CE, CE->getMethodDecl());
7881 }
7882 
7883 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7884                                       SourceLocation RParen) {
7885   // If the operand is an unresolved lookup expression, the expression is ill-
7886   // formed per [over.over]p1, because overloaded function names cannot be used
7887   // without arguments except in explicit contexts.
7888   ExprResult R = CheckPlaceholderExpr(Operand);
7889   if (R.isInvalid())
7890     return R;
7891 
7892   R = CheckUnevaluatedOperand(R.get());
7893   if (R.isInvalid())
7894     return ExprError();
7895 
7896   Operand = R.get();
7897 
7898   if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
7899       Operand->HasSideEffects(Context, false)) {
7900     // The expression operand for noexcept is in an unevaluated expression
7901     // context, so side effects could result in unintended consequences.
7902     Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7903   }
7904 
7905   CanThrowResult CanThrow = canThrow(Operand);
7906   return new (Context)
7907       CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
7908 }
7909 
7910 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7911                                    Expr *Operand, SourceLocation RParen) {
7912   return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
7913 }
7914 
7915 static void MaybeDecrementCount(
7916     Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
7917   DeclRefExpr *LHS = nullptr;
7918   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7919     if (BO->getLHS()->getType()->isDependentType() ||
7920         BO->getRHS()->getType()->isDependentType()) {
7921       if (BO->getOpcode() != BO_Assign)
7922         return;
7923     } else if (!BO->isAssignmentOp())
7924       return;
7925     LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
7926   } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7927     if (COCE->getOperator() != OO_Equal)
7928       return;
7929     LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
7930   }
7931   if (!LHS)
7932     return;
7933   VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
7934   if (!VD)
7935     return;
7936   auto iter = RefsMinusAssignments.find(VD);
7937   if (iter == RefsMinusAssignments.end())
7938     return;
7939   iter->getSecond()--;
7940 }
7941 
7942 /// Perform the conversions required for an expression used in a
7943 /// context that ignores the result.
7944 ExprResult Sema::IgnoredValueConversions(Expr *E) {
7945   MaybeDecrementCount(E, RefsMinusAssignments);
7946 
7947   if (E->hasPlaceholderType()) {
7948     ExprResult result = CheckPlaceholderExpr(E);
7949     if (result.isInvalid()) return E;
7950     E = result.get();
7951   }
7952 
7953   // C99 6.3.2.1:
7954   //   [Except in specific positions,] an lvalue that does not have
7955   //   array type is converted to the value stored in the
7956   //   designated object (and is no longer an lvalue).
7957   if (E->isPRValue()) {
7958     // In C, function designators (i.e. expressions of function type)
7959     // are r-values, but we still want to do function-to-pointer decay
7960     // on them.  This is both technically correct and convenient for
7961     // some clients.
7962     if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
7963       return DefaultFunctionArrayConversion(E);
7964 
7965     return E;
7966   }
7967 
7968   if (getLangOpts().CPlusPlus) {
7969     // The C++11 standard defines the notion of a discarded-value expression;
7970     // normally, we don't need to do anything to handle it, but if it is a
7971     // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7972     // conversion.
7973     if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) {
7974       ExprResult Res = DefaultLvalueConversion(E);
7975       if (Res.isInvalid())
7976         return E;
7977       E = Res.get();
7978     } else {
7979       // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7980       // it occurs as a discarded-value expression.
7981       CheckUnusedVolatileAssignment(E);
7982     }
7983 
7984     // C++1z:
7985     //   If the expression is a prvalue after this optional conversion, the
7986     //   temporary materialization conversion is applied.
7987     //
7988     // We skip this step: IR generation is able to synthesize the storage for
7989     // itself in the aggregate case, and adding the extra node to the AST is
7990     // just clutter.
7991     // FIXME: We don't emit lifetime markers for the temporaries due to this.
7992     // FIXME: Do any other AST consumers care about this?
7993     return E;
7994   }
7995 
7996   // GCC seems to also exclude expressions of incomplete enum type.
7997   if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7998     if (!T->getDecl()->isComplete()) {
7999       // FIXME: stupid workaround for a codegen bug!
8000       E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
8001       return E;
8002     }
8003   }
8004 
8005   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
8006   if (Res.isInvalid())
8007     return E;
8008   E = Res.get();
8009 
8010   if (!E->getType()->isVoidType())
8011     RequireCompleteType(E->getExprLoc(), E->getType(),
8012                         diag::err_incomplete_type);
8013   return E;
8014 }
8015 
8016 ExprResult Sema::CheckUnevaluatedOperand(Expr *E) {
8017   // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8018   // it occurs as an unevaluated operand.
8019   CheckUnusedVolatileAssignment(E);
8020 
8021   return E;
8022 }
8023 
8024 // If we can unambiguously determine whether Var can never be used
8025 // in a constant expression, return true.
8026 //  - if the variable and its initializer are non-dependent, then
8027 //    we can unambiguously check if the variable is a constant expression.
8028 //  - if the initializer is not value dependent - we can determine whether
8029 //    it can be used to initialize a constant expression.  If Init can not
8030 //    be used to initialize a constant expression we conclude that Var can
8031 //    never be a constant expression.
8032 //  - FXIME: if the initializer is dependent, we can still do some analysis and
8033 //    identify certain cases unambiguously as non-const by using a Visitor:
8034 //      - such as those that involve odr-use of a ParmVarDecl, involve a new
8035 //        delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
8036 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
8037     ASTContext &Context) {
8038   if (isa<ParmVarDecl>(Var)) return true;
8039   const VarDecl *DefVD = nullptr;
8040 
8041   // If there is no initializer - this can not be a constant expression.
8042   if (!Var->getAnyInitializer(DefVD)) return true;
8043   assert(DefVD);
8044   if (DefVD->isWeak()) return false;
8045   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
8046 
8047   Expr *Init = cast<Expr>(Eval->Value);
8048 
8049   if (Var->getType()->isDependentType() || Init->isValueDependent()) {
8050     // FIXME: Teach the constant evaluator to deal with the non-dependent parts
8051     // of value-dependent expressions, and use it here to determine whether the
8052     // initializer is a potential constant expression.
8053     return false;
8054   }
8055 
8056   return !Var->isUsableInConstantExpressions(Context);
8057 }
8058 
8059 /// Check if the current lambda has any potential captures
8060 /// that must be captured by any of its enclosing lambdas that are ready to
8061 /// capture. If there is a lambda that can capture a nested
8062 /// potential-capture, go ahead and do so.  Also, check to see if any
8063 /// variables are uncaptureable or do not involve an odr-use so do not
8064 /// need to be captured.
8065 
8066 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
8067     Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
8068 
8069   assert(!S.isUnevaluatedContext());
8070   assert(S.CurContext->isDependentContext());
8071 #ifndef NDEBUG
8072   DeclContext *DC = S.CurContext;
8073   while (DC && isa<CapturedDecl>(DC))
8074     DC = DC->getParent();
8075   assert(
8076       CurrentLSI->CallOperator == DC &&
8077       "The current call operator must be synchronized with Sema's CurContext");
8078 #endif // NDEBUG
8079 
8080   const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
8081 
8082   // All the potentially captureable variables in the current nested
8083   // lambda (within a generic outer lambda), must be captured by an
8084   // outer lambda that is enclosed within a non-dependent context.
8085   CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) {
8086     // If the variable is clearly identified as non-odr-used and the full
8087     // expression is not instantiation dependent, only then do we not
8088     // need to check enclosing lambda's for speculative captures.
8089     // For e.g.:
8090     // Even though 'x' is not odr-used, it should be captured.
8091     // int test() {
8092     //   const int x = 10;
8093     //   auto L = [=](auto a) {
8094     //     (void) +x + a;
8095     //   };
8096     // }
8097     if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
8098         !IsFullExprInstantiationDependent)
8099       return;
8100 
8101     // If we have a capture-capable lambda for the variable, go ahead and
8102     // capture the variable in that lambda (and all its enclosing lambdas).
8103     if (const Optional<unsigned> Index =
8104             getStackIndexOfNearestEnclosingCaptureCapableLambda(
8105                 S.FunctionScopes, Var, S))
8106       S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(),
8107                                           Index.getValue());
8108     const bool IsVarNeverAConstantExpression =
8109         VariableCanNeverBeAConstantExpression(Var, S.Context);
8110     if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
8111       // This full expression is not instantiation dependent or the variable
8112       // can not be used in a constant expression - which means
8113       // this variable must be odr-used here, so diagnose a
8114       // capture violation early, if the variable is un-captureable.
8115       // This is purely for diagnosing errors early.  Otherwise, this
8116       // error would get diagnosed when the lambda becomes capture ready.
8117       QualType CaptureType, DeclRefType;
8118       SourceLocation ExprLoc = VarExpr->getExprLoc();
8119       if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8120                           /*EllipsisLoc*/ SourceLocation(),
8121                           /*BuildAndDiagnose*/false, CaptureType,
8122                           DeclRefType, nullptr)) {
8123         // We will never be able to capture this variable, and we need
8124         // to be able to in any and all instantiations, so diagnose it.
8125         S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8126                           /*EllipsisLoc*/ SourceLocation(),
8127                           /*BuildAndDiagnose*/true, CaptureType,
8128                           DeclRefType, nullptr);
8129       }
8130     }
8131   });
8132 
8133   // Check if 'this' needs to be captured.
8134   if (CurrentLSI->hasPotentialThisCapture()) {
8135     // If we have a capture-capable lambda for 'this', go ahead and capture
8136     // 'this' in that lambda (and all its enclosing lambdas).
8137     if (const Optional<unsigned> Index =
8138             getStackIndexOfNearestEnclosingCaptureCapableLambda(
8139                 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
8140       const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
8141       S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
8142                             /*Explicit*/ false, /*BuildAndDiagnose*/ true,
8143                             &FunctionScopeIndexOfCapturableLambda);
8144     }
8145   }
8146 
8147   // Reset all the potential captures at the end of each full-expression.
8148   CurrentLSI->clearPotentialCaptures();
8149 }
8150 
8151 static ExprResult attemptRecovery(Sema &SemaRef,
8152                                   const TypoCorrectionConsumer &Consumer,
8153                                   const TypoCorrection &TC) {
8154   LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
8155                  Consumer.getLookupResult().getLookupKind());
8156   const CXXScopeSpec *SS = Consumer.getSS();
8157   CXXScopeSpec NewSS;
8158 
8159   // Use an approprate CXXScopeSpec for building the expr.
8160   if (auto *NNS = TC.getCorrectionSpecifier())
8161     NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
8162   else if (SS && !TC.WillReplaceSpecifier())
8163     NewSS = *SS;
8164 
8165   if (auto *ND = TC.getFoundDecl()) {
8166     R.setLookupName(ND->getDeclName());
8167     R.addDecl(ND);
8168     if (ND->isCXXClassMember()) {
8169       // Figure out the correct naming class to add to the LookupResult.
8170       CXXRecordDecl *Record = nullptr;
8171       if (auto *NNS = TC.getCorrectionSpecifier())
8172         Record = NNS->getAsType()->getAsCXXRecordDecl();
8173       if (!Record)
8174         Record =
8175             dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
8176       if (Record)
8177         R.setNamingClass(Record);
8178 
8179       // Detect and handle the case where the decl might be an implicit
8180       // member.
8181       bool MightBeImplicitMember;
8182       if (!Consumer.isAddressOfOperand())
8183         MightBeImplicitMember = true;
8184       else if (!NewSS.isEmpty())
8185         MightBeImplicitMember = false;
8186       else if (R.isOverloadedResult())
8187         MightBeImplicitMember = false;
8188       else if (R.isUnresolvableResult())
8189         MightBeImplicitMember = true;
8190       else
8191         MightBeImplicitMember = isa<FieldDecl>(ND) ||
8192                                 isa<IndirectFieldDecl>(ND) ||
8193                                 isa<MSPropertyDecl>(ND);
8194 
8195       if (MightBeImplicitMember)
8196         return SemaRef.BuildPossibleImplicitMemberExpr(
8197             NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
8198             /*TemplateArgs*/ nullptr, /*S*/ nullptr);
8199     } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
8200       return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
8201                                         Ivar->getIdentifier());
8202     }
8203   }
8204 
8205   return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
8206                                           /*AcceptInvalidDecl*/ true);
8207 }
8208 
8209 namespace {
8210 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
8211   llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
8212 
8213 public:
8214   explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
8215       : TypoExprs(TypoExprs) {}
8216   bool VisitTypoExpr(TypoExpr *TE) {
8217     TypoExprs.insert(TE);
8218     return true;
8219   }
8220 };
8221 
8222 class TransformTypos : public TreeTransform<TransformTypos> {
8223   typedef TreeTransform<TransformTypos> BaseTransform;
8224 
8225   VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
8226                      // process of being initialized.
8227   llvm::function_ref<ExprResult(Expr *)> ExprFilter;
8228   llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
8229   llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
8230   llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
8231 
8232   /// Emit diagnostics for all of the TypoExprs encountered.
8233   ///
8234   /// If the TypoExprs were successfully corrected, then the diagnostics should
8235   /// suggest the corrections. Otherwise the diagnostics will not suggest
8236   /// anything (having been passed an empty TypoCorrection).
8237   ///
8238   /// If we've failed to correct due to ambiguous corrections, we need to
8239   /// be sure to pass empty corrections and replacements. Otherwise it's
8240   /// possible that the Consumer has a TypoCorrection that failed to ambiguity
8241   /// and we don't want to report those diagnostics.
8242   void EmitAllDiagnostics(bool IsAmbiguous) {
8243     for (TypoExpr *TE : TypoExprs) {
8244       auto &State = SemaRef.getTypoExprState(TE);
8245       if (State.DiagHandler) {
8246         TypoCorrection TC = IsAmbiguous
8247             ? TypoCorrection() : State.Consumer->getCurrentCorrection();
8248         ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
8249 
8250         // Extract the NamedDecl from the transformed TypoExpr and add it to the
8251         // TypoCorrection, replacing the existing decls. This ensures the right
8252         // NamedDecl is used in diagnostics e.g. in the case where overload
8253         // resolution was used to select one from several possible decls that
8254         // had been stored in the TypoCorrection.
8255         if (auto *ND = getDeclFromExpr(
8256                 Replacement.isInvalid() ? nullptr : Replacement.get()))
8257           TC.setCorrectionDecl(ND);
8258 
8259         State.DiagHandler(TC);
8260       }
8261       SemaRef.clearDelayedTypo(TE);
8262     }
8263   }
8264 
8265   /// Try to advance the typo correction state of the first unfinished TypoExpr.
8266   /// We allow advancement of the correction stream by removing it from the
8267   /// TransformCache which allows `TransformTypoExpr` to advance during the
8268   /// next transformation attempt.
8269   ///
8270   /// Any substitution attempts for the previous TypoExprs (which must have been
8271   /// finished) will need to be retried since it's possible that they will now
8272   /// be invalid given the latest advancement.
8273   ///
8274   /// We need to be sure that we're making progress - it's possible that the
8275   /// tree is so malformed that the transform never makes it to the
8276   /// `TransformTypoExpr`.
8277   ///
8278   /// Returns true if there are any untried correction combinations.
8279   bool CheckAndAdvanceTypoExprCorrectionStreams() {
8280     for (auto TE : TypoExprs) {
8281       auto &State = SemaRef.getTypoExprState(TE);
8282       TransformCache.erase(TE);
8283       if (!State.Consumer->hasMadeAnyCorrectionProgress())
8284         return false;
8285       if (!State.Consumer->finished())
8286         return true;
8287       State.Consumer->resetCorrectionStream();
8288     }
8289     return false;
8290   }
8291 
8292   NamedDecl *getDeclFromExpr(Expr *E) {
8293     if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8294       E = OverloadResolution[OE];
8295 
8296     if (!E)
8297       return nullptr;
8298     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
8299       return DRE->getFoundDecl();
8300     if (auto *ME = dyn_cast<MemberExpr>(E))
8301       return ME->getFoundDecl();
8302     // FIXME: Add any other expr types that could be be seen by the delayed typo
8303     // correction TreeTransform for which the corresponding TypoCorrection could
8304     // contain multiple decls.
8305     return nullptr;
8306   }
8307 
8308   ExprResult TryTransform(Expr *E) {
8309     Sema::SFINAETrap Trap(SemaRef);
8310     ExprResult Res = TransformExpr(E);
8311     if (Trap.hasErrorOccurred() || Res.isInvalid())
8312       return ExprError();
8313 
8314     return ExprFilter(Res.get());
8315   }
8316 
8317   // Since correcting typos may intoduce new TypoExprs, this function
8318   // checks for new TypoExprs and recurses if it finds any. Note that it will
8319   // only succeed if it is able to correct all typos in the given expression.
8320   ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8321     if (Res.isInvalid()) {
8322       return Res;
8323     }
8324     // Check to see if any new TypoExprs were created. If so, we need to recurse
8325     // to check their validity.
8326     Expr *FixedExpr = Res.get();
8327 
8328     auto SavedTypoExprs = std::move(TypoExprs);
8329     auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8330     TypoExprs.clear();
8331     AmbiguousTypoExprs.clear();
8332 
8333     FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8334     if (!TypoExprs.empty()) {
8335       // Recurse to handle newly created TypoExprs. If we're not able to
8336       // handle them, discard these TypoExprs.
8337       ExprResult RecurResult =
8338           RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8339       if (RecurResult.isInvalid()) {
8340         Res = ExprError();
8341         // Recursive corrections didn't work, wipe them away and don't add
8342         // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8343         // since we don't want to clear them twice. Note: it's possible the
8344         // TypoExprs were created recursively and thus won't be in our
8345         // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8346         auto &SemaTypoExprs = SemaRef.TypoExprs;
8347         for (auto TE : TypoExprs) {
8348           TransformCache.erase(TE);
8349           SemaRef.clearDelayedTypo(TE);
8350 
8351           auto SI = find(SemaTypoExprs, TE);
8352           if (SI != SemaTypoExprs.end()) {
8353             SemaTypoExprs.erase(SI);
8354           }
8355         }
8356       } else {
8357         // TypoExpr is valid: add newly created TypoExprs since we were
8358         // able to correct them.
8359         Res = RecurResult;
8360         SavedTypoExprs.set_union(TypoExprs);
8361       }
8362     }
8363 
8364     TypoExprs = std::move(SavedTypoExprs);
8365     AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8366 
8367     return Res;
8368   }
8369 
8370   // Try to transform the given expression, looping through the correction
8371   // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8372   //
8373   // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8374   // true and this method immediately will return an `ExprError`.
8375   ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8376     ExprResult Res;
8377     auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8378     SemaRef.TypoExprs.clear();
8379 
8380     while (true) {
8381       Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8382 
8383       // Recursion encountered an ambiguous correction. This means that our
8384       // correction itself is ambiguous, so stop now.
8385       if (IsAmbiguous)
8386         break;
8387 
8388       // If the transform is still valid after checking for any new typos,
8389       // it's good to go.
8390       if (!Res.isInvalid())
8391         break;
8392 
8393       // The transform was invalid, see if we have any TypoExprs with untried
8394       // correction candidates.
8395       if (!CheckAndAdvanceTypoExprCorrectionStreams())
8396         break;
8397     }
8398 
8399     // If we found a valid result, double check to make sure it's not ambiguous.
8400     if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
8401       auto SavedTransformCache =
8402           llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8403 
8404       // Ensure none of the TypoExprs have multiple typo correction candidates
8405       // with the same edit length that pass all the checks and filters.
8406       while (!AmbiguousTypoExprs.empty()) {
8407         auto TE  = AmbiguousTypoExprs.back();
8408 
8409         // TryTransform itself can create new Typos, adding them to the TypoExpr map
8410         // and invalidating our TypoExprState, so always fetch it instead of storing.
8411         SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8412 
8413         TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8414         TypoCorrection Next;
8415         do {
8416           // Fetch the next correction by erasing the typo from the cache and calling
8417           // `TryTransform` which will iterate through corrections in
8418           // `TransformTypoExpr`.
8419           TransformCache.erase(TE);
8420           ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8421 
8422           if (!AmbigRes.isInvalid() || IsAmbiguous) {
8423             SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8424             SavedTransformCache.erase(TE);
8425             Res = ExprError();
8426             IsAmbiguous = true;
8427             break;
8428           }
8429         } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8430                  Next.getEditDistance(false) == TC.getEditDistance(false));
8431 
8432         if (IsAmbiguous)
8433           break;
8434 
8435         AmbiguousTypoExprs.remove(TE);
8436         SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8437         TransformCache[TE] = SavedTransformCache[TE];
8438       }
8439       TransformCache = std::move(SavedTransformCache);
8440     }
8441 
8442     // Wipe away any newly created TypoExprs that we don't know about. Since we
8443     // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8444     // possible if a `TypoExpr` is created during a transformation but then
8445     // fails before we can discover it.
8446     auto &SemaTypoExprs = SemaRef.TypoExprs;
8447     for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
8448       auto TE = *Iterator;
8449       auto FI = find(TypoExprs, TE);
8450       if (FI != TypoExprs.end()) {
8451         Iterator++;
8452         continue;
8453       }
8454       SemaRef.clearDelayedTypo(TE);
8455       Iterator = SemaTypoExprs.erase(Iterator);
8456     }
8457     SemaRef.TypoExprs = std::move(SavedTypoExprs);
8458 
8459     return Res;
8460   }
8461 
8462 public:
8463   TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
8464       : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
8465 
8466   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
8467                                    MultiExprArg Args,
8468                                    SourceLocation RParenLoc,
8469                                    Expr *ExecConfig = nullptr) {
8470     auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
8471                                                  RParenLoc, ExecConfig);
8472     if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
8473       if (Result.isUsable()) {
8474         Expr *ResultCall = Result.get();
8475         if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
8476           ResultCall = BE->getSubExpr();
8477         if (auto *CE = dyn_cast<CallExpr>(ResultCall))
8478           OverloadResolution[OE] = CE->getCallee();
8479       }
8480     }
8481     return Result;
8482   }
8483 
8484   ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
8485 
8486   ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
8487 
8488   ExprResult Transform(Expr *E) {
8489     bool IsAmbiguous = false;
8490     ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
8491 
8492     if (!Res.isUsable())
8493       FindTypoExprs(TypoExprs).TraverseStmt(E);
8494 
8495     EmitAllDiagnostics(IsAmbiguous);
8496 
8497     return Res;
8498   }
8499 
8500   ExprResult TransformTypoExpr(TypoExpr *E) {
8501     // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
8502     // cached transformation result if there is one and the TypoExpr isn't the
8503     // first one that was encountered.
8504     auto &CacheEntry = TransformCache[E];
8505     if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
8506       return CacheEntry;
8507     }
8508 
8509     auto &State = SemaRef.getTypoExprState(E);
8510     assert(State.Consumer && "Cannot transform a cleared TypoExpr");
8511 
8512     // For the first TypoExpr and an uncached TypoExpr, find the next likely
8513     // typo correction and return it.
8514     while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
8515       if (InitDecl && TC.getFoundDecl() == InitDecl)
8516         continue;
8517       // FIXME: If we would typo-correct to an invalid declaration, it's
8518       // probably best to just suppress all errors from this typo correction.
8519       ExprResult NE = State.RecoveryHandler ?
8520           State.RecoveryHandler(SemaRef, E, TC) :
8521           attemptRecovery(SemaRef, *State.Consumer, TC);
8522       if (!NE.isInvalid()) {
8523         // Check whether there may be a second viable correction with the same
8524         // edit distance; if so, remember this TypoExpr may have an ambiguous
8525         // correction so it can be more thoroughly vetted later.
8526         TypoCorrection Next;
8527         if ((Next = State.Consumer->peekNextCorrection()) &&
8528             Next.getEditDistance(false) == TC.getEditDistance(false)) {
8529           AmbiguousTypoExprs.insert(E);
8530         } else {
8531           AmbiguousTypoExprs.remove(E);
8532         }
8533         assert(!NE.isUnset() &&
8534                "Typo was transformed into a valid-but-null ExprResult");
8535         return CacheEntry = NE;
8536       }
8537     }
8538     return CacheEntry = ExprError();
8539   }
8540 };
8541 }
8542 
8543 ExprResult
8544 Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
8545                                 bool RecoverUncorrectedTypos,
8546                                 llvm::function_ref<ExprResult(Expr *)> Filter) {
8547   // If the current evaluation context indicates there are uncorrected typos
8548   // and the current expression isn't guaranteed to not have typos, try to
8549   // resolve any TypoExpr nodes that might be in the expression.
8550   if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
8551       (E->isTypeDependent() || E->isValueDependent() ||
8552        E->isInstantiationDependent())) {
8553     auto TyposResolved = DelayedTypos.size();
8554     auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
8555     TyposResolved -= DelayedTypos.size();
8556     if (Result.isInvalid() || Result.get() != E) {
8557       ExprEvalContexts.back().NumTypos -= TyposResolved;
8558       if (Result.isInvalid() && RecoverUncorrectedTypos) {
8559         struct TyposReplace : TreeTransform<TyposReplace> {
8560           TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}
8561           ExprResult TransformTypoExpr(clang::TypoExpr *E) {
8562             return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),
8563                                                     E->getEndLoc(), {});
8564           }
8565         } TT(*this);
8566         return TT.TransformExpr(E);
8567       }
8568       return Result;
8569     }
8570     assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
8571   }
8572   return E;
8573 }
8574 
8575 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
8576                                      bool DiscardedValue,
8577                                      bool IsConstexpr) {
8578   ExprResult FullExpr = FE;
8579 
8580   if (!FullExpr.get())
8581     return ExprError();
8582 
8583   if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
8584     return ExprError();
8585 
8586   if (DiscardedValue) {
8587     // Top-level expressions default to 'id' when we're in a debugger.
8588     if (getLangOpts().DebuggerCastResultToId &&
8589         FullExpr.get()->getType() == Context.UnknownAnyTy) {
8590       FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
8591       if (FullExpr.isInvalid())
8592         return ExprError();
8593     }
8594 
8595     FullExpr = CheckPlaceholderExpr(FullExpr.get());
8596     if (FullExpr.isInvalid())
8597       return ExprError();
8598 
8599     FullExpr = IgnoredValueConversions(FullExpr.get());
8600     if (FullExpr.isInvalid())
8601       return ExprError();
8602 
8603     DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
8604   }
8605 
8606   FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,
8607                                        /*RecoverUncorrectedTypos=*/true);
8608   if (FullExpr.isInvalid())
8609     return ExprError();
8610 
8611   CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
8612 
8613   // At the end of this full expression (which could be a deeply nested
8614   // lambda), if there is a potential capture within the nested lambda,
8615   // have the outer capture-able lambda try and capture it.
8616   // Consider the following code:
8617   // void f(int, int);
8618   // void f(const int&, double);
8619   // void foo() {
8620   //  const int x = 10, y = 20;
8621   //  auto L = [=](auto a) {
8622   //      auto M = [=](auto b) {
8623   //         f(x, b); <-- requires x to be captured by L and M
8624   //         f(y, a); <-- requires y to be captured by L, but not all Ms
8625   //      };
8626   //   };
8627   // }
8628 
8629   // FIXME: Also consider what happens for something like this that involves
8630   // the gnu-extension statement-expressions or even lambda-init-captures:
8631   //   void f() {
8632   //     const int n = 0;
8633   //     auto L =  [&](auto a) {
8634   //       +n + ({ 0; a; });
8635   //     };
8636   //   }
8637   //
8638   // Here, we see +n, and then the full-expression 0; ends, so we don't
8639   // capture n (and instead remove it from our list of potential captures),
8640   // and then the full-expression +n + ({ 0; }); ends, but it's too late
8641   // for us to see that we need to capture n after all.
8642 
8643   LambdaScopeInfo *const CurrentLSI =
8644       getCurLambda(/*IgnoreCapturedRegions=*/true);
8645   // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
8646   // even if CurContext is not a lambda call operator. Refer to that Bug Report
8647   // for an example of the code that might cause this asynchrony.
8648   // By ensuring we are in the context of a lambda's call operator
8649   // we can fix the bug (we only need to check whether we need to capture
8650   // if we are within a lambda's body); but per the comments in that
8651   // PR, a proper fix would entail :
8652   //   "Alternative suggestion:
8653   //   - Add to Sema an integer holding the smallest (outermost) scope
8654   //     index that we are *lexically* within, and save/restore/set to
8655   //     FunctionScopes.size() in InstantiatingTemplate's
8656   //     constructor/destructor.
8657   //  - Teach the handful of places that iterate over FunctionScopes to
8658   //    stop at the outermost enclosing lexical scope."
8659   DeclContext *DC = CurContext;
8660   while (DC && isa<CapturedDecl>(DC))
8661     DC = DC->getParent();
8662   const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
8663   if (IsInLambdaDeclContext && CurrentLSI &&
8664       CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
8665     CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
8666                                                               *this);
8667   return MaybeCreateExprWithCleanups(FullExpr);
8668 }
8669 
8670 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
8671   if (!FullStmt) return StmtError();
8672 
8673   return MaybeCreateStmtWithCleanups(FullStmt);
8674 }
8675 
8676 Sema::IfExistsResult
8677 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
8678                                    CXXScopeSpec &SS,
8679                                    const DeclarationNameInfo &TargetNameInfo) {
8680   DeclarationName TargetName = TargetNameInfo.getName();
8681   if (!TargetName)
8682     return IER_DoesNotExist;
8683 
8684   // If the name itself is dependent, then the result is dependent.
8685   if (TargetName.isDependentName())
8686     return IER_Dependent;
8687 
8688   // Do the redeclaration lookup in the current scope.
8689   LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
8690                  Sema::NotForRedeclaration);
8691   LookupParsedName(R, S, &SS);
8692   R.suppressDiagnostics();
8693 
8694   switch (R.getResultKind()) {
8695   case LookupResult::Found:
8696   case LookupResult::FoundOverloaded:
8697   case LookupResult::FoundUnresolvedValue:
8698   case LookupResult::Ambiguous:
8699     return IER_Exists;
8700 
8701   case LookupResult::NotFound:
8702     return IER_DoesNotExist;
8703 
8704   case LookupResult::NotFoundInCurrentInstantiation:
8705     return IER_Dependent;
8706   }
8707 
8708   llvm_unreachable("Invalid LookupResult Kind!");
8709 }
8710 
8711 Sema::IfExistsResult
8712 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
8713                                    bool IsIfExists, CXXScopeSpec &SS,
8714                                    UnqualifiedId &Name) {
8715   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8716 
8717   // Check for an unexpanded parameter pack.
8718   auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
8719   if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
8720       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
8721     return IER_Error;
8722 
8723   return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
8724 }
8725 
8726 concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) {
8727   return BuildExprRequirement(E, /*IsSimple=*/true,
8728                               /*NoexceptLoc=*/SourceLocation(),
8729                               /*ReturnTypeRequirement=*/{});
8730 }
8731 
8732 concepts::Requirement *
8733 Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS,
8734                            SourceLocation NameLoc, IdentifierInfo *TypeName,
8735                            TemplateIdAnnotation *TemplateId) {
8736   assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
8737          "Exactly one of TypeName and TemplateId must be specified.");
8738   TypeSourceInfo *TSI = nullptr;
8739   if (TypeName) {
8740     QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc,
8741                                    SS.getWithLocInContext(Context), *TypeName,
8742                                    NameLoc, &TSI, /*DeducedTSTContext=*/false);
8743     if (T.isNull())
8744       return nullptr;
8745   } else {
8746     ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
8747                                TemplateId->NumArgs);
8748     TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
8749                                      TemplateId->TemplateKWLoc,
8750                                      TemplateId->Template, TemplateId->Name,
8751                                      TemplateId->TemplateNameLoc,
8752                                      TemplateId->LAngleLoc, ArgsPtr,
8753                                      TemplateId->RAngleLoc);
8754     if (T.isInvalid())
8755       return nullptr;
8756     if (GetTypeFromParser(T.get(), &TSI).isNull())
8757       return nullptr;
8758   }
8759   return BuildTypeRequirement(TSI);
8760 }
8761 
8762 concepts::Requirement *
8763 Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) {
8764   return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
8765                               /*ReturnTypeRequirement=*/{});
8766 }
8767 
8768 concepts::Requirement *
8769 Sema::ActOnCompoundRequirement(
8770     Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8771     TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
8772   // C++2a [expr.prim.req.compound] p1.3.3
8773   //   [..] the expression is deduced against an invented function template
8774   //   F [...] F is a void function template with a single type template
8775   //   parameter T declared with the constrained-parameter. Form a new
8776   //   cv-qualifier-seq cv by taking the union of const and volatile specifiers
8777   //   around the constrained-parameter. F has a single parameter whose
8778   //   type-specifier is cv T followed by the abstract-declarator. [...]
8779   //
8780   // The cv part is done in the calling function - we get the concept with
8781   // arguments and the abstract declarator with the correct CV qualification and
8782   // have to synthesize T and the single parameter of F.
8783   auto &II = Context.Idents.get("expr-type");
8784   auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext,
8785                                               SourceLocation(),
8786                                               SourceLocation(), Depth,
8787                                               /*Index=*/0, &II,
8788                                               /*Typename=*/true,
8789                                               /*ParameterPack=*/false,
8790                                               /*HasTypeConstraint=*/true);
8791 
8792   if (BuildTypeConstraint(SS, TypeConstraint, TParam,
8793                           /*EllipsisLoc=*/SourceLocation(),
8794                           /*AllowUnexpandedPack=*/true))
8795     // Just produce a requirement with no type requirements.
8796     return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
8797 
8798   auto *TPL = TemplateParameterList::Create(Context, SourceLocation(),
8799                                             SourceLocation(),
8800                                             ArrayRef<NamedDecl *>(TParam),
8801                                             SourceLocation(),
8802                                             /*RequiresClause=*/nullptr);
8803   return BuildExprRequirement(
8804       E, /*IsSimple=*/false, NoexceptLoc,
8805       concepts::ExprRequirement::ReturnTypeRequirement(TPL));
8806 }
8807 
8808 concepts::ExprRequirement *
8809 Sema::BuildExprRequirement(
8810     Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
8811     concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
8812   auto Status = concepts::ExprRequirement::SS_Satisfied;
8813   ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
8814   if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent())
8815     Status = concepts::ExprRequirement::SS_Dependent;
8816   else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
8817     Status = concepts::ExprRequirement::SS_NoexceptNotMet;
8818   else if (ReturnTypeRequirement.isSubstitutionFailure())
8819     Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure;
8820   else if (ReturnTypeRequirement.isTypeConstraint()) {
8821     // C++2a [expr.prim.req]p1.3.3
8822     //     The immediately-declared constraint ([temp]) of decltype((E)) shall
8823     //     be satisfied.
8824     TemplateParameterList *TPL =
8825         ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
8826     QualType MatchedType =
8827         Context.getReferenceQualifiedType(E).getCanonicalType();
8828     llvm::SmallVector<TemplateArgument, 1> Args;
8829     Args.push_back(TemplateArgument(MatchedType));
8830     TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args);
8831     MultiLevelTemplateArgumentList MLTAL(TAL);
8832     for (unsigned I = 0; I < TPL->getDepth(); ++I)
8833       MLTAL.addOuterRetainedLevel();
8834     Expr *IDC =
8835         cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint()
8836             ->getImmediatelyDeclaredConstraint();
8837     ExprResult Constraint = SubstExpr(IDC, MLTAL);
8838     assert(!Constraint.isInvalid() &&
8839            "Substitution cannot fail as it is simply putting a type template "
8840            "argument into a concept specialization expression's parameter.");
8841 
8842     SubstitutedConstraintExpr =
8843         cast<ConceptSpecializationExpr>(Constraint.get());
8844     if (!SubstitutedConstraintExpr->isSatisfied())
8845       Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
8846   }
8847   return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
8848                                                  ReturnTypeRequirement, Status,
8849                                                  SubstitutedConstraintExpr);
8850 }
8851 
8852 concepts::ExprRequirement *
8853 Sema::BuildExprRequirement(
8854     concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
8855     bool IsSimple, SourceLocation NoexceptLoc,
8856     concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
8857   return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
8858                                                  IsSimple, NoexceptLoc,
8859                                                  ReturnTypeRequirement);
8860 }
8861 
8862 concepts::TypeRequirement *
8863 Sema::BuildTypeRequirement(TypeSourceInfo *Type) {
8864   return new (Context) concepts::TypeRequirement(Type);
8865 }
8866 
8867 concepts::TypeRequirement *
8868 Sema::BuildTypeRequirement(
8869     concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
8870   return new (Context) concepts::TypeRequirement(SubstDiag);
8871 }
8872 
8873 concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) {
8874   return BuildNestedRequirement(Constraint);
8875 }
8876 
8877 concepts::NestedRequirement *
8878 Sema::BuildNestedRequirement(Expr *Constraint) {
8879   ConstraintSatisfaction Satisfaction;
8880   if (!Constraint->isInstantiationDependent() &&
8881       CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
8882                                   Constraint->getSourceRange(), Satisfaction))
8883     return nullptr;
8884   return new (Context) concepts::NestedRequirement(Context, Constraint,
8885                                                    Satisfaction);
8886 }
8887 
8888 concepts::NestedRequirement *
8889 Sema::BuildNestedRequirement(
8890     concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
8891   return new (Context) concepts::NestedRequirement(SubstDiag);
8892 }
8893 
8894 RequiresExprBodyDecl *
8895 Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8896                              ArrayRef<ParmVarDecl *> LocalParameters,
8897                              Scope *BodyScope) {
8898   assert(BodyScope);
8899 
8900   RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext,
8901                                                             RequiresKWLoc);
8902 
8903   PushDeclContext(BodyScope, Body);
8904 
8905   for (ParmVarDecl *Param : LocalParameters) {
8906     if (Param->hasDefaultArg())
8907       // C++2a [expr.prim.req] p4
8908       //     [...] A local parameter of a requires-expression shall not have a
8909       //     default argument. [...]
8910       Diag(Param->getDefaultArgRange().getBegin(),
8911            diag::err_requires_expr_local_parameter_default_argument);
8912     // Ignore default argument and move on
8913 
8914     Param->setDeclContext(Body);
8915     // If this has an identifier, add it to the scope stack.
8916     if (Param->getIdentifier()) {
8917       CheckShadow(BodyScope, Param);
8918       PushOnScopeChains(Param, BodyScope);
8919     }
8920   }
8921   return Body;
8922 }
8923 
8924 void Sema::ActOnFinishRequiresExpr() {
8925   assert(CurContext && "DeclContext imbalance!");
8926   CurContext = CurContext->getLexicalParent();
8927   assert(CurContext && "Popped translation unit!");
8928 }
8929 
8930 ExprResult
8931 Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8932                         RequiresExprBodyDecl *Body,
8933                         ArrayRef<ParmVarDecl *> LocalParameters,
8934                         ArrayRef<concepts::Requirement *> Requirements,
8935                         SourceLocation ClosingBraceLoc) {
8936   auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters,
8937                                   Requirements, ClosingBraceLoc);
8938   if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE))
8939     return ExprError();
8940   return RE;
8941 }
8942