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