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