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