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