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