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_SVE_Vector_Conversion:
4327     From = ImpCastExprToType(From, ToType, CK_BitCast, VK_RValue,
4328                              /*BasePath=*/nullptr, CCK)
4329                .get();
4330     break;
4331 
4332   case ICK_Vector_Splat: {
4333     // Vector splat from any arithmetic type to a vector.
4334     Expr *Elem = prepareVectorSplat(ToType, From).get();
4335     From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4336                              /*BasePath=*/nullptr, CCK).get();
4337     break;
4338   }
4339 
4340   case ICK_Complex_Real:
4341     // Case 1.  x -> _Complex y
4342     if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4343       QualType ElType = ToComplex->getElementType();
4344       bool isFloatingComplex = ElType->isRealFloatingType();
4345 
4346       // x -> y
4347       if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4348         // do nothing
4349       } else if (From->getType()->isRealFloatingType()) {
4350         From = ImpCastExprToType(From, ElType,
4351                 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4352       } else {
4353         assert(From->getType()->isIntegerType());
4354         From = ImpCastExprToType(From, ElType,
4355                 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4356       }
4357       // y -> _Complex y
4358       From = ImpCastExprToType(From, ToType,
4359                    isFloatingComplex ? CK_FloatingRealToComplex
4360                                      : CK_IntegralRealToComplex).get();
4361 
4362     // Case 2.  _Complex x -> y
4363     } else {
4364       auto *FromComplex = From->getType()->castAs<ComplexType>();
4365       QualType ElType = FromComplex->getElementType();
4366       bool isFloatingComplex = ElType->isRealFloatingType();
4367 
4368       // _Complex x -> x
4369       From = ImpCastExprToType(From, ElType,
4370                    isFloatingComplex ? CK_FloatingComplexToReal
4371                                      : CK_IntegralComplexToReal,
4372                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
4373 
4374       // x -> y
4375       if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4376         // do nothing
4377       } else if (ToType->isRealFloatingType()) {
4378         From = ImpCastExprToType(From, ToType,
4379                    isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
4380                                  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4381       } else {
4382         assert(ToType->isIntegerType());
4383         From = ImpCastExprToType(From, ToType,
4384                    isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
4385                                  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4386       }
4387     }
4388     break;
4389 
4390   case ICK_Block_Pointer_Conversion: {
4391     LangAS AddrSpaceL =
4392         ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4393     LangAS AddrSpaceR =
4394         FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4395     assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4396            "Invalid cast");
4397     CastKind Kind =
4398         AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4399     From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4400                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
4401     break;
4402   }
4403 
4404   case ICK_TransparentUnionConversion: {
4405     ExprResult FromRes = From;
4406     Sema::AssignConvertType ConvTy =
4407       CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4408     if (FromRes.isInvalid())
4409       return ExprError();
4410     From = FromRes.get();
4411     assert ((ConvTy == Sema::Compatible) &&
4412             "Improper transparent union conversion");
4413     (void)ConvTy;
4414     break;
4415   }
4416 
4417   case ICK_Zero_Event_Conversion:
4418   case ICK_Zero_Queue_Conversion:
4419     From = ImpCastExprToType(From, ToType,
4420                              CK_ZeroToOCLOpaqueType,
4421                              From->getValueKind()).get();
4422     break;
4423 
4424   case ICK_Lvalue_To_Rvalue:
4425   case ICK_Array_To_Pointer:
4426   case ICK_Function_To_Pointer:
4427   case ICK_Function_Conversion:
4428   case ICK_Qualification:
4429   case ICK_Num_Conversion_Kinds:
4430   case ICK_C_Only_Conversion:
4431   case ICK_Incompatible_Pointer_Conversion:
4432     llvm_unreachable("Improper second standard conversion");
4433   }
4434 
4435   switch (SCS.Third) {
4436   case ICK_Identity:
4437     // Nothing to do.
4438     break;
4439 
4440   case ICK_Function_Conversion:
4441     // If both sides are functions (or pointers/references to them), there could
4442     // be incompatible exception declarations.
4443     if (CheckExceptionSpecCompatibility(From, ToType))
4444       return ExprError();
4445 
4446     From = ImpCastExprToType(From, ToType, CK_NoOp,
4447                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
4448     break;
4449 
4450   case ICK_Qualification: {
4451     ExprValueKind VK = From->getValueKind();
4452     CastKind CK = CK_NoOp;
4453 
4454     if (ToType->isReferenceType() &&
4455         ToType->getPointeeType().getAddressSpace() !=
4456             From->getType().getAddressSpace())
4457       CK = CK_AddressSpaceConversion;
4458 
4459     if (ToType->isPointerType() &&
4460         ToType->getPointeeType().getAddressSpace() !=
4461             From->getType()->getPointeeType().getAddressSpace())
4462       CK = CK_AddressSpaceConversion;
4463 
4464     From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4465                              /*BasePath=*/nullptr, CCK)
4466                .get();
4467 
4468     if (SCS.DeprecatedStringLiteralToCharPtr &&
4469         !getLangOpts().WritableStrings) {
4470       Diag(From->getBeginLoc(),
4471            getLangOpts().CPlusPlus11
4472                ? diag::ext_deprecated_string_literal_conversion
4473                : diag::warn_deprecated_string_literal_conversion)
4474           << ToType.getNonReferenceType();
4475     }
4476 
4477     break;
4478   }
4479 
4480   default:
4481     llvm_unreachable("Improper third standard conversion");
4482   }
4483 
4484   // If this conversion sequence involved a scalar -> atomic conversion, perform
4485   // that conversion now.
4486   if (!ToAtomicType.isNull()) {
4487     assert(Context.hasSameType(
4488         ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4489     From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4490                              VK_RValue, nullptr, CCK).get();
4491   }
4492 
4493   // Materialize a temporary if we're implicitly converting to a reference
4494   // type. This is not required by the C++ rules but is necessary to maintain
4495   // AST invariants.
4496   if (ToType->isReferenceType() && From->isRValue()) {
4497     ExprResult Res = TemporaryMaterializationConversion(From);
4498     if (Res.isInvalid())
4499       return ExprError();
4500     From = Res.get();
4501   }
4502 
4503   // If this conversion sequence succeeded and involved implicitly converting a
4504   // _Nullable type to a _Nonnull one, complain.
4505   if (!isCast(CCK))
4506     diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4507                                         From->getBeginLoc());
4508 
4509   return From;
4510 }
4511 
4512 /// Check the completeness of a type in a unary type trait.
4513 ///
4514 /// If the particular type trait requires a complete type, tries to complete
4515 /// it. If completing the type fails, a diagnostic is emitted and false
4516 /// returned. If completing the type succeeds or no completion was required,
4517 /// returns true.
4518 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4519                                                 SourceLocation Loc,
4520                                                 QualType ArgTy) {
4521   // C++0x [meta.unary.prop]p3:
4522   //   For all of the class templates X declared in this Clause, instantiating
4523   //   that template with a template argument that is a class template
4524   //   specialization may result in the implicit instantiation of the template
4525   //   argument if and only if the semantics of X require that the argument
4526   //   must be a complete type.
4527   // We apply this rule to all the type trait expressions used to implement
4528   // these class templates. We also try to follow any GCC documented behavior
4529   // in these expressions to ensure portability of standard libraries.
4530   switch (UTT) {
4531   default: llvm_unreachable("not a UTT");
4532     // is_complete_type somewhat obviously cannot require a complete type.
4533   case UTT_IsCompleteType:
4534     // Fall-through
4535 
4536     // These traits are modeled on the type predicates in C++0x
4537     // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4538     // requiring a complete type, as whether or not they return true cannot be
4539     // impacted by the completeness of the type.
4540   case UTT_IsVoid:
4541   case UTT_IsIntegral:
4542   case UTT_IsFloatingPoint:
4543   case UTT_IsArray:
4544   case UTT_IsPointer:
4545   case UTT_IsLvalueReference:
4546   case UTT_IsRvalueReference:
4547   case UTT_IsMemberFunctionPointer:
4548   case UTT_IsMemberObjectPointer:
4549   case UTT_IsEnum:
4550   case UTT_IsUnion:
4551   case UTT_IsClass:
4552   case UTT_IsFunction:
4553   case UTT_IsReference:
4554   case UTT_IsArithmetic:
4555   case UTT_IsFundamental:
4556   case UTT_IsObject:
4557   case UTT_IsScalar:
4558   case UTT_IsCompound:
4559   case UTT_IsMemberPointer:
4560     // Fall-through
4561 
4562     // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4563     // which requires some of its traits to have the complete type. However,
4564     // the completeness of the type cannot impact these traits' semantics, and
4565     // so they don't require it. This matches the comments on these traits in
4566     // Table 49.
4567   case UTT_IsConst:
4568   case UTT_IsVolatile:
4569   case UTT_IsSigned:
4570   case UTT_IsUnsigned:
4571 
4572   // This type trait always returns false, checking the type is moot.
4573   case UTT_IsInterfaceClass:
4574     return true;
4575 
4576   // C++14 [meta.unary.prop]:
4577   //   If T is a non-union class type, T shall be a complete type.
4578   case UTT_IsEmpty:
4579   case UTT_IsPolymorphic:
4580   case UTT_IsAbstract:
4581     if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4582       if (!RD->isUnion())
4583         return !S.RequireCompleteType(
4584             Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4585     return true;
4586 
4587   // C++14 [meta.unary.prop]:
4588   //   If T is a class type, T shall be a complete type.
4589   case UTT_IsFinal:
4590   case UTT_IsSealed:
4591     if (ArgTy->getAsCXXRecordDecl())
4592       return !S.RequireCompleteType(
4593           Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4594     return true;
4595 
4596   // C++1z [meta.unary.prop]:
4597   //   remove_all_extents_t<T> shall be a complete type or cv void.
4598   case UTT_IsAggregate:
4599   case UTT_IsTrivial:
4600   case UTT_IsTriviallyCopyable:
4601   case UTT_IsStandardLayout:
4602   case UTT_IsPOD:
4603   case UTT_IsLiteral:
4604   // Per the GCC type traits documentation, T shall be a complete type, cv void,
4605   // or an array of unknown bound. But GCC actually imposes the same constraints
4606   // as above.
4607   case UTT_HasNothrowAssign:
4608   case UTT_HasNothrowMoveAssign:
4609   case UTT_HasNothrowConstructor:
4610   case UTT_HasNothrowCopy:
4611   case UTT_HasTrivialAssign:
4612   case UTT_HasTrivialMoveAssign:
4613   case UTT_HasTrivialDefaultConstructor:
4614   case UTT_HasTrivialMoveConstructor:
4615   case UTT_HasTrivialCopy:
4616   case UTT_HasTrivialDestructor:
4617   case UTT_HasVirtualDestructor:
4618     ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4619     LLVM_FALLTHROUGH;
4620 
4621   // C++1z [meta.unary.prop]:
4622   //   T shall be a complete type, cv void, or an array of unknown bound.
4623   case UTT_IsDestructible:
4624   case UTT_IsNothrowDestructible:
4625   case UTT_IsTriviallyDestructible:
4626   case UTT_HasUniqueObjectRepresentations:
4627     if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4628       return true;
4629 
4630     return !S.RequireCompleteType(
4631         Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4632   }
4633 }
4634 
4635 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4636                                Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4637                                bool (CXXRecordDecl::*HasTrivial)() const,
4638                                bool (CXXRecordDecl::*HasNonTrivial)() const,
4639                                bool (CXXMethodDecl::*IsDesiredOp)() const)
4640 {
4641   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4642   if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4643     return true;
4644 
4645   DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4646   DeclarationNameInfo NameInfo(Name, KeyLoc);
4647   LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4648   if (Self.LookupQualifiedName(Res, RD)) {
4649     bool FoundOperator = false;
4650     Res.suppressDiagnostics();
4651     for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4652          Op != OpEnd; ++Op) {
4653       if (isa<FunctionTemplateDecl>(*Op))
4654         continue;
4655 
4656       CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4657       if((Operator->*IsDesiredOp)()) {
4658         FoundOperator = true;
4659         auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
4660         CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4661         if (!CPT || !CPT->isNothrow())
4662           return false;
4663       }
4664     }
4665     return FoundOperator;
4666   }
4667   return false;
4668 }
4669 
4670 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4671                                    SourceLocation KeyLoc, QualType T) {
4672   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4673 
4674   ASTContext &C = Self.Context;
4675   switch(UTT) {
4676   default: llvm_unreachable("not a UTT");
4677     // Type trait expressions corresponding to the primary type category
4678     // predicates in C++0x [meta.unary.cat].
4679   case UTT_IsVoid:
4680     return T->isVoidType();
4681   case UTT_IsIntegral:
4682     return T->isIntegralType(C);
4683   case UTT_IsFloatingPoint:
4684     return T->isFloatingType();
4685   case UTT_IsArray:
4686     return T->isArrayType();
4687   case UTT_IsPointer:
4688     return T->isAnyPointerType();
4689   case UTT_IsLvalueReference:
4690     return T->isLValueReferenceType();
4691   case UTT_IsRvalueReference:
4692     return T->isRValueReferenceType();
4693   case UTT_IsMemberFunctionPointer:
4694     return T->isMemberFunctionPointerType();
4695   case UTT_IsMemberObjectPointer:
4696     return T->isMemberDataPointerType();
4697   case UTT_IsEnum:
4698     return T->isEnumeralType();
4699   case UTT_IsUnion:
4700     return T->isUnionType();
4701   case UTT_IsClass:
4702     return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4703   case UTT_IsFunction:
4704     return T->isFunctionType();
4705 
4706     // Type trait expressions which correspond to the convenient composition
4707     // predicates in C++0x [meta.unary.comp].
4708   case UTT_IsReference:
4709     return T->isReferenceType();
4710   case UTT_IsArithmetic:
4711     return T->isArithmeticType() && !T->isEnumeralType();
4712   case UTT_IsFundamental:
4713     return T->isFundamentalType();
4714   case UTT_IsObject:
4715     return T->isObjectType();
4716   case UTT_IsScalar:
4717     // Note: semantic analysis depends on Objective-C lifetime types to be
4718     // considered scalar types. However, such types do not actually behave
4719     // like scalar types at run time (since they may require retain/release
4720     // operations), so we report them as non-scalar.
4721     if (T->isObjCLifetimeType()) {
4722       switch (T.getObjCLifetime()) {
4723       case Qualifiers::OCL_None:
4724       case Qualifiers::OCL_ExplicitNone:
4725         return true;
4726 
4727       case Qualifiers::OCL_Strong:
4728       case Qualifiers::OCL_Weak:
4729       case Qualifiers::OCL_Autoreleasing:
4730         return false;
4731       }
4732     }
4733 
4734     return T->isScalarType();
4735   case UTT_IsCompound:
4736     return T->isCompoundType();
4737   case UTT_IsMemberPointer:
4738     return T->isMemberPointerType();
4739 
4740     // Type trait expressions which correspond to the type property predicates
4741     // in C++0x [meta.unary.prop].
4742   case UTT_IsConst:
4743     return T.isConstQualified();
4744   case UTT_IsVolatile:
4745     return T.isVolatileQualified();
4746   case UTT_IsTrivial:
4747     return T.isTrivialType(C);
4748   case UTT_IsTriviallyCopyable:
4749     return T.isTriviallyCopyableType(C);
4750   case UTT_IsStandardLayout:
4751     return T->isStandardLayoutType();
4752   case UTT_IsPOD:
4753     return T.isPODType(C);
4754   case UTT_IsLiteral:
4755     return T->isLiteralType(C);
4756   case UTT_IsEmpty:
4757     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4758       return !RD->isUnion() && RD->isEmpty();
4759     return false;
4760   case UTT_IsPolymorphic:
4761     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4762       return !RD->isUnion() && RD->isPolymorphic();
4763     return false;
4764   case UTT_IsAbstract:
4765     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4766       return !RD->isUnion() && RD->isAbstract();
4767     return false;
4768   case UTT_IsAggregate:
4769     // Report vector extensions and complex types as aggregates because they
4770     // support aggregate initialization. GCC mirrors this behavior for vectors
4771     // but not _Complex.
4772     return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4773            T->isAnyComplexType();
4774   // __is_interface_class only returns true when CL is invoked in /CLR mode and
4775   // even then only when it is used with the 'interface struct ...' syntax
4776   // Clang doesn't support /CLR which makes this type trait moot.
4777   case UTT_IsInterfaceClass:
4778     return false;
4779   case UTT_IsFinal:
4780   case UTT_IsSealed:
4781     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4782       return RD->hasAttr<FinalAttr>();
4783     return false;
4784   case UTT_IsSigned:
4785     // Enum types should always return false.
4786     // Floating points should always return true.
4787     return !T->isEnumeralType() && (T->isFloatingType() || T->isSignedIntegerType());
4788   case UTT_IsUnsigned:
4789     return T->isUnsignedIntegerType();
4790 
4791     // Type trait expressions which query classes regarding their construction,
4792     // destruction, and copying. Rather than being based directly on the
4793     // related type predicates in the standard, they are specified by both
4794     // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4795     // specifications.
4796     //
4797     //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4798     //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4799     //
4800     // Note that these builtins do not behave as documented in g++: if a class
4801     // has both a trivial and a non-trivial special member of a particular kind,
4802     // they return false! For now, we emulate this behavior.
4803     // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4804     // does not correctly compute triviality in the presence of multiple special
4805     // members of the same kind. Revisit this once the g++ bug is fixed.
4806   case UTT_HasTrivialDefaultConstructor:
4807     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4808     //   If __is_pod (type) is true then the trait is true, else if type is
4809     //   a cv class or union type (or array thereof) with a trivial default
4810     //   constructor ([class.ctor]) then the trait is true, else it is false.
4811     if (T.isPODType(C))
4812       return true;
4813     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4814       return RD->hasTrivialDefaultConstructor() &&
4815              !RD->hasNonTrivialDefaultConstructor();
4816     return false;
4817   case UTT_HasTrivialMoveConstructor:
4818     //  This trait is implemented by MSVC 2012 and needed to parse the
4819     //  standard library headers. Specifically this is used as the logic
4820     //  behind std::is_trivially_move_constructible (20.9.4.3).
4821     if (T.isPODType(C))
4822       return true;
4823     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4824       return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4825     return false;
4826   case UTT_HasTrivialCopy:
4827     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4828     //   If __is_pod (type) is true or type is a reference type then
4829     //   the trait is true, else if type is a cv class or union type
4830     //   with a trivial copy constructor ([class.copy]) then the trait
4831     //   is true, else it is false.
4832     if (T.isPODType(C) || T->isReferenceType())
4833       return true;
4834     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4835       return RD->hasTrivialCopyConstructor() &&
4836              !RD->hasNonTrivialCopyConstructor();
4837     return false;
4838   case UTT_HasTrivialMoveAssign:
4839     //  This trait is implemented by MSVC 2012 and needed to parse the
4840     //  standard library headers. Specifically it is used as the logic
4841     //  behind std::is_trivially_move_assignable (20.9.4.3)
4842     if (T.isPODType(C))
4843       return true;
4844     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4845       return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4846     return false;
4847   case UTT_HasTrivialAssign:
4848     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4849     //   If type is const qualified or is a reference type then the
4850     //   trait is false. Otherwise if __is_pod (type) is true then the
4851     //   trait is true, else if type is a cv class or union type with
4852     //   a trivial copy assignment ([class.copy]) then the trait is
4853     //   true, else it is false.
4854     // Note: the const and reference restrictions are interesting,
4855     // given that const and reference members don't prevent a class
4856     // from having a trivial copy assignment operator (but do cause
4857     // errors if the copy assignment operator is actually used, q.v.
4858     // [class.copy]p12).
4859 
4860     if (T.isConstQualified())
4861       return false;
4862     if (T.isPODType(C))
4863       return true;
4864     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4865       return RD->hasTrivialCopyAssignment() &&
4866              !RD->hasNonTrivialCopyAssignment();
4867     return false;
4868   case UTT_IsDestructible:
4869   case UTT_IsTriviallyDestructible:
4870   case UTT_IsNothrowDestructible:
4871     // C++14 [meta.unary.prop]:
4872     //   For reference types, is_destructible<T>::value is true.
4873     if (T->isReferenceType())
4874       return true;
4875 
4876     // Objective-C++ ARC: autorelease types don't require destruction.
4877     if (T->isObjCLifetimeType() &&
4878         T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4879       return true;
4880 
4881     // C++14 [meta.unary.prop]:
4882     //   For incomplete types and function types, is_destructible<T>::value is
4883     //   false.
4884     if (T->isIncompleteType() || T->isFunctionType())
4885       return false;
4886 
4887     // A type that requires destruction (via a non-trivial destructor or ARC
4888     // lifetime semantics) is not trivially-destructible.
4889     if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4890       return false;
4891 
4892     // C++14 [meta.unary.prop]:
4893     //   For object types and given U equal to remove_all_extents_t<T>, if the
4894     //   expression std::declval<U&>().~U() is well-formed when treated as an
4895     //   unevaluated operand (Clause 5), then is_destructible<T>::value is true
4896     if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4897       CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4898       if (!Destructor)
4899         return false;
4900       //  C++14 [dcl.fct.def.delete]p2:
4901       //    A program that refers to a deleted function implicitly or
4902       //    explicitly, other than to declare it, is ill-formed.
4903       if (Destructor->isDeleted())
4904         return false;
4905       if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4906         return false;
4907       if (UTT == UTT_IsNothrowDestructible) {
4908         auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
4909         CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4910         if (!CPT || !CPT->isNothrow())
4911           return false;
4912       }
4913     }
4914     return true;
4915 
4916   case UTT_HasTrivialDestructor:
4917     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4918     //   If __is_pod (type) is true or type is a reference type
4919     //   then the trait is true, else if type is a cv class or union
4920     //   type (or array thereof) with a trivial destructor
4921     //   ([class.dtor]) then the trait is true, else it is
4922     //   false.
4923     if (T.isPODType(C) || T->isReferenceType())
4924       return true;
4925 
4926     // Objective-C++ ARC: autorelease types don't require destruction.
4927     if (T->isObjCLifetimeType() &&
4928         T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4929       return true;
4930 
4931     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4932       return RD->hasTrivialDestructor();
4933     return false;
4934   // TODO: Propagate nothrowness for implicitly declared special members.
4935   case UTT_HasNothrowAssign:
4936     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4937     //   If type is const qualified or is a reference type then the
4938     //   trait is false. Otherwise if __has_trivial_assign (type)
4939     //   is true then the trait is true, else if type is a cv class
4940     //   or union type with copy assignment operators that are known
4941     //   not to throw an exception then the trait is true, else it is
4942     //   false.
4943     if (C.getBaseElementType(T).isConstQualified())
4944       return false;
4945     if (T->isReferenceType())
4946       return false;
4947     if (T.isPODType(C) || T->isObjCLifetimeType())
4948       return true;
4949 
4950     if (const RecordType *RT = T->getAs<RecordType>())
4951       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4952                                 &CXXRecordDecl::hasTrivialCopyAssignment,
4953                                 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4954                                 &CXXMethodDecl::isCopyAssignmentOperator);
4955     return false;
4956   case UTT_HasNothrowMoveAssign:
4957     //  This trait is implemented by MSVC 2012 and needed to parse the
4958     //  standard library headers. Specifically this is used as the logic
4959     //  behind std::is_nothrow_move_assignable (20.9.4.3).
4960     if (T.isPODType(C))
4961       return true;
4962 
4963     if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4964       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4965                                 &CXXRecordDecl::hasTrivialMoveAssignment,
4966                                 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4967                                 &CXXMethodDecl::isMoveAssignmentOperator);
4968     return false;
4969   case UTT_HasNothrowCopy:
4970     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4971     //   If __has_trivial_copy (type) is true then the trait is true, else
4972     //   if type is a cv class or union type with copy constructors that are
4973     //   known not to throw an exception then the trait is true, else it is
4974     //   false.
4975     if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4976       return true;
4977     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4978       if (RD->hasTrivialCopyConstructor() &&
4979           !RD->hasNonTrivialCopyConstructor())
4980         return true;
4981 
4982       bool FoundConstructor = false;
4983       unsigned FoundTQs;
4984       for (const auto *ND : Self.LookupConstructors(RD)) {
4985         // A template constructor is never a copy constructor.
4986         // FIXME: However, it may actually be selected at the actual overload
4987         // resolution point.
4988         if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4989           continue;
4990         // UsingDecl itself is not a constructor
4991         if (isa<UsingDecl>(ND))
4992           continue;
4993         auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4994         if (Constructor->isCopyConstructor(FoundTQs)) {
4995           FoundConstructor = true;
4996           auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
4997           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4998           if (!CPT)
4999             return false;
5000           // TODO: check whether evaluating default arguments can throw.
5001           // For now, we'll be conservative and assume that they can throw.
5002           if (!CPT->isNothrow() || CPT->getNumParams() > 1)
5003             return false;
5004         }
5005       }
5006 
5007       return FoundConstructor;
5008     }
5009     return false;
5010   case UTT_HasNothrowConstructor:
5011     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5012     //   If __has_trivial_constructor (type) is true then the trait is
5013     //   true, else if type is a cv class or union type (or array
5014     //   thereof) with a default constructor that is known not to
5015     //   throw an exception then the trait is true, else it is false.
5016     if (T.isPODType(C) || T->isObjCLifetimeType())
5017       return true;
5018     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5019       if (RD->hasTrivialDefaultConstructor() &&
5020           !RD->hasNonTrivialDefaultConstructor())
5021         return true;
5022 
5023       bool FoundConstructor = false;
5024       for (const auto *ND : Self.LookupConstructors(RD)) {
5025         // FIXME: In C++0x, a constructor template can be a default constructor.
5026         if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5027           continue;
5028         // UsingDecl itself is not a constructor
5029         if (isa<UsingDecl>(ND))
5030           continue;
5031         auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5032         if (Constructor->isDefaultConstructor()) {
5033           FoundConstructor = true;
5034           auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5035           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5036           if (!CPT)
5037             return false;
5038           // FIXME: check whether evaluating default arguments can throw.
5039           // For now, we'll be conservative and assume that they can throw.
5040           if (!CPT->isNothrow() || CPT->getNumParams() > 0)
5041             return false;
5042         }
5043       }
5044       return FoundConstructor;
5045     }
5046     return false;
5047   case UTT_HasVirtualDestructor:
5048     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5049     //   If type is a class type with a virtual destructor ([class.dtor])
5050     //   then the trait is true, else it is false.
5051     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5052       if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5053         return Destructor->isVirtual();
5054     return false;
5055 
5056     // These type trait expressions are modeled on the specifications for the
5057     // Embarcadero C++0x type trait functions:
5058     //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5059   case UTT_IsCompleteType:
5060     // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5061     //   Returns True if and only if T is a complete type at the point of the
5062     //   function call.
5063     return !T->isIncompleteType();
5064   case UTT_HasUniqueObjectRepresentations:
5065     return C.hasUniqueObjectRepresentations(T);
5066   }
5067 }
5068 
5069 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5070                                     QualType RhsT, SourceLocation KeyLoc);
5071 
5072 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
5073                               ArrayRef<TypeSourceInfo *> Args,
5074                               SourceLocation RParenLoc) {
5075   if (Kind <= UTT_Last)
5076     return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
5077 
5078   // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
5079   // traits to avoid duplication.
5080   if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
5081     return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
5082                                    Args[1]->getType(), RParenLoc);
5083 
5084   switch (Kind) {
5085   case clang::BTT_ReferenceBindsToTemporary:
5086   case clang::TT_IsConstructible:
5087   case clang::TT_IsNothrowConstructible:
5088   case clang::TT_IsTriviallyConstructible: {
5089     // C++11 [meta.unary.prop]:
5090     //   is_trivially_constructible is defined as:
5091     //
5092     //     is_constructible<T, Args...>::value is true and the variable
5093     //     definition for is_constructible, as defined below, is known to call
5094     //     no operation that is not trivial.
5095     //
5096     //   The predicate condition for a template specialization
5097     //   is_constructible<T, Args...> shall be satisfied if and only if the
5098     //   following variable definition would be well-formed for some invented
5099     //   variable t:
5100     //
5101     //     T t(create<Args>()...);
5102     assert(!Args.empty());
5103 
5104     // Precondition: T and all types in the parameter pack Args shall be
5105     // complete types, (possibly cv-qualified) void, or arrays of
5106     // unknown bound.
5107     for (const auto *TSI : Args) {
5108       QualType ArgTy = TSI->getType();
5109       if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
5110         continue;
5111 
5112       if (S.RequireCompleteType(KWLoc, ArgTy,
5113           diag::err_incomplete_type_used_in_type_trait_expr))
5114         return false;
5115     }
5116 
5117     // Make sure the first argument is not incomplete nor a function type.
5118     QualType T = Args[0]->getType();
5119     if (T->isIncompleteType() || T->isFunctionType())
5120       return false;
5121 
5122     // Make sure the first argument is not an abstract type.
5123     CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5124     if (RD && RD->isAbstract())
5125       return false;
5126 
5127     llvm::BumpPtrAllocator OpaqueExprAllocator;
5128     SmallVector<Expr *, 2> ArgExprs;
5129     ArgExprs.reserve(Args.size() - 1);
5130     for (unsigned I = 1, N = Args.size(); I != N; ++I) {
5131       QualType ArgTy = Args[I]->getType();
5132       if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5133         ArgTy = S.Context.getRValueReferenceType(ArgTy);
5134       ArgExprs.push_back(
5135           new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5136               OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
5137                               ArgTy.getNonLValueExprType(S.Context),
5138                               Expr::getValueKindForType(ArgTy)));
5139     }
5140 
5141     // Perform the initialization in an unevaluated context within a SFINAE
5142     // trap at translation unit scope.
5143     EnterExpressionEvaluationContext Unevaluated(
5144         S, Sema::ExpressionEvaluationContext::Unevaluated);
5145     Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5146     Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
5147     InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
5148     InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
5149                                                                  RParenLoc));
5150     InitializationSequence Init(S, To, InitKind, ArgExprs);
5151     if (Init.Failed())
5152       return false;
5153 
5154     ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5155     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5156       return false;
5157 
5158     if (Kind == clang::TT_IsConstructible)
5159       return true;
5160 
5161     if (Kind == clang::BTT_ReferenceBindsToTemporary) {
5162       if (!T->isReferenceType())
5163         return false;
5164 
5165       return !Init.isDirectReferenceBinding();
5166     }
5167 
5168     if (Kind == clang::TT_IsNothrowConstructible)
5169       return S.canThrow(Result.get()) == CT_Cannot;
5170 
5171     if (Kind == clang::TT_IsTriviallyConstructible) {
5172       // Under Objective-C ARC and Weak, if the destination has non-trivial
5173       // Objective-C lifetime, this is a non-trivial construction.
5174       if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5175         return false;
5176 
5177       // The initialization succeeded; now make sure there are no non-trivial
5178       // calls.
5179       return !Result.get()->hasNonTrivialCall(S.Context);
5180     }
5181 
5182     llvm_unreachable("unhandled type trait");
5183     return false;
5184   }
5185     default: llvm_unreachable("not a TT");
5186   }
5187 
5188   return false;
5189 }
5190 
5191 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5192                                 ArrayRef<TypeSourceInfo *> Args,
5193                                 SourceLocation RParenLoc) {
5194   QualType ResultType = Context.getLogicalOperationType();
5195 
5196   if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5197                                *this, Kind, KWLoc, Args[0]->getType()))
5198     return ExprError();
5199 
5200   bool Dependent = false;
5201   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5202     if (Args[I]->getType()->isDependentType()) {
5203       Dependent = true;
5204       break;
5205     }
5206   }
5207 
5208   bool Result = false;
5209   if (!Dependent)
5210     Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5211 
5212   return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5213                                RParenLoc, Result);
5214 }
5215 
5216 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5217                                 ArrayRef<ParsedType> Args,
5218                                 SourceLocation RParenLoc) {
5219   SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5220   ConvertedArgs.reserve(Args.size());
5221 
5222   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5223     TypeSourceInfo *TInfo;
5224     QualType T = GetTypeFromParser(Args[I], &TInfo);
5225     if (!TInfo)
5226       TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5227 
5228     ConvertedArgs.push_back(TInfo);
5229   }
5230 
5231   return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5232 }
5233 
5234 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5235                                     QualType RhsT, SourceLocation KeyLoc) {
5236   assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5237          "Cannot evaluate traits of dependent types");
5238 
5239   switch(BTT) {
5240   case BTT_IsBaseOf: {
5241     // C++0x [meta.rel]p2
5242     // Base is a base class of Derived without regard to cv-qualifiers or
5243     // Base and Derived are not unions and name the same class type without
5244     // regard to cv-qualifiers.
5245 
5246     const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5247     const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5248     if (!rhsRecord || !lhsRecord) {
5249       const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5250       const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5251       if (!LHSObjTy || !RHSObjTy)
5252         return false;
5253 
5254       ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5255       ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5256       if (!BaseInterface || !DerivedInterface)
5257         return false;
5258 
5259       if (Self.RequireCompleteType(
5260               KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5261         return false;
5262 
5263       return BaseInterface->isSuperClassOf(DerivedInterface);
5264     }
5265 
5266     assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5267              == (lhsRecord == rhsRecord));
5268 
5269     // Unions are never base classes, and never have base classes.
5270     // It doesn't matter if they are complete or not. See PR#41843
5271     if (lhsRecord && lhsRecord->getDecl()->isUnion())
5272       return false;
5273     if (rhsRecord && rhsRecord->getDecl()->isUnion())
5274       return false;
5275 
5276     if (lhsRecord == rhsRecord)
5277       return true;
5278 
5279     // C++0x [meta.rel]p2:
5280     //   If Base and Derived are class types and are different types
5281     //   (ignoring possible cv-qualifiers) then Derived shall be a
5282     //   complete type.
5283     if (Self.RequireCompleteType(KeyLoc, RhsT,
5284                           diag::err_incomplete_type_used_in_type_trait_expr))
5285       return false;
5286 
5287     return cast<CXXRecordDecl>(rhsRecord->getDecl())
5288       ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5289   }
5290   case BTT_IsSame:
5291     return Self.Context.hasSameType(LhsT, RhsT);
5292   case BTT_TypeCompatible: {
5293     // GCC ignores cv-qualifiers on arrays for this builtin.
5294     Qualifiers LhsQuals, RhsQuals;
5295     QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5296     QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5297     return Self.Context.typesAreCompatible(Lhs, Rhs);
5298   }
5299   case BTT_IsConvertible:
5300   case BTT_IsConvertibleTo: {
5301     // C++0x [meta.rel]p4:
5302     //   Given the following function prototype:
5303     //
5304     //     template <class T>
5305     //       typename add_rvalue_reference<T>::type create();
5306     //
5307     //   the predicate condition for a template specialization
5308     //   is_convertible<From, To> shall be satisfied if and only if
5309     //   the return expression in the following code would be
5310     //   well-formed, including any implicit conversions to the return
5311     //   type of the function:
5312     //
5313     //     To test() {
5314     //       return create<From>();
5315     //     }
5316     //
5317     //   Access checking is performed as if in a context unrelated to To and
5318     //   From. Only the validity of the immediate context of the expression
5319     //   of the return-statement (including conversions to the return type)
5320     //   is considered.
5321     //
5322     // We model the initialization as a copy-initialization of a temporary
5323     // of the appropriate type, which for this expression is identical to the
5324     // return statement (since NRVO doesn't apply).
5325 
5326     // Functions aren't allowed to return function or array types.
5327     if (RhsT->isFunctionType() || RhsT->isArrayType())
5328       return false;
5329 
5330     // A return statement in a void function must have void type.
5331     if (RhsT->isVoidType())
5332       return LhsT->isVoidType();
5333 
5334     // A function definition requires a complete, non-abstract return type.
5335     if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5336       return false;
5337 
5338     // Compute the result of add_rvalue_reference.
5339     if (LhsT->isObjectType() || LhsT->isFunctionType())
5340       LhsT = Self.Context.getRValueReferenceType(LhsT);
5341 
5342     // Build a fake source and destination for initialization.
5343     InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
5344     OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5345                          Expr::getValueKindForType(LhsT));
5346     Expr *FromPtr = &From;
5347     InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
5348                                                            SourceLocation()));
5349 
5350     // Perform the initialization in an unevaluated context within a SFINAE
5351     // trap at translation unit scope.
5352     EnterExpressionEvaluationContext Unevaluated(
5353         Self, Sema::ExpressionEvaluationContext::Unevaluated);
5354     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5355     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5356     InitializationSequence Init(Self, To, Kind, FromPtr);
5357     if (Init.Failed())
5358       return false;
5359 
5360     ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5361     return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5362   }
5363 
5364   case BTT_IsAssignable:
5365   case BTT_IsNothrowAssignable:
5366   case BTT_IsTriviallyAssignable: {
5367     // C++11 [meta.unary.prop]p3:
5368     //   is_trivially_assignable is defined as:
5369     //     is_assignable<T, U>::value is true and the assignment, as defined by
5370     //     is_assignable, is known to call no operation that is not trivial
5371     //
5372     //   is_assignable is defined as:
5373     //     The expression declval<T>() = declval<U>() is well-formed when
5374     //     treated as an unevaluated operand (Clause 5).
5375     //
5376     //   For both, T and U shall be complete types, (possibly cv-qualified)
5377     //   void, or arrays of unknown bound.
5378     if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5379         Self.RequireCompleteType(KeyLoc, LhsT,
5380           diag::err_incomplete_type_used_in_type_trait_expr))
5381       return false;
5382     if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5383         Self.RequireCompleteType(KeyLoc, RhsT,
5384           diag::err_incomplete_type_used_in_type_trait_expr))
5385       return false;
5386 
5387     // cv void is never assignable.
5388     if (LhsT->isVoidType() || RhsT->isVoidType())
5389       return false;
5390 
5391     // Build expressions that emulate the effect of declval<T>() and
5392     // declval<U>().
5393     if (LhsT->isObjectType() || LhsT->isFunctionType())
5394       LhsT = Self.Context.getRValueReferenceType(LhsT);
5395     if (RhsT->isObjectType() || RhsT->isFunctionType())
5396       RhsT = Self.Context.getRValueReferenceType(RhsT);
5397     OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5398                         Expr::getValueKindForType(LhsT));
5399     OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5400                         Expr::getValueKindForType(RhsT));
5401 
5402     // Attempt the assignment in an unevaluated context within a SFINAE
5403     // trap at translation unit scope.
5404     EnterExpressionEvaluationContext Unevaluated(
5405         Self, Sema::ExpressionEvaluationContext::Unevaluated);
5406     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5407     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5408     ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5409                                         &Rhs);
5410     if (Result.isInvalid())
5411       return false;
5412 
5413     // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
5414     Self.CheckUnusedVolatileAssignment(Result.get());
5415 
5416     if (SFINAE.hasErrorOccurred())
5417       return false;
5418 
5419     if (BTT == BTT_IsAssignable)
5420       return true;
5421 
5422     if (BTT == BTT_IsNothrowAssignable)
5423       return Self.canThrow(Result.get()) == CT_Cannot;
5424 
5425     if (BTT == BTT_IsTriviallyAssignable) {
5426       // Under Objective-C ARC and Weak, if the destination has non-trivial
5427       // Objective-C lifetime, this is a non-trivial assignment.
5428       if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
5429         return false;
5430 
5431       return !Result.get()->hasNonTrivialCall(Self.Context);
5432     }
5433 
5434     llvm_unreachable("unhandled type trait");
5435     return false;
5436   }
5437     default: llvm_unreachable("not a BTT");
5438   }
5439   llvm_unreachable("Unknown type trait or not implemented");
5440 }
5441 
5442 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5443                                      SourceLocation KWLoc,
5444                                      ParsedType Ty,
5445                                      Expr* DimExpr,
5446                                      SourceLocation RParen) {
5447   TypeSourceInfo *TSInfo;
5448   QualType T = GetTypeFromParser(Ty, &TSInfo);
5449   if (!TSInfo)
5450     TSInfo = Context.getTrivialTypeSourceInfo(T);
5451 
5452   return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5453 }
5454 
5455 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5456                                            QualType T, Expr *DimExpr,
5457                                            SourceLocation KeyLoc) {
5458   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5459 
5460   switch(ATT) {
5461   case ATT_ArrayRank:
5462     if (T->isArrayType()) {
5463       unsigned Dim = 0;
5464       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5465         ++Dim;
5466         T = AT->getElementType();
5467       }
5468       return Dim;
5469     }
5470     return 0;
5471 
5472   case ATT_ArrayExtent: {
5473     llvm::APSInt Value;
5474     uint64_t Dim;
5475     if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
5476           diag::err_dimension_expr_not_constant_integer,
5477           false).isInvalid())
5478       return 0;
5479     if (Value.isSigned() && Value.isNegative()) {
5480       Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5481         << DimExpr->getSourceRange();
5482       return 0;
5483     }
5484     Dim = Value.getLimitedValue();
5485 
5486     if (T->isArrayType()) {
5487       unsigned D = 0;
5488       bool Matched = false;
5489       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5490         if (Dim == D) {
5491           Matched = true;
5492           break;
5493         }
5494         ++D;
5495         T = AT->getElementType();
5496       }
5497 
5498       if (Matched && T->isArrayType()) {
5499         if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5500           return CAT->getSize().getLimitedValue();
5501       }
5502     }
5503     return 0;
5504   }
5505   }
5506   llvm_unreachable("Unknown type trait or not implemented");
5507 }
5508 
5509 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5510                                      SourceLocation KWLoc,
5511                                      TypeSourceInfo *TSInfo,
5512                                      Expr* DimExpr,
5513                                      SourceLocation RParen) {
5514   QualType T = TSInfo->getType();
5515 
5516   // FIXME: This should likely be tracked as an APInt to remove any host
5517   // assumptions about the width of size_t on the target.
5518   uint64_t Value = 0;
5519   if (!T->isDependentType())
5520     Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5521 
5522   // While the specification for these traits from the Embarcadero C++
5523   // compiler's documentation says the return type is 'unsigned int', Clang
5524   // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5525   // compiler, there is no difference. On several other platforms this is an
5526   // important distinction.
5527   return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5528                                           RParen, Context.getSizeType());
5529 }
5530 
5531 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
5532                                       SourceLocation KWLoc,
5533                                       Expr *Queried,
5534                                       SourceLocation RParen) {
5535   // If error parsing the expression, ignore.
5536   if (!Queried)
5537     return ExprError();
5538 
5539   ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5540 
5541   return Result;
5542 }
5543 
5544 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5545   switch (ET) {
5546   case ET_IsLValueExpr: return E->isLValue();
5547   case ET_IsRValueExpr: return E->isRValue();
5548   }
5549   llvm_unreachable("Expression trait not covered by switch");
5550 }
5551 
5552 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5553                                       SourceLocation KWLoc,
5554                                       Expr *Queried,
5555                                       SourceLocation RParen) {
5556   if (Queried->isTypeDependent()) {
5557     // Delay type-checking for type-dependent expressions.
5558   } else if (Queried->getType()->isPlaceholderType()) {
5559     ExprResult PE = CheckPlaceholderExpr(Queried);
5560     if (PE.isInvalid()) return ExprError();
5561     return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5562   }
5563 
5564   bool Value = EvaluateExpressionTrait(ET, Queried);
5565 
5566   return new (Context)
5567       ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5568 }
5569 
5570 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5571                                             ExprValueKind &VK,
5572                                             SourceLocation Loc,
5573                                             bool isIndirect) {
5574   assert(!LHS.get()->getType()->isPlaceholderType() &&
5575          !RHS.get()->getType()->isPlaceholderType() &&
5576          "placeholders should have been weeded out by now");
5577 
5578   // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5579   // temporary materialization conversion otherwise.
5580   if (isIndirect)
5581     LHS = DefaultLvalueConversion(LHS.get());
5582   else if (LHS.get()->isRValue())
5583     LHS = TemporaryMaterializationConversion(LHS.get());
5584   if (LHS.isInvalid())
5585     return QualType();
5586 
5587   // The RHS always undergoes lvalue conversions.
5588   RHS = DefaultLvalueConversion(RHS.get());
5589   if (RHS.isInvalid()) return QualType();
5590 
5591   const char *OpSpelling = isIndirect ? "->*" : ".*";
5592   // C++ 5.5p2
5593   //   The binary operator .* [p3: ->*] binds its second operand, which shall
5594   //   be of type "pointer to member of T" (where T is a completely-defined
5595   //   class type) [...]
5596   QualType RHSType = RHS.get()->getType();
5597   const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5598   if (!MemPtr) {
5599     Diag(Loc, diag::err_bad_memptr_rhs)
5600       << OpSpelling << RHSType << RHS.get()->getSourceRange();
5601     return QualType();
5602   }
5603 
5604   QualType Class(MemPtr->getClass(), 0);
5605 
5606   // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5607   // member pointer points must be completely-defined. However, there is no
5608   // reason for this semantic distinction, and the rule is not enforced by
5609   // other compilers. Therefore, we do not check this property, as it is
5610   // likely to be considered a defect.
5611 
5612   // C++ 5.5p2
5613   //   [...] to its first operand, which shall be of class T or of a class of
5614   //   which T is an unambiguous and accessible base class. [p3: a pointer to
5615   //   such a class]
5616   QualType LHSType = LHS.get()->getType();
5617   if (isIndirect) {
5618     if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5619       LHSType = Ptr->getPointeeType();
5620     else {
5621       Diag(Loc, diag::err_bad_memptr_lhs)
5622         << OpSpelling << 1 << LHSType
5623         << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5624       return QualType();
5625     }
5626   }
5627 
5628   if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5629     // If we want to check the hierarchy, we need a complete type.
5630     if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5631                             OpSpelling, (int)isIndirect)) {
5632       return QualType();
5633     }
5634 
5635     if (!IsDerivedFrom(Loc, LHSType, Class)) {
5636       Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5637         << (int)isIndirect << LHS.get()->getType();
5638       return QualType();
5639     }
5640 
5641     CXXCastPath BasePath;
5642     if (CheckDerivedToBaseConversion(
5643             LHSType, Class, Loc,
5644             SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
5645             &BasePath))
5646       return QualType();
5647 
5648     // Cast LHS to type of use.
5649     QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5650     if (isIndirect)
5651       UseType = Context.getPointerType(UseType);
5652     ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
5653     LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5654                             &BasePath);
5655   }
5656 
5657   if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5658     // Diagnose use of pointer-to-member type which when used as
5659     // the functional cast in a pointer-to-member expression.
5660     Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5661      return QualType();
5662   }
5663 
5664   // C++ 5.5p2
5665   //   The result is an object or a function of the type specified by the
5666   //   second operand.
5667   // The cv qualifiers are the union of those in the pointer and the left side,
5668   // in accordance with 5.5p5 and 5.2.5.
5669   QualType Result = MemPtr->getPointeeType();
5670   Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5671 
5672   // C++0x [expr.mptr.oper]p6:
5673   //   In a .* expression whose object expression is an rvalue, the program is
5674   //   ill-formed if the second operand is a pointer to member function with
5675   //   ref-qualifier &. In a ->* expression or in a .* expression whose object
5676   //   expression is an lvalue, the program is ill-formed if the second operand
5677   //   is a pointer to member function with ref-qualifier &&.
5678   if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5679     switch (Proto->getRefQualifier()) {
5680     case RQ_None:
5681       // Do nothing
5682       break;
5683 
5684     case RQ_LValue:
5685       if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5686         // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5687         // is (exactly) 'const'.
5688         if (Proto->isConst() && !Proto->isVolatile())
5689           Diag(Loc, getLangOpts().CPlusPlus20
5690                         ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5691                         : diag::ext_pointer_to_const_ref_member_on_rvalue);
5692         else
5693           Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5694               << RHSType << 1 << LHS.get()->getSourceRange();
5695       }
5696       break;
5697 
5698     case RQ_RValue:
5699       if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5700         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5701           << RHSType << 0 << LHS.get()->getSourceRange();
5702       break;
5703     }
5704   }
5705 
5706   // C++ [expr.mptr.oper]p6:
5707   //   The result of a .* expression whose second operand is a pointer
5708   //   to a data member is of the same value category as its
5709   //   first operand. The result of a .* expression whose second
5710   //   operand is a pointer to a member function is a prvalue. The
5711   //   result of an ->* expression is an lvalue if its second operand
5712   //   is a pointer to data member and a prvalue otherwise.
5713   if (Result->isFunctionType()) {
5714     VK = VK_RValue;
5715     return Context.BoundMemberTy;
5716   } else if (isIndirect) {
5717     VK = VK_LValue;
5718   } else {
5719     VK = LHS.get()->getValueKind();
5720   }
5721 
5722   return Result;
5723 }
5724 
5725 /// Try to convert a type to another according to C++11 5.16p3.
5726 ///
5727 /// This is part of the parameter validation for the ? operator. If either
5728 /// value operand is a class type, the two operands are attempted to be
5729 /// converted to each other. This function does the conversion in one direction.
5730 /// It returns true if the program is ill-formed and has already been diagnosed
5731 /// as such.
5732 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5733                                 SourceLocation QuestionLoc,
5734                                 bool &HaveConversion,
5735                                 QualType &ToType) {
5736   HaveConversion = false;
5737   ToType = To->getType();
5738 
5739   InitializationKind Kind =
5740       InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
5741   // C++11 5.16p3
5742   //   The process for determining whether an operand expression E1 of type T1
5743   //   can be converted to match an operand expression E2 of type T2 is defined
5744   //   as follows:
5745   //   -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5746   //      implicitly converted to type "lvalue reference to T2", subject to the
5747   //      constraint that in the conversion the reference must bind directly to
5748   //      an lvalue.
5749   //   -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5750   //      implicitly converted to the type "rvalue reference to R2", subject to
5751   //      the constraint that the reference must bind directly.
5752   if (To->isLValue() || To->isXValue()) {
5753     QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5754                                 : Self.Context.getRValueReferenceType(ToType);
5755 
5756     InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5757 
5758     InitializationSequence InitSeq(Self, Entity, Kind, From);
5759     if (InitSeq.isDirectReferenceBinding()) {
5760       ToType = T;
5761       HaveConversion = true;
5762       return false;
5763     }
5764 
5765     if (InitSeq.isAmbiguous())
5766       return InitSeq.Diagnose(Self, Entity, Kind, From);
5767   }
5768 
5769   //   -- If E2 is an rvalue, or if the conversion above cannot be done:
5770   //      -- if E1 and E2 have class type, and the underlying class types are
5771   //         the same or one is a base class of the other:
5772   QualType FTy = From->getType();
5773   QualType TTy = To->getType();
5774   const RecordType *FRec = FTy->getAs<RecordType>();
5775   const RecordType *TRec = TTy->getAs<RecordType>();
5776   bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5777                        Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5778   if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5779                        Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5780     //         E1 can be converted to match E2 if the class of T2 is the
5781     //         same type as, or a base class of, the class of T1, and
5782     //         [cv2 > cv1].
5783     if (FRec == TRec || FDerivedFromT) {
5784       if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5785         InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5786         InitializationSequence InitSeq(Self, Entity, Kind, From);
5787         if (InitSeq) {
5788           HaveConversion = true;
5789           return false;
5790         }
5791 
5792         if (InitSeq.isAmbiguous())
5793           return InitSeq.Diagnose(Self, Entity, Kind, From);
5794       }
5795     }
5796 
5797     return false;
5798   }
5799 
5800   //     -- Otherwise: E1 can be converted to match E2 if E1 can be
5801   //        implicitly converted to the type that expression E2 would have
5802   //        if E2 were converted to an rvalue (or the type it has, if E2 is
5803   //        an rvalue).
5804   //
5805   // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5806   // to the array-to-pointer or function-to-pointer conversions.
5807   TTy = TTy.getNonLValueExprType(Self.Context);
5808 
5809   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5810   InitializationSequence InitSeq(Self, Entity, Kind, From);
5811   HaveConversion = !InitSeq.Failed();
5812   ToType = TTy;
5813   if (InitSeq.isAmbiguous())
5814     return InitSeq.Diagnose(Self, Entity, Kind, From);
5815 
5816   return false;
5817 }
5818 
5819 /// Try to find a common type for two according to C++0x 5.16p5.
5820 ///
5821 /// This is part of the parameter validation for the ? operator. If either
5822 /// value operand is a class type, overload resolution is used to find a
5823 /// conversion to a common type.
5824 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5825                                     SourceLocation QuestionLoc) {
5826   Expr *Args[2] = { LHS.get(), RHS.get() };
5827   OverloadCandidateSet CandidateSet(QuestionLoc,
5828                                     OverloadCandidateSet::CSK_Operator);
5829   Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5830                                     CandidateSet);
5831 
5832   OverloadCandidateSet::iterator Best;
5833   switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5834     case OR_Success: {
5835       // We found a match. Perform the conversions on the arguments and move on.
5836       ExprResult LHSRes = Self.PerformImplicitConversion(
5837           LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5838           Sema::AA_Converting);
5839       if (LHSRes.isInvalid())
5840         break;
5841       LHS = LHSRes;
5842 
5843       ExprResult RHSRes = Self.PerformImplicitConversion(
5844           RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5845           Sema::AA_Converting);
5846       if (RHSRes.isInvalid())
5847         break;
5848       RHS = RHSRes;
5849       if (Best->Function)
5850         Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5851       return false;
5852     }
5853 
5854     case OR_No_Viable_Function:
5855 
5856       // Emit a better diagnostic if one of the expressions is a null pointer
5857       // constant and the other is a pointer type. In this case, the user most
5858       // likely forgot to take the address of the other expression.
5859       if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5860         return true;
5861 
5862       Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5863         << LHS.get()->getType() << RHS.get()->getType()
5864         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5865       return true;
5866 
5867     case OR_Ambiguous:
5868       Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5869         << LHS.get()->getType() << RHS.get()->getType()
5870         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5871       // FIXME: Print the possible common types by printing the return types of
5872       // the viable candidates.
5873       break;
5874 
5875     case OR_Deleted:
5876       llvm_unreachable("Conditional operator has only built-in overloads");
5877   }
5878   return true;
5879 }
5880 
5881 /// Perform an "extended" implicit conversion as returned by
5882 /// TryClassUnification.
5883 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5884   InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5885   InitializationKind Kind =
5886       InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
5887   Expr *Arg = E.get();
5888   InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5889   ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5890   if (Result.isInvalid())
5891     return true;
5892 
5893   E = Result;
5894   return false;
5895 }
5896 
5897 // Check the condition operand of ?: to see if it is valid for the GCC
5898 // extension.
5899 static bool isValidVectorForConditionalCondition(ASTContext &Ctx,
5900                                                  QualType CondTy) {
5901   if (!CondTy->isVectorType() || CondTy->isExtVectorType())
5902     return false;
5903   const QualType EltTy =
5904       cast<VectorType>(CondTy.getCanonicalType())->getElementType();
5905 
5906   assert(!EltTy->isBooleanType() && !EltTy->isEnumeralType() &&
5907          "Vectors cant be boolean or enum types");
5908   return EltTy->isIntegralType(Ctx);
5909 }
5910 
5911 QualType Sema::CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
5912                                               ExprResult &RHS,
5913                                               SourceLocation QuestionLoc) {
5914   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5915   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5916 
5917   QualType CondType = Cond.get()->getType();
5918   const auto *CondVT = CondType->castAs<VectorType>();
5919   QualType CondElementTy = CondVT->getElementType();
5920   unsigned CondElementCount = CondVT->getNumElements();
5921   QualType LHSType = LHS.get()->getType();
5922   const auto *LHSVT = LHSType->getAs<VectorType>();
5923   QualType RHSType = RHS.get()->getType();
5924   const auto *RHSVT = RHSType->getAs<VectorType>();
5925 
5926   QualType ResultType;
5927 
5928   // FIXME: In the future we should define what the Extvector conditional
5929   // operator looks like.
5930   if (LHSVT && isa<ExtVectorType>(LHSVT)) {
5931     Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5932         << /*isExtVector*/ true << LHSType;
5933     return {};
5934   }
5935 
5936   if (RHSVT && isa<ExtVectorType>(RHSVT)) {
5937     Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5938         << /*isExtVector*/ true << RHSType;
5939     return {};
5940   }
5941 
5942   if (LHSVT && RHSVT) {
5943     // If both are vector types, they must be the same type.
5944     if (!Context.hasSameType(LHSType, RHSType)) {
5945       Diag(QuestionLoc, diag::err_conditional_vector_mismatched_vectors)
5946           << LHSType << RHSType;
5947       return {};
5948     }
5949     ResultType = LHSType;
5950   } else if (LHSVT || RHSVT) {
5951     ResultType = CheckVectorOperands(
5952         LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
5953         /*AllowBoolConversions*/ false);
5954     if (ResultType.isNull())
5955       return {};
5956   } else {
5957     // Both are scalar.
5958     QualType ResultElementTy;
5959     LHSType = LHSType.getCanonicalType().getUnqualifiedType();
5960     RHSType = RHSType.getCanonicalType().getUnqualifiedType();
5961 
5962     if (Context.hasSameType(LHSType, RHSType))
5963       ResultElementTy = LHSType;
5964     else
5965       ResultElementTy =
5966           UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
5967 
5968     if (ResultElementTy->isEnumeralType()) {
5969       Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5970           << /*isExtVector*/ false << ResultElementTy;
5971       return {};
5972     }
5973     ResultType = Context.getVectorType(
5974         ResultElementTy, CondType->castAs<VectorType>()->getNumElements(),
5975         VectorType::GenericVector);
5976 
5977     LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
5978     RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
5979   }
5980 
5981   assert(!ResultType.isNull() && ResultType->isVectorType() &&
5982          "Result should have been a vector type");
5983   auto *ResultVectorTy = ResultType->castAs<VectorType>();
5984   QualType ResultElementTy = ResultVectorTy->getElementType();
5985   unsigned ResultElementCount = ResultVectorTy->getNumElements();
5986 
5987   if (ResultElementCount != CondElementCount) {
5988     Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
5989                                                          << ResultType;
5990     return {};
5991   }
5992 
5993   if (Context.getTypeSize(ResultElementTy) !=
5994       Context.getTypeSize(CondElementTy)) {
5995     Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
5996                                                                  << ResultType;
5997     return {};
5998   }
5999 
6000   return ResultType;
6001 }
6002 
6003 /// Check the operands of ?: under C++ semantics.
6004 ///
6005 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
6006 /// extension. In this case, LHS == Cond. (But they're not aliases.)
6007 ///
6008 /// This function also implements GCC's vector extension for conditionals.
6009 ///  GCC's vector extension permits the use of a?b:c where the type of
6010 ///  a is that of a integer vector with the same number of elements and
6011 ///  size as the vectors of b and c. If one of either b or c is a scalar
6012 ///  it is implicitly converted to match the type of the vector.
6013 ///  Otherwise the expression is ill-formed. If both b and c are scalars,
6014 ///  then b and c are checked and converted to the type of a if possible.
6015 ///  Unlike the OpenCL ?: operator, the expression is evaluated as
6016 ///  (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
6017 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6018                                            ExprResult &RHS, ExprValueKind &VK,
6019                                            ExprObjectKind &OK,
6020                                            SourceLocation QuestionLoc) {
6021   // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6022   // pointers.
6023 
6024   // Assume r-value.
6025   VK = VK_RValue;
6026   OK = OK_Ordinary;
6027   bool IsVectorConditional =
6028       isValidVectorForConditionalCondition(Context, Cond.get()->getType());
6029 
6030   // C++11 [expr.cond]p1
6031   //   The first expression is contextually converted to bool.
6032   if (!Cond.get()->isTypeDependent()) {
6033     ExprResult CondRes = IsVectorConditional
6034                              ? DefaultFunctionArrayLvalueConversion(Cond.get())
6035                              : CheckCXXBooleanCondition(Cond.get());
6036     if (CondRes.isInvalid())
6037       return QualType();
6038     Cond = CondRes;
6039   } else {
6040     // To implement C++, the first expression typically doesn't alter the result
6041     // type of the conditional, however the GCC compatible vector extension
6042     // changes the result type to be that of the conditional. Since we cannot
6043     // know if this is a vector extension here, delay the conversion of the
6044     // LHS/RHS below until later.
6045     return Context.DependentTy;
6046   }
6047 
6048 
6049   // Either of the arguments dependent?
6050   if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
6051     return Context.DependentTy;
6052 
6053   // C++11 [expr.cond]p2
6054   //   If either the second or the third operand has type (cv) void, ...
6055   QualType LTy = LHS.get()->getType();
6056   QualType RTy = RHS.get()->getType();
6057   bool LVoid = LTy->isVoidType();
6058   bool RVoid = RTy->isVoidType();
6059   if (LVoid || RVoid) {
6060     //   ... one of the following shall hold:
6061     //   -- The second or the third operand (but not both) is a (possibly
6062     //      parenthesized) throw-expression; the result is of the type
6063     //      and value category of the other.
6064     bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
6065     bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
6066 
6067     // Void expressions aren't legal in the vector-conditional expressions.
6068     if (IsVectorConditional) {
6069       SourceRange DiagLoc =
6070           LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
6071       bool IsThrow = LVoid ? LThrow : RThrow;
6072       Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
6073           << DiagLoc << IsThrow;
6074       return QualType();
6075     }
6076 
6077     if (LThrow != RThrow) {
6078       Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
6079       VK = NonThrow->getValueKind();
6080       // DR (no number yet): the result is a bit-field if the
6081       // non-throw-expression operand is a bit-field.
6082       OK = NonThrow->getObjectKind();
6083       return NonThrow->getType();
6084     }
6085 
6086     //   -- Both the second and third operands have type void; the result is of
6087     //      type void and is a prvalue.
6088     if (LVoid && RVoid)
6089       return Context.VoidTy;
6090 
6091     // Neither holds, error.
6092     Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
6093       << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
6094       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6095     return QualType();
6096   }
6097 
6098   // Neither is void.
6099   if (IsVectorConditional)
6100     return CheckGNUVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6101 
6102   // C++11 [expr.cond]p3
6103   //   Otherwise, if the second and third operand have different types, and
6104   //   either has (cv) class type [...] an attempt is made to convert each of
6105   //   those operands to the type of the other.
6106   if (!Context.hasSameType(LTy, RTy) &&
6107       (LTy->isRecordType() || RTy->isRecordType())) {
6108     // These return true if a single direction is already ambiguous.
6109     QualType L2RType, R2LType;
6110     bool HaveL2R, HaveR2L;
6111     if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
6112       return QualType();
6113     if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
6114       return QualType();
6115 
6116     //   If both can be converted, [...] the program is ill-formed.
6117     if (HaveL2R && HaveR2L) {
6118       Diag(QuestionLoc, diag::err_conditional_ambiguous)
6119         << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6120       return QualType();
6121     }
6122 
6123     //   If exactly one conversion is possible, that conversion is applied to
6124     //   the chosen operand and the converted operands are used in place of the
6125     //   original operands for the remainder of this section.
6126     if (HaveL2R) {
6127       if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
6128         return QualType();
6129       LTy = LHS.get()->getType();
6130     } else if (HaveR2L) {
6131       if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
6132         return QualType();
6133       RTy = RHS.get()->getType();
6134     }
6135   }
6136 
6137   // C++11 [expr.cond]p3
6138   //   if both are glvalues of the same value category and the same type except
6139   //   for cv-qualification, an attempt is made to convert each of those
6140   //   operands to the type of the other.
6141   // FIXME:
6142   //   Resolving a defect in P0012R1: we extend this to cover all cases where
6143   //   one of the operands is reference-compatible with the other, in order
6144   //   to support conditionals between functions differing in noexcept. This
6145   //   will similarly cover difference in array bounds after P0388R4.
6146   // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6147   //   that instead?
6148   ExprValueKind LVK = LHS.get()->getValueKind();
6149   ExprValueKind RVK = RHS.get()->getValueKind();
6150   if (!Context.hasSameType(LTy, RTy) &&
6151       LVK == RVK && LVK != VK_RValue) {
6152     // DerivedToBase was already handled by the class-specific case above.
6153     // FIXME: Should we allow ObjC conversions here?
6154     const ReferenceConversions AllowedConversions =
6155         ReferenceConversions::Qualification |
6156         ReferenceConversions::NestedQualification |
6157         ReferenceConversions::Function;
6158 
6159     ReferenceConversions RefConv;
6160     if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6161             Ref_Compatible &&
6162         !(RefConv & ~AllowedConversions) &&
6163         // [...] subject to the constraint that the reference must bind
6164         // directly [...]
6165         !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6166       RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6167       RTy = RHS.get()->getType();
6168     } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6169                    Ref_Compatible &&
6170                !(RefConv & ~AllowedConversions) &&
6171                !LHS.get()->refersToBitField() &&
6172                !LHS.get()->refersToVectorElement()) {
6173       LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6174       LTy = LHS.get()->getType();
6175     }
6176   }
6177 
6178   // C++11 [expr.cond]p4
6179   //   If the second and third operands are glvalues of the same value
6180   //   category and have the same type, the result is of that type and
6181   //   value category and it is a bit-field if the second or the third
6182   //   operand is a bit-field, or if both are bit-fields.
6183   // We only extend this to bitfields, not to the crazy other kinds of
6184   // l-values.
6185   bool Same = Context.hasSameType(LTy, RTy);
6186   if (Same && LVK == RVK && LVK != VK_RValue &&
6187       LHS.get()->isOrdinaryOrBitFieldObject() &&
6188       RHS.get()->isOrdinaryOrBitFieldObject()) {
6189     VK = LHS.get()->getValueKind();
6190     if (LHS.get()->getObjectKind() == OK_BitField ||
6191         RHS.get()->getObjectKind() == OK_BitField)
6192       OK = OK_BitField;
6193 
6194     // If we have function pointer types, unify them anyway to unify their
6195     // exception specifications, if any.
6196     if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
6197       Qualifiers Qs = LTy.getQualifiers();
6198       LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
6199                                      /*ConvertArgs*/false);
6200       LTy = Context.getQualifiedType(LTy, Qs);
6201 
6202       assert(!LTy.isNull() && "failed to find composite pointer type for "
6203                               "canonically equivalent function ptr types");
6204       assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
6205     }
6206 
6207     return LTy;
6208   }
6209 
6210   // C++11 [expr.cond]p5
6211   //   Otherwise, the result is a prvalue. If the second and third operands
6212   //   do not have the same type, and either has (cv) class type, ...
6213   if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6214     //   ... overload resolution is used to determine the conversions (if any)
6215     //   to be applied to the operands. If the overload resolution fails, the
6216     //   program is ill-formed.
6217     if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
6218       return QualType();
6219   }
6220 
6221   // C++11 [expr.cond]p6
6222   //   Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
6223   //   conversions are performed on the second and third operands.
6224   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6225   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6226   if (LHS.isInvalid() || RHS.isInvalid())
6227     return QualType();
6228   LTy = LHS.get()->getType();
6229   RTy = RHS.get()->getType();
6230 
6231   //   After those conversions, one of the following shall hold:
6232   //   -- The second and third operands have the same type; the result
6233   //      is of that type. If the operands have class type, the result
6234   //      is a prvalue temporary of the result type, which is
6235   //      copy-initialized from either the second operand or the third
6236   //      operand depending on the value of the first operand.
6237   if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
6238     if (LTy->isRecordType()) {
6239       // The operands have class type. Make a temporary copy.
6240       InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
6241 
6242       ExprResult LHSCopy = PerformCopyInitialization(Entity,
6243                                                      SourceLocation(),
6244                                                      LHS);
6245       if (LHSCopy.isInvalid())
6246         return QualType();
6247 
6248       ExprResult RHSCopy = PerformCopyInitialization(Entity,
6249                                                      SourceLocation(),
6250                                                      RHS);
6251       if (RHSCopy.isInvalid())
6252         return QualType();
6253 
6254       LHS = LHSCopy;
6255       RHS = RHSCopy;
6256     }
6257 
6258     // If we have function pointer types, unify them anyway to unify their
6259     // exception specifications, if any.
6260     if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
6261       LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
6262       assert(!LTy.isNull() && "failed to find composite pointer type for "
6263                               "canonically equivalent function ptr types");
6264     }
6265 
6266     return LTy;
6267   }
6268 
6269   // Extension: conditional operator involving vector types.
6270   if (LTy->isVectorType() || RTy->isVectorType())
6271     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6272                                /*AllowBothBool*/true,
6273                                /*AllowBoolConversions*/false);
6274 
6275   //   -- The second and third operands have arithmetic or enumeration type;
6276   //      the usual arithmetic conversions are performed to bring them to a
6277   //      common type, and the result is of that type.
6278   if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
6279     QualType ResTy =
6280         UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6281     if (LHS.isInvalid() || RHS.isInvalid())
6282       return QualType();
6283     if (ResTy.isNull()) {
6284       Diag(QuestionLoc,
6285            diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
6286         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6287       return QualType();
6288     }
6289 
6290     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6291     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6292 
6293     return ResTy;
6294   }
6295 
6296   //   -- The second and third operands have pointer type, or one has pointer
6297   //      type and the other is a null pointer constant, or both are null
6298   //      pointer constants, at least one of which is non-integral; pointer
6299   //      conversions and qualification conversions are performed to bring them
6300   //      to their composite pointer type. The result is of the composite
6301   //      pointer type.
6302   //   -- The second and third operands have pointer to member type, or one has
6303   //      pointer to member type and the other is a null pointer constant;
6304   //      pointer to member conversions and qualification conversions are
6305   //      performed to bring them to a common type, whose cv-qualification
6306   //      shall match the cv-qualification of either the second or the third
6307   //      operand. The result is of the common type.
6308   QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
6309   if (!Composite.isNull())
6310     return Composite;
6311 
6312   // Similarly, attempt to find composite type of two objective-c pointers.
6313   Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6314   if (!Composite.isNull())
6315     return Composite;
6316 
6317   // Check if we are using a null with a non-pointer type.
6318   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6319     return QualType();
6320 
6321   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6322     << LHS.get()->getType() << RHS.get()->getType()
6323     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6324   return QualType();
6325 }
6326 
6327 static FunctionProtoType::ExceptionSpecInfo
6328 mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
6329                     FunctionProtoType::ExceptionSpecInfo ESI2,
6330                     SmallVectorImpl<QualType> &ExceptionTypeStorage) {
6331   ExceptionSpecificationType EST1 = ESI1.Type;
6332   ExceptionSpecificationType EST2 = ESI2.Type;
6333 
6334   // If either of them can throw anything, that is the result.
6335   if (EST1 == EST_None) return ESI1;
6336   if (EST2 == EST_None) return ESI2;
6337   if (EST1 == EST_MSAny) return ESI1;
6338   if (EST2 == EST_MSAny) return ESI2;
6339   if (EST1 == EST_NoexceptFalse) return ESI1;
6340   if (EST2 == EST_NoexceptFalse) return ESI2;
6341 
6342   // If either of them is non-throwing, the result is the other.
6343   if (EST1 == EST_NoThrow) return ESI2;
6344   if (EST2 == EST_NoThrow) return ESI1;
6345   if (EST1 == EST_DynamicNone) return ESI2;
6346   if (EST2 == EST_DynamicNone) return ESI1;
6347   if (EST1 == EST_BasicNoexcept) return ESI2;
6348   if (EST2 == EST_BasicNoexcept) return ESI1;
6349   if (EST1 == EST_NoexceptTrue) return ESI2;
6350   if (EST2 == EST_NoexceptTrue) return ESI1;
6351 
6352   // If we're left with value-dependent computed noexcept expressions, we're
6353   // stuck. Before C++17, we can just drop the exception specification entirely,
6354   // since it's not actually part of the canonical type. And this should never
6355   // happen in C++17, because it would mean we were computing the composite
6356   // pointer type of dependent types, which should never happen.
6357   if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
6358     assert(!S.getLangOpts().CPlusPlus17 &&
6359            "computing composite pointer type of dependent types");
6360     return FunctionProtoType::ExceptionSpecInfo();
6361   }
6362 
6363   // Switch over the possibilities so that people adding new values know to
6364   // update this function.
6365   switch (EST1) {
6366   case EST_None:
6367   case EST_DynamicNone:
6368   case EST_MSAny:
6369   case EST_BasicNoexcept:
6370   case EST_DependentNoexcept:
6371   case EST_NoexceptFalse:
6372   case EST_NoexceptTrue:
6373   case EST_NoThrow:
6374     llvm_unreachable("handled above");
6375 
6376   case EST_Dynamic: {
6377     // This is the fun case: both exception specifications are dynamic. Form
6378     // the union of the two lists.
6379     assert(EST2 == EST_Dynamic && "other cases should already be handled");
6380     llvm::SmallPtrSet<QualType, 8> Found;
6381     for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6382       for (QualType E : Exceptions)
6383         if (Found.insert(S.Context.getCanonicalType(E)).second)
6384           ExceptionTypeStorage.push_back(E);
6385 
6386     FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6387     Result.Exceptions = ExceptionTypeStorage;
6388     return Result;
6389   }
6390 
6391   case EST_Unevaluated:
6392   case EST_Uninstantiated:
6393   case EST_Unparsed:
6394     llvm_unreachable("shouldn't see unresolved exception specifications here");
6395   }
6396 
6397   llvm_unreachable("invalid ExceptionSpecificationType");
6398 }
6399 
6400 /// Find a merged pointer type and convert the two expressions to it.
6401 ///
6402 /// This finds the composite pointer type for \p E1 and \p E2 according to
6403 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
6404 /// it.  It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs
6405 /// is \c true).
6406 ///
6407 /// \param Loc The location of the operator requiring these two expressions to
6408 /// be converted to the composite pointer type.
6409 ///
6410 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
6411 QualType Sema::FindCompositePointerType(SourceLocation Loc,
6412                                         Expr *&E1, Expr *&E2,
6413                                         bool ConvertArgs) {
6414   assert(getLangOpts().CPlusPlus && "This function assumes C++");
6415 
6416   // C++1z [expr]p14:
6417   //   The composite pointer type of two operands p1 and p2 having types T1
6418   //   and T2
6419   QualType T1 = E1->getType(), T2 = E2->getType();
6420 
6421   //   where at least one is a pointer or pointer to member type or
6422   //   std::nullptr_t is:
6423   bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6424                          T1->isNullPtrType();
6425   bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6426                          T2->isNullPtrType();
6427   if (!T1IsPointerLike && !T2IsPointerLike)
6428     return QualType();
6429 
6430   //   - if both p1 and p2 are null pointer constants, std::nullptr_t;
6431   // This can't actually happen, following the standard, but we also use this
6432   // to implement the end of [expr.conv], which hits this case.
6433   //
6434   //   - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6435   if (T1IsPointerLike &&
6436       E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6437     if (ConvertArgs)
6438       E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6439                                          ? CK_NullToMemberPointer
6440                                          : CK_NullToPointer).get();
6441     return T1;
6442   }
6443   if (T2IsPointerLike &&
6444       E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6445     if (ConvertArgs)
6446       E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6447                                          ? CK_NullToMemberPointer
6448                                          : CK_NullToPointer).get();
6449     return T2;
6450   }
6451 
6452   // Now both have to be pointers or member pointers.
6453   if (!T1IsPointerLike || !T2IsPointerLike)
6454     return QualType();
6455   assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6456          "nullptr_t should be a null pointer constant");
6457 
6458   struct Step {
6459     enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
6460     // Qualifiers to apply under the step kind.
6461     Qualifiers Quals;
6462     /// The class for a pointer-to-member; a constant array type with a bound
6463     /// (if any) for an array.
6464     const Type *ClassOrBound;
6465 
6466     Step(Kind K, const Type *ClassOrBound = nullptr)
6467         : K(K), Quals(), ClassOrBound(ClassOrBound) {}
6468     QualType rebuild(ASTContext &Ctx, QualType T) const {
6469       T = Ctx.getQualifiedType(T, Quals);
6470       switch (K) {
6471       case Pointer:
6472         return Ctx.getPointerType(T);
6473       case MemberPointer:
6474         return Ctx.getMemberPointerType(T, ClassOrBound);
6475       case ObjCPointer:
6476         return Ctx.getObjCObjectPointerType(T);
6477       case Array:
6478         if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
6479           return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
6480                                           ArrayType::Normal, 0);
6481         else
6482           return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0);
6483       }
6484       llvm_unreachable("unknown step kind");
6485     }
6486   };
6487 
6488   SmallVector<Step, 8> Steps;
6489 
6490   //  - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6491   //    is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6492   //    the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6493   //    respectively;
6494   //  - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6495   //    to member of C2 of type cv2 U2" for some non-function type U, where
6496   //    C1 is reference-related to C2 or C2 is reference-related to C1, the
6497   //    cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6498   //    respectively;
6499   //  - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6500   //    T2;
6501   //
6502   // Dismantle T1 and T2 to simultaneously determine whether they are similar
6503   // and to prepare to form the cv-combined type if so.
6504   QualType Composite1 = T1;
6505   QualType Composite2 = T2;
6506   unsigned NeedConstBefore = 0;
6507   while (true) {
6508     assert(!Composite1.isNull() && !Composite2.isNull());
6509 
6510     Qualifiers Q1, Q2;
6511     Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
6512     Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
6513 
6514     // Top-level qualifiers are ignored. Merge at all lower levels.
6515     if (!Steps.empty()) {
6516       // Find the qualifier union: (approximately) the unique minimal set of
6517       // qualifiers that is compatible with both types.
6518       Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() |
6519                                                   Q2.getCVRUQualifiers());
6520 
6521       // Under one level of pointer or pointer-to-member, we can change to an
6522       // unambiguous compatible address space.
6523       if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
6524         Quals.setAddressSpace(Q1.getAddressSpace());
6525       } else if (Steps.size() == 1) {
6526         bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
6527         bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
6528         if (MaybeQ1 == MaybeQ2)
6529           return QualType(); // No unique best address space.
6530         Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
6531                                       : Q2.getAddressSpace());
6532       } else {
6533         return QualType();
6534       }
6535 
6536       // FIXME: In C, we merge __strong and none to __strong at the top level.
6537       if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
6538         Quals.setObjCGCAttr(Q1.getObjCGCAttr());
6539       else
6540         return QualType();
6541 
6542       // Mismatched lifetime qualifiers never compatibly include each other.
6543       if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
6544         Quals.setObjCLifetime(Q1.getObjCLifetime());
6545       else
6546         return QualType();
6547 
6548       Steps.back().Quals = Quals;
6549       if (Q1 != Quals || Q2 != Quals)
6550         NeedConstBefore = Steps.size() - 1;
6551     }
6552 
6553     // FIXME: Can we unify the following with UnwrapSimilarTypes?
6554     const PointerType *Ptr1, *Ptr2;
6555     if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6556         (Ptr2 = Composite2->getAs<PointerType>())) {
6557       Composite1 = Ptr1->getPointeeType();
6558       Composite2 = Ptr2->getPointeeType();
6559       Steps.emplace_back(Step::Pointer);
6560       continue;
6561     }
6562 
6563     const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
6564     if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
6565         (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
6566       Composite1 = ObjPtr1->getPointeeType();
6567       Composite2 = ObjPtr2->getPointeeType();
6568       Steps.emplace_back(Step::ObjCPointer);
6569       continue;
6570     }
6571 
6572     const MemberPointerType *MemPtr1, *MemPtr2;
6573     if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6574         (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6575       Composite1 = MemPtr1->getPointeeType();
6576       Composite2 = MemPtr2->getPointeeType();
6577 
6578       // At the top level, we can perform a base-to-derived pointer-to-member
6579       // conversion:
6580       //
6581       //  - [...] where C1 is reference-related to C2 or C2 is
6582       //    reference-related to C1
6583       //
6584       // (Note that the only kinds of reference-relatedness in scope here are
6585       // "same type or derived from".) At any other level, the class must
6586       // exactly match.
6587       const Type *Class = nullptr;
6588       QualType Cls1(MemPtr1->getClass(), 0);
6589       QualType Cls2(MemPtr2->getClass(), 0);
6590       if (Context.hasSameType(Cls1, Cls2))
6591         Class = MemPtr1->getClass();
6592       else if (Steps.empty())
6593         Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
6594                 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
6595       if (!Class)
6596         return QualType();
6597 
6598       Steps.emplace_back(Step::MemberPointer, Class);
6599       continue;
6600     }
6601 
6602     // Special case: at the top level, we can decompose an Objective-C pointer
6603     // and a 'cv void *'. Unify the qualifiers.
6604     if (Steps.empty() && ((Composite1->isVoidPointerType() &&
6605                            Composite2->isObjCObjectPointerType()) ||
6606                           (Composite1->isObjCObjectPointerType() &&
6607                            Composite2->isVoidPointerType()))) {
6608       Composite1 = Composite1->getPointeeType();
6609       Composite2 = Composite2->getPointeeType();
6610       Steps.emplace_back(Step::Pointer);
6611       continue;
6612     }
6613 
6614     // FIXME: arrays
6615 
6616     // FIXME: block pointer types?
6617 
6618     // Cannot unwrap any more types.
6619     break;
6620   }
6621 
6622   //  - if T1 or T2 is "pointer to noexcept function" and the other type is
6623   //    "pointer to function", where the function types are otherwise the same,
6624   //    "pointer to function";
6625   //  - if T1 or T2 is "pointer to member of C1 of type function", the other
6626   //    type is "pointer to member of C2 of type noexcept function", and C1
6627   //    is reference-related to C2 or C2 is reference-related to C1, where
6628   //    the function types are otherwise the same, "pointer to member of C2 of
6629   //    type function" or "pointer to member of C1 of type function",
6630   //    respectively;
6631   //
6632   // We also support 'noreturn' here, so as a Clang extension we generalize the
6633   // above to:
6634   //
6635   //  - [Clang] If T1 and T2 are both of type "pointer to function" or
6636   //    "pointer to member function" and the pointee types can be unified
6637   //    by a function pointer conversion, that conversion is applied
6638   //    before checking the following rules.
6639   //
6640   // We've already unwrapped down to the function types, and we want to merge
6641   // rather than just convert, so do this ourselves rather than calling
6642   // IsFunctionConversion.
6643   //
6644   // FIXME: In order to match the standard wording as closely as possible, we
6645   // currently only do this under a single level of pointers. Ideally, we would
6646   // allow this in general, and set NeedConstBefore to the relevant depth on
6647   // the side(s) where we changed anything. If we permit that, we should also
6648   // consider this conversion when determining type similarity and model it as
6649   // a qualification conversion.
6650   if (Steps.size() == 1) {
6651     if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6652       if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6653         FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6654         FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6655 
6656         // The result is noreturn if both operands are.
6657         bool Noreturn =
6658             EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6659         EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6660         EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6661 
6662         // The result is nothrow if both operands are.
6663         SmallVector<QualType, 8> ExceptionTypeStorage;
6664         EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6665             mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6666                                 ExceptionTypeStorage);
6667 
6668         Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6669                                              FPT1->getParamTypes(), EPI1);
6670         Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6671                                              FPT2->getParamTypes(), EPI2);
6672       }
6673     }
6674   }
6675 
6676   // There are some more conversions we can perform under exactly one pointer.
6677   if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
6678       !Context.hasSameType(Composite1, Composite2)) {
6679     //  - if T1 or T2 is "pointer to cv1 void" and the other type is
6680     //    "pointer to cv2 T", where T is an object type or void,
6681     //    "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
6682     if (Composite1->isVoidType() && Composite2->isObjectType())
6683       Composite2 = Composite1;
6684     else if (Composite2->isVoidType() && Composite1->isObjectType())
6685       Composite1 = Composite2;
6686     //  - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6687     //    is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6688     //    the cv-combined type of T1 and T2 or the cv-combined type of T2 and
6689     //    T1, respectively;
6690     //
6691     // The "similar type" handling covers all of this except for the "T1 is a
6692     // base class of T2" case in the definition of reference-related.
6693     else if (IsDerivedFrom(Loc, Composite1, Composite2))
6694       Composite1 = Composite2;
6695     else if (IsDerivedFrom(Loc, Composite2, Composite1))
6696       Composite2 = Composite1;
6697   }
6698 
6699   // At this point, either the inner types are the same or we have failed to
6700   // find a composite pointer type.
6701   if (!Context.hasSameType(Composite1, Composite2))
6702     return QualType();
6703 
6704   // Per C++ [conv.qual]p3, add 'const' to every level before the last
6705   // differing qualifier.
6706   for (unsigned I = 0; I != NeedConstBefore; ++I)
6707     Steps[I].Quals.addConst();
6708 
6709   // Rebuild the composite type.
6710   QualType Composite = Composite1;
6711   for (auto &S : llvm::reverse(Steps))
6712     Composite = S.rebuild(Context, Composite);
6713 
6714   if (ConvertArgs) {
6715     // Convert the expressions to the composite pointer type.
6716     InitializedEntity Entity =
6717         InitializedEntity::InitializeTemporary(Composite);
6718     InitializationKind Kind =
6719         InitializationKind::CreateCopy(Loc, SourceLocation());
6720 
6721     InitializationSequence E1ToC(*this, Entity, Kind, E1);
6722     if (!E1ToC)
6723       return QualType();
6724 
6725     InitializationSequence E2ToC(*this, Entity, Kind, E2);
6726     if (!E2ToC)
6727       return QualType();
6728 
6729     // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
6730     ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
6731     if (E1Result.isInvalid())
6732       return QualType();
6733     E1 = E1Result.get();
6734 
6735     ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
6736     if (E2Result.isInvalid())
6737       return QualType();
6738     E2 = E2Result.get();
6739   }
6740 
6741   return Composite;
6742 }
6743 
6744 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
6745   if (!E)
6746     return ExprError();
6747 
6748   assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6749 
6750   // If the result is a glvalue, we shouldn't bind it.
6751   if (!E->isRValue())
6752     return E;
6753 
6754   // In ARC, calls that return a retainable type can return retained,
6755   // in which case we have to insert a consuming cast.
6756   if (getLangOpts().ObjCAutoRefCount &&
6757       E->getType()->isObjCRetainableType()) {
6758 
6759     bool ReturnsRetained;
6760 
6761     // For actual calls, we compute this by examining the type of the
6762     // called value.
6763     if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6764       Expr *Callee = Call->getCallee()->IgnoreParens();
6765       QualType T = Callee->getType();
6766 
6767       if (T == Context.BoundMemberTy) {
6768         // Handle pointer-to-members.
6769         if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6770           T = BinOp->getRHS()->getType();
6771         else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6772           T = Mem->getMemberDecl()->getType();
6773       }
6774 
6775       if (const PointerType *Ptr = T->getAs<PointerType>())
6776         T = Ptr->getPointeeType();
6777       else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6778         T = Ptr->getPointeeType();
6779       else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6780         T = MemPtr->getPointeeType();
6781 
6782       auto *FTy = T->castAs<FunctionType>();
6783       ReturnsRetained = FTy->getExtInfo().getProducesResult();
6784 
6785     // ActOnStmtExpr arranges things so that StmtExprs of retainable
6786     // type always produce a +1 object.
6787     } else if (isa<StmtExpr>(E)) {
6788       ReturnsRetained = true;
6789 
6790     // We hit this case with the lambda conversion-to-block optimization;
6791     // we don't want any extra casts here.
6792     } else if (isa<CastExpr>(E) &&
6793                isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
6794       return E;
6795 
6796     // For message sends and property references, we try to find an
6797     // actual method.  FIXME: we should infer retention by selector in
6798     // cases where we don't have an actual method.
6799     } else {
6800       ObjCMethodDecl *D = nullptr;
6801       if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6802         D = Send->getMethodDecl();
6803       } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6804         D = BoxedExpr->getBoxingMethod();
6805       } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
6806         // Don't do reclaims if we're using the zero-element array
6807         // constant.
6808         if (ArrayLit->getNumElements() == 0 &&
6809             Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6810           return E;
6811 
6812         D = ArrayLit->getArrayWithObjectsMethod();
6813       } else if (ObjCDictionaryLiteral *DictLit
6814                                         = dyn_cast<ObjCDictionaryLiteral>(E)) {
6815         // Don't do reclaims if we're using the zero-element dictionary
6816         // constant.
6817         if (DictLit->getNumElements() == 0 &&
6818             Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6819           return E;
6820 
6821         D = DictLit->getDictWithObjectsMethod();
6822       }
6823 
6824       ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6825 
6826       // Don't do reclaims on performSelector calls; despite their
6827       // return type, the invoked method doesn't necessarily actually
6828       // return an object.
6829       if (!ReturnsRetained &&
6830           D && D->getMethodFamily() == OMF_performSelector)
6831         return E;
6832     }
6833 
6834     // Don't reclaim an object of Class type.
6835     if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6836       return E;
6837 
6838     Cleanup.setExprNeedsCleanups(true);
6839 
6840     CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6841                                    : CK_ARCReclaimReturnedObject);
6842     return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6843                                     VK_RValue);
6844   }
6845 
6846   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
6847     Cleanup.setExprNeedsCleanups(true);
6848 
6849   if (!getLangOpts().CPlusPlus)
6850     return E;
6851 
6852   // Search for the base element type (cf. ASTContext::getBaseElementType) with
6853   // a fast path for the common case that the type is directly a RecordType.
6854   const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
6855   const RecordType *RT = nullptr;
6856   while (!RT) {
6857     switch (T->getTypeClass()) {
6858     case Type::Record:
6859       RT = cast<RecordType>(T);
6860       break;
6861     case Type::ConstantArray:
6862     case Type::IncompleteArray:
6863     case Type::VariableArray:
6864     case Type::DependentSizedArray:
6865       T = cast<ArrayType>(T)->getElementType().getTypePtr();
6866       break;
6867     default:
6868       return E;
6869     }
6870   }
6871 
6872   // That should be enough to guarantee that this type is complete, if we're
6873   // not processing a decltype expression.
6874   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6875   if (RD->isInvalidDecl() || RD->isDependentContext())
6876     return E;
6877 
6878   bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6879                     ExpressionEvaluationContextRecord::EK_Decltype;
6880   CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
6881 
6882   if (Destructor) {
6883     MarkFunctionReferenced(E->getExprLoc(), Destructor);
6884     CheckDestructorAccess(E->getExprLoc(), Destructor,
6885                           PDiag(diag::err_access_dtor_temp)
6886                             << E->getType());
6887     if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6888       return ExprError();
6889 
6890     // If destructor is trivial, we can avoid the extra copy.
6891     if (Destructor->isTrivial())
6892       return E;
6893 
6894     // We need a cleanup, but we don't need to remember the temporary.
6895     Cleanup.setExprNeedsCleanups(true);
6896   }
6897 
6898   CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
6899   CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6900 
6901   if (IsDecltype)
6902     ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6903 
6904   return Bind;
6905 }
6906 
6907 ExprResult
6908 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
6909   if (SubExpr.isInvalid())
6910     return ExprError();
6911 
6912   return MaybeCreateExprWithCleanups(SubExpr.get());
6913 }
6914 
6915 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
6916   assert(SubExpr && "subexpression can't be null!");
6917 
6918   CleanupVarDeclMarking();
6919 
6920   unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6921   assert(ExprCleanupObjects.size() >= FirstCleanup);
6922   assert(Cleanup.exprNeedsCleanups() ||
6923          ExprCleanupObjects.size() == FirstCleanup);
6924   if (!Cleanup.exprNeedsCleanups())
6925     return SubExpr;
6926 
6927   auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6928                                      ExprCleanupObjects.size() - FirstCleanup);
6929 
6930   auto *E = ExprWithCleanups::Create(
6931       Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
6932   DiscardCleanupsInEvaluationContext();
6933 
6934   return E;
6935 }
6936 
6937 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
6938   assert(SubStmt && "sub-statement can't be null!");
6939 
6940   CleanupVarDeclMarking();
6941 
6942   if (!Cleanup.exprNeedsCleanups())
6943     return SubStmt;
6944 
6945   // FIXME: In order to attach the temporaries, wrap the statement into
6946   // a StmtExpr; currently this is only used for asm statements.
6947   // This is hacky, either create a new CXXStmtWithTemporaries statement or
6948   // a new AsmStmtWithTemporaries.
6949   CompoundStmt *CompStmt = CompoundStmt::Create(
6950       Context, SubStmt, SourceLocation(), SourceLocation());
6951   Expr *E = new (Context)
6952       StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),
6953                /*FIXME TemplateDepth=*/0);
6954   return MaybeCreateExprWithCleanups(E);
6955 }
6956 
6957 /// Process the expression contained within a decltype. For such expressions,
6958 /// certain semantic checks on temporaries are delayed until this point, and
6959 /// are omitted for the 'topmost' call in the decltype expression. If the
6960 /// topmost call bound a temporary, strip that temporary off the expression.
6961 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
6962   assert(ExprEvalContexts.back().ExprContext ==
6963              ExpressionEvaluationContextRecord::EK_Decltype &&
6964          "not in a decltype expression");
6965 
6966   ExprResult Result = CheckPlaceholderExpr(E);
6967   if (Result.isInvalid())
6968     return ExprError();
6969   E = Result.get();
6970 
6971   // C++11 [expr.call]p11:
6972   //   If a function call is a prvalue of object type,
6973   // -- if the function call is either
6974   //   -- the operand of a decltype-specifier, or
6975   //   -- the right operand of a comma operator that is the operand of a
6976   //      decltype-specifier,
6977   //   a temporary object is not introduced for the prvalue.
6978 
6979   // Recursively rebuild ParenExprs and comma expressions to strip out the
6980   // outermost CXXBindTemporaryExpr, if any.
6981   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6982     ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6983     if (SubExpr.isInvalid())
6984       return ExprError();
6985     if (SubExpr.get() == PE->getSubExpr())
6986       return E;
6987     return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
6988   }
6989   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6990     if (BO->getOpcode() == BO_Comma) {
6991       ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6992       if (RHS.isInvalid())
6993         return ExprError();
6994       if (RHS.get() == BO->getRHS())
6995         return E;
6996       return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
6997                                     BO->getType(), BO->getValueKind(),
6998                                     BO->getObjectKind(), BO->getOperatorLoc(),
6999                                     BO->getFPFeatures(getLangOpts()));
7000     }
7001   }
7002 
7003   CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
7004   CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
7005                               : nullptr;
7006   if (TopCall)
7007     E = TopCall;
7008   else
7009     TopBind = nullptr;
7010 
7011   // Disable the special decltype handling now.
7012   ExprEvalContexts.back().ExprContext =
7013       ExpressionEvaluationContextRecord::EK_Other;
7014 
7015   Result = CheckUnevaluatedOperand(E);
7016   if (Result.isInvalid())
7017     return ExprError();
7018   E = Result.get();
7019 
7020   // In MS mode, don't perform any extra checking of call return types within a
7021   // decltype expression.
7022   if (getLangOpts().MSVCCompat)
7023     return E;
7024 
7025   // Perform the semantic checks we delayed until this point.
7026   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
7027        I != N; ++I) {
7028     CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
7029     if (Call == TopCall)
7030       continue;
7031 
7032     if (CheckCallReturnType(Call->getCallReturnType(Context),
7033                             Call->getBeginLoc(), Call, Call->getDirectCallee()))
7034       return ExprError();
7035   }
7036 
7037   // Now all relevant types are complete, check the destructors are accessible
7038   // and non-deleted, and annotate them on the temporaries.
7039   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7040        I != N; ++I) {
7041     CXXBindTemporaryExpr *Bind =
7042       ExprEvalContexts.back().DelayedDecltypeBinds[I];
7043     if (Bind == TopBind)
7044       continue;
7045 
7046     CXXTemporary *Temp = Bind->getTemporary();
7047 
7048     CXXRecordDecl *RD =
7049       Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7050     CXXDestructorDecl *Destructor = LookupDestructor(RD);
7051     Temp->setDestructor(Destructor);
7052 
7053     MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7054     CheckDestructorAccess(Bind->getExprLoc(), Destructor,
7055                           PDiag(diag::err_access_dtor_temp)
7056                             << Bind->getType());
7057     if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7058       return ExprError();
7059 
7060     // We need a cleanup, but we don't need to remember the temporary.
7061     Cleanup.setExprNeedsCleanups(true);
7062   }
7063 
7064   // Possibly strip off the top CXXBindTemporaryExpr.
7065   return E;
7066 }
7067 
7068 /// Note a set of 'operator->' functions that were used for a member access.
7069 static void noteOperatorArrows(Sema &S,
7070                                ArrayRef<FunctionDecl *> OperatorArrows) {
7071   unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7072   // FIXME: Make this configurable?
7073   unsigned Limit = 9;
7074   if (OperatorArrows.size() > Limit) {
7075     // Produce Limit-1 normal notes and one 'skipping' note.
7076     SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7077     SkipCount = OperatorArrows.size() - (Limit - 1);
7078   }
7079 
7080   for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7081     if (I == SkipStart) {
7082       S.Diag(OperatorArrows[I]->getLocation(),
7083              diag::note_operator_arrows_suppressed)
7084           << SkipCount;
7085       I += SkipCount;
7086     } else {
7087       S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7088           << OperatorArrows[I]->getCallResultType();
7089       ++I;
7090     }
7091   }
7092 }
7093 
7094 ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
7095                                               SourceLocation OpLoc,
7096                                               tok::TokenKind OpKind,
7097                                               ParsedType &ObjectType,
7098                                               bool &MayBePseudoDestructor) {
7099   // Since this might be a postfix expression, get rid of ParenListExprs.
7100   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
7101   if (Result.isInvalid()) return ExprError();
7102   Base = Result.get();
7103 
7104   Result = CheckPlaceholderExpr(Base);
7105   if (Result.isInvalid()) return ExprError();
7106   Base = Result.get();
7107 
7108   QualType BaseType = Base->getType();
7109   MayBePseudoDestructor = false;
7110   if (BaseType->isDependentType()) {
7111     // If we have a pointer to a dependent type and are using the -> operator,
7112     // the object type is the type that the pointer points to. We might still
7113     // have enough information about that type to do something useful.
7114     if (OpKind == tok::arrow)
7115       if (const PointerType *Ptr = BaseType->getAs<PointerType>())
7116         BaseType = Ptr->getPointeeType();
7117 
7118     ObjectType = ParsedType::make(BaseType);
7119     MayBePseudoDestructor = true;
7120     return Base;
7121   }
7122 
7123   // C++ [over.match.oper]p8:
7124   //   [...] When operator->returns, the operator-> is applied  to the value
7125   //   returned, with the original second operand.
7126   if (OpKind == tok::arrow) {
7127     QualType StartingType = BaseType;
7128     bool NoArrowOperatorFound = false;
7129     bool FirstIteration = true;
7130     FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
7131     // The set of types we've considered so far.
7132     llvm::SmallPtrSet<CanQualType,8> CTypes;
7133     SmallVector<FunctionDecl*, 8> OperatorArrows;
7134     CTypes.insert(Context.getCanonicalType(BaseType));
7135 
7136     while (BaseType->isRecordType()) {
7137       if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
7138         Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
7139           << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
7140         noteOperatorArrows(*this, OperatorArrows);
7141         Diag(OpLoc, diag::note_operator_arrow_depth)
7142           << getLangOpts().ArrowDepth;
7143         return ExprError();
7144       }
7145 
7146       Result = BuildOverloadedArrowExpr(
7147           S, Base, OpLoc,
7148           // When in a template specialization and on the first loop iteration,
7149           // potentially give the default diagnostic (with the fixit in a
7150           // separate note) instead of having the error reported back to here
7151           // and giving a diagnostic with a fixit attached to the error itself.
7152           (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7153               ? nullptr
7154               : &NoArrowOperatorFound);
7155       if (Result.isInvalid()) {
7156         if (NoArrowOperatorFound) {
7157           if (FirstIteration) {
7158             Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7159               << BaseType << 1 << Base->getSourceRange()
7160               << FixItHint::CreateReplacement(OpLoc, ".");
7161             OpKind = tok::period;
7162             break;
7163           }
7164           Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7165             << BaseType << Base->getSourceRange();
7166           CallExpr *CE = dyn_cast<CallExpr>(Base);
7167           if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7168             Diag(CD->getBeginLoc(),
7169                  diag::note_member_reference_arrow_from_operator_arrow);
7170           }
7171         }
7172         return ExprError();
7173       }
7174       Base = Result.get();
7175       if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7176         OperatorArrows.push_back(OpCall->getDirectCallee());
7177       BaseType = Base->getType();
7178       CanQualType CBaseType = Context.getCanonicalType(BaseType);
7179       if (!CTypes.insert(CBaseType).second) {
7180         Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7181         noteOperatorArrows(*this, OperatorArrows);
7182         return ExprError();
7183       }
7184       FirstIteration = false;
7185     }
7186 
7187     if (OpKind == tok::arrow) {
7188       if (BaseType->isPointerType())
7189         BaseType = BaseType->getPointeeType();
7190       else if (auto *AT = Context.getAsArrayType(BaseType))
7191         BaseType = AT->getElementType();
7192     }
7193   }
7194 
7195   // Objective-C properties allow "." access on Objective-C pointer types,
7196   // so adjust the base type to the object type itself.
7197   if (BaseType->isObjCObjectPointerType())
7198     BaseType = BaseType->getPointeeType();
7199 
7200   // C++ [basic.lookup.classref]p2:
7201   //   [...] If the type of the object expression is of pointer to scalar
7202   //   type, the unqualified-id is looked up in the context of the complete
7203   //   postfix-expression.
7204   //
7205   // This also indicates that we could be parsing a pseudo-destructor-name.
7206   // Note that Objective-C class and object types can be pseudo-destructor
7207   // expressions or normal member (ivar or property) access expressions, and
7208   // it's legal for the type to be incomplete if this is a pseudo-destructor
7209   // call.  We'll do more incomplete-type checks later in the lookup process,
7210   // so just skip this check for ObjC types.
7211   if (!BaseType->isRecordType()) {
7212     ObjectType = ParsedType::make(BaseType);
7213     MayBePseudoDestructor = true;
7214     return Base;
7215   }
7216 
7217   // The object type must be complete (or dependent), or
7218   // C++11 [expr.prim.general]p3:
7219   //   Unlike the object expression in other contexts, *this is not required to
7220   //   be of complete type for purposes of class member access (5.2.5) outside
7221   //   the member function body.
7222   if (!BaseType->isDependentType() &&
7223       !isThisOutsideMemberFunctionBody(BaseType) &&
7224       RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
7225     return ExprError();
7226 
7227   // C++ [basic.lookup.classref]p2:
7228   //   If the id-expression in a class member access (5.2.5) is an
7229   //   unqualified-id, and the type of the object expression is of a class
7230   //   type C (or of pointer to a class type C), the unqualified-id is looked
7231   //   up in the scope of class C. [...]
7232   ObjectType = ParsedType::make(BaseType);
7233   return Base;
7234 }
7235 
7236 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
7237                    tok::TokenKind& OpKind, SourceLocation OpLoc) {
7238   if (Base->hasPlaceholderType()) {
7239     ExprResult result = S.CheckPlaceholderExpr(Base);
7240     if (result.isInvalid()) return true;
7241     Base = result.get();
7242   }
7243   ObjectType = Base->getType();
7244 
7245   // C++ [expr.pseudo]p2:
7246   //   The left-hand side of the dot operator shall be of scalar type. The
7247   //   left-hand side of the arrow operator shall be of pointer to scalar type.
7248   //   This scalar type is the object type.
7249   // Note that this is rather different from the normal handling for the
7250   // arrow operator.
7251   if (OpKind == tok::arrow) {
7252     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7253       ObjectType = Ptr->getPointeeType();
7254     } else if (!Base->isTypeDependent()) {
7255       // The user wrote "p->" when they probably meant "p."; fix it.
7256       S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7257         << ObjectType << true
7258         << FixItHint::CreateReplacement(OpLoc, ".");
7259       if (S.isSFINAEContext())
7260         return true;
7261 
7262       OpKind = tok::period;
7263     }
7264   }
7265 
7266   return false;
7267 }
7268 
7269 /// Check if it's ok to try and recover dot pseudo destructor calls on
7270 /// pointer objects.
7271 static bool
7272 canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
7273                                                    QualType DestructedType) {
7274   // If this is a record type, check if its destructor is callable.
7275   if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
7276     if (RD->hasDefinition())
7277       if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
7278         return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
7279     return false;
7280   }
7281 
7282   // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7283   return DestructedType->isDependentType() || DestructedType->isScalarType() ||
7284          DestructedType->isVectorType();
7285 }
7286 
7287 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
7288                                            SourceLocation OpLoc,
7289                                            tok::TokenKind OpKind,
7290                                            const CXXScopeSpec &SS,
7291                                            TypeSourceInfo *ScopeTypeInfo,
7292                                            SourceLocation CCLoc,
7293                                            SourceLocation TildeLoc,
7294                                          PseudoDestructorTypeStorage Destructed) {
7295   TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
7296 
7297   QualType ObjectType;
7298   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7299     return ExprError();
7300 
7301   if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
7302       !ObjectType->isVectorType()) {
7303     if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
7304       Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
7305     else {
7306       Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
7307         << ObjectType << Base->getSourceRange();
7308       return ExprError();
7309     }
7310   }
7311 
7312   // C++ [expr.pseudo]p2:
7313   //   [...] The cv-unqualified versions of the object type and of the type
7314   //   designated by the pseudo-destructor-name shall be the same type.
7315   if (DestructedTypeInfo) {
7316     QualType DestructedType = DestructedTypeInfo->getType();
7317     SourceLocation DestructedTypeStart
7318       = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
7319     if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
7320       if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
7321         // Detect dot pseudo destructor calls on pointer objects, e.g.:
7322         //   Foo *foo;
7323         //   foo.~Foo();
7324         if (OpKind == tok::period && ObjectType->isPointerType() &&
7325             Context.hasSameUnqualifiedType(DestructedType,
7326                                            ObjectType->getPointeeType())) {
7327           auto Diagnostic =
7328               Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7329               << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
7330 
7331           // Issue a fixit only when the destructor is valid.
7332           if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
7333                   *this, DestructedType))
7334             Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
7335 
7336           // Recover by setting the object type to the destructed type and the
7337           // operator to '->'.
7338           ObjectType = DestructedType;
7339           OpKind = tok::arrow;
7340         } else {
7341           Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
7342               << ObjectType << DestructedType << Base->getSourceRange()
7343               << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
7344 
7345           // Recover by setting the destructed type to the object type.
7346           DestructedType = ObjectType;
7347           DestructedTypeInfo =
7348               Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
7349           Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7350         }
7351       } else if (DestructedType.getObjCLifetime() !=
7352                                                 ObjectType.getObjCLifetime()) {
7353 
7354         if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
7355           // Okay: just pretend that the user provided the correctly-qualified
7356           // type.
7357         } else {
7358           Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
7359             << ObjectType << DestructedType << Base->getSourceRange()
7360             << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
7361         }
7362 
7363         // Recover by setting the destructed type to the object type.
7364         DestructedType = ObjectType;
7365         DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
7366                                                            DestructedTypeStart);
7367         Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7368       }
7369     }
7370   }
7371 
7372   // C++ [expr.pseudo]p2:
7373   //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7374   //   form
7375   //
7376   //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
7377   //
7378   //   shall designate the same scalar type.
7379   if (ScopeTypeInfo) {
7380     QualType ScopeType = ScopeTypeInfo->getType();
7381     if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
7382         !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
7383 
7384       Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
7385            diag::err_pseudo_dtor_type_mismatch)
7386         << ObjectType << ScopeType << Base->getSourceRange()
7387         << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
7388 
7389       ScopeType = QualType();
7390       ScopeTypeInfo = nullptr;
7391     }
7392   }
7393 
7394   Expr *Result
7395     = new (Context) CXXPseudoDestructorExpr(Context, Base,
7396                                             OpKind == tok::arrow, OpLoc,
7397                                             SS.getWithLocInContext(Context),
7398                                             ScopeTypeInfo,
7399                                             CCLoc,
7400                                             TildeLoc,
7401                                             Destructed);
7402 
7403   return Result;
7404 }
7405 
7406 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7407                                            SourceLocation OpLoc,
7408                                            tok::TokenKind OpKind,
7409                                            CXXScopeSpec &SS,
7410                                            UnqualifiedId &FirstTypeName,
7411                                            SourceLocation CCLoc,
7412                                            SourceLocation TildeLoc,
7413                                            UnqualifiedId &SecondTypeName) {
7414   assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7415           FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7416          "Invalid first type name in pseudo-destructor");
7417   assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7418           SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7419          "Invalid second type name in pseudo-destructor");
7420 
7421   QualType ObjectType;
7422   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7423     return ExprError();
7424 
7425   // Compute the object type that we should use for name lookup purposes. Only
7426   // record types and dependent types matter.
7427   ParsedType ObjectTypePtrForLookup;
7428   if (!SS.isSet()) {
7429     if (ObjectType->isRecordType())
7430       ObjectTypePtrForLookup = ParsedType::make(ObjectType);
7431     else if (ObjectType->isDependentType())
7432       ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
7433   }
7434 
7435   // Convert the name of the type being destructed (following the ~) into a
7436   // type (with source-location information).
7437   QualType DestructedType;
7438   TypeSourceInfo *DestructedTypeInfo = nullptr;
7439   PseudoDestructorTypeStorage Destructed;
7440   if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7441     ParsedType T = getTypeName(*SecondTypeName.Identifier,
7442                                SecondTypeName.StartLocation,
7443                                S, &SS, true, false, ObjectTypePtrForLookup,
7444                                /*IsCtorOrDtorName*/true);
7445     if (!T &&
7446         ((SS.isSet() && !computeDeclContext(SS, false)) ||
7447          (!SS.isSet() && ObjectType->isDependentType()))) {
7448       // The name of the type being destroyed is a dependent name, and we
7449       // couldn't find anything useful in scope. Just store the identifier and
7450       // it's location, and we'll perform (qualified) name lookup again at
7451       // template instantiation time.
7452       Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7453                                                SecondTypeName.StartLocation);
7454     } else if (!T) {
7455       Diag(SecondTypeName.StartLocation,
7456            diag::err_pseudo_dtor_destructor_non_type)
7457         << SecondTypeName.Identifier << ObjectType;
7458       if (isSFINAEContext())
7459         return ExprError();
7460 
7461       // Recover by assuming we had the right type all along.
7462       DestructedType = ObjectType;
7463     } else
7464       DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
7465   } else {
7466     // Resolve the template-id to a type.
7467     TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
7468     ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7469                                        TemplateId->NumArgs);
7470     TypeResult T = ActOnTemplateIdType(S,
7471                                        SS,
7472                                        TemplateId->TemplateKWLoc,
7473                                        TemplateId->Template,
7474                                        TemplateId->Name,
7475                                        TemplateId->TemplateNameLoc,
7476                                        TemplateId->LAngleLoc,
7477                                        TemplateArgsPtr,
7478                                        TemplateId->RAngleLoc,
7479                                        /*IsCtorOrDtorName*/true);
7480     if (T.isInvalid() || !T.get()) {
7481       // Recover by assuming we had the right type all along.
7482       DestructedType = ObjectType;
7483     } else
7484       DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
7485   }
7486 
7487   // If we've performed some kind of recovery, (re-)build the type source
7488   // information.
7489   if (!DestructedType.isNull()) {
7490     if (!DestructedTypeInfo)
7491       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
7492                                                   SecondTypeName.StartLocation);
7493     Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7494   }
7495 
7496   // Convert the name of the scope type (the type prior to '::') into a type.
7497   TypeSourceInfo *ScopeTypeInfo = nullptr;
7498   QualType ScopeType;
7499   if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7500       FirstTypeName.Identifier) {
7501     if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7502       ParsedType T = getTypeName(*FirstTypeName.Identifier,
7503                                  FirstTypeName.StartLocation,
7504                                  S, &SS, true, false, ObjectTypePtrForLookup,
7505                                  /*IsCtorOrDtorName*/true);
7506       if (!T) {
7507         Diag(FirstTypeName.StartLocation,
7508              diag::err_pseudo_dtor_destructor_non_type)
7509           << FirstTypeName.Identifier << ObjectType;
7510 
7511         if (isSFINAEContext())
7512           return ExprError();
7513 
7514         // Just drop this type. It's unnecessary anyway.
7515         ScopeType = QualType();
7516       } else
7517         ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
7518     } else {
7519       // Resolve the template-id to a type.
7520       TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
7521       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7522                                          TemplateId->NumArgs);
7523       TypeResult T = ActOnTemplateIdType(S,
7524                                          SS,
7525                                          TemplateId->TemplateKWLoc,
7526                                          TemplateId->Template,
7527                                          TemplateId->Name,
7528                                          TemplateId->TemplateNameLoc,
7529                                          TemplateId->LAngleLoc,
7530                                          TemplateArgsPtr,
7531                                          TemplateId->RAngleLoc,
7532                                          /*IsCtorOrDtorName*/true);
7533       if (T.isInvalid() || !T.get()) {
7534         // Recover by dropping this type.
7535         ScopeType = QualType();
7536       } else
7537         ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
7538     }
7539   }
7540 
7541   if (!ScopeType.isNull() && !ScopeTypeInfo)
7542     ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7543                                                   FirstTypeName.StartLocation);
7544 
7545 
7546   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
7547                                    ScopeTypeInfo, CCLoc, TildeLoc,
7548                                    Destructed);
7549 }
7550 
7551 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7552                                            SourceLocation OpLoc,
7553                                            tok::TokenKind OpKind,
7554                                            SourceLocation TildeLoc,
7555                                            const DeclSpec& DS) {
7556   QualType ObjectType;
7557   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7558     return ExprError();
7559 
7560   QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7561                                  false);
7562 
7563   TypeLocBuilder TLB;
7564   DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7565   DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7566   TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7567   PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7568 
7569   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
7570                                    nullptr, SourceLocation(), TildeLoc,
7571                                    Destructed);
7572 }
7573 
7574 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
7575                                         CXXConversionDecl *Method,
7576                                         bool HadMultipleCandidates) {
7577   // Convert the expression to match the conversion function's implicit object
7578   // parameter.
7579   ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7580                                           FoundDecl, Method);
7581   if (Exp.isInvalid())
7582     return true;
7583 
7584   if (Method->getParent()->isLambda() &&
7585       Method->getConversionType()->isBlockPointerType()) {
7586     // This is a lambda conversion to block pointer; check if the argument
7587     // was a LambdaExpr.
7588     Expr *SubE = E;
7589     CastExpr *CE = dyn_cast<CastExpr>(SubE);
7590     if (CE && CE->getCastKind() == CK_NoOp)
7591       SubE = CE->getSubExpr();
7592     SubE = SubE->IgnoreParens();
7593     if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7594       SubE = BE->getSubExpr();
7595     if (isa<LambdaExpr>(SubE)) {
7596       // For the conversion to block pointer on a lambda expression, we
7597       // construct a special BlockLiteral instead; this doesn't really make
7598       // a difference in ARC, but outside of ARC the resulting block literal
7599       // follows the normal lifetime rules for block literals instead of being
7600       // autoreleased.
7601       PushExpressionEvaluationContext(
7602           ExpressionEvaluationContext::PotentiallyEvaluated);
7603       ExprResult BlockExp = BuildBlockForLambdaConversion(
7604           Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
7605       PopExpressionEvaluationContext();
7606 
7607       // FIXME: This note should be produced by a CodeSynthesisContext.
7608       if (BlockExp.isInvalid())
7609         Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7610       return BlockExp;
7611     }
7612   }
7613 
7614   MemberExpr *ME =
7615       BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
7616                       NestedNameSpecifierLoc(), SourceLocation(), Method,
7617                       DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
7618                       HadMultipleCandidates, DeclarationNameInfo(),
7619                       Context.BoundMemberTy, VK_RValue, OK_Ordinary);
7620 
7621   QualType ResultType = Method->getReturnType();
7622   ExprValueKind VK = Expr::getValueKindForType(ResultType);
7623   ResultType = ResultType.getNonLValueExprType(Context);
7624 
7625   CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
7626       Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc(),
7627       CurFPFeatureOverrides());
7628 
7629   if (CheckFunctionCall(Method, CE,
7630                         Method->getType()->castAs<FunctionProtoType>()))
7631     return ExprError();
7632 
7633   return CE;
7634 }
7635 
7636 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7637                                       SourceLocation RParen) {
7638   // If the operand is an unresolved lookup expression, the expression is ill-
7639   // formed per [over.over]p1, because overloaded function names cannot be used
7640   // without arguments except in explicit contexts.
7641   ExprResult R = CheckPlaceholderExpr(Operand);
7642   if (R.isInvalid())
7643     return R;
7644 
7645   R = CheckUnevaluatedOperand(R.get());
7646   if (R.isInvalid())
7647     return ExprError();
7648 
7649   Operand = R.get();
7650 
7651   if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
7652     // The expression operand for noexcept is in an unevaluated expression
7653     // context, so side effects could result in unintended consequences.
7654     Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7655   }
7656 
7657   CanThrowResult CanThrow = canThrow(Operand);
7658   return new (Context)
7659       CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
7660 }
7661 
7662 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7663                                    Expr *Operand, SourceLocation RParen) {
7664   return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
7665 }
7666 
7667 /// Perform the conversions required for an expression used in a
7668 /// context that ignores the result.
7669 ExprResult Sema::IgnoredValueConversions(Expr *E) {
7670   if (E->hasPlaceholderType()) {
7671     ExprResult result = CheckPlaceholderExpr(E);
7672     if (result.isInvalid()) return E;
7673     E = result.get();
7674   }
7675 
7676   // C99 6.3.2.1:
7677   //   [Except in specific positions,] an lvalue that does not have
7678   //   array type is converted to the value stored in the
7679   //   designated object (and is no longer an lvalue).
7680   if (E->isRValue()) {
7681     // In C, function designators (i.e. expressions of function type)
7682     // are r-values, but we still want to do function-to-pointer decay
7683     // on them.  This is both technically correct and convenient for
7684     // some clients.
7685     if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
7686       return DefaultFunctionArrayConversion(E);
7687 
7688     return E;
7689   }
7690 
7691   if (getLangOpts().CPlusPlus) {
7692     // The C++11 standard defines the notion of a discarded-value expression;
7693     // normally, we don't need to do anything to handle it, but if it is a
7694     // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7695     // conversion.
7696     if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) {
7697       ExprResult Res = DefaultLvalueConversion(E);
7698       if (Res.isInvalid())
7699         return E;
7700       E = Res.get();
7701     } else {
7702       // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7703       // it occurs as a discarded-value expression.
7704       CheckUnusedVolatileAssignment(E);
7705     }
7706 
7707     // C++1z:
7708     //   If the expression is a prvalue after this optional conversion, the
7709     //   temporary materialization conversion is applied.
7710     //
7711     // We skip this step: IR generation is able to synthesize the storage for
7712     // itself in the aggregate case, and adding the extra node to the AST is
7713     // just clutter.
7714     // FIXME: We don't emit lifetime markers for the temporaries due to this.
7715     // FIXME: Do any other AST consumers care about this?
7716     return E;
7717   }
7718 
7719   // GCC seems to also exclude expressions of incomplete enum type.
7720   if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7721     if (!T->getDecl()->isComplete()) {
7722       // FIXME: stupid workaround for a codegen bug!
7723       E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
7724       return E;
7725     }
7726   }
7727 
7728   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7729   if (Res.isInvalid())
7730     return E;
7731   E = Res.get();
7732 
7733   if (!E->getType()->isVoidType())
7734     RequireCompleteType(E->getExprLoc(), E->getType(),
7735                         diag::err_incomplete_type);
7736   return E;
7737 }
7738 
7739 ExprResult Sema::CheckUnevaluatedOperand(Expr *E) {
7740   // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7741   // it occurs as an unevaluated operand.
7742   CheckUnusedVolatileAssignment(E);
7743 
7744   return E;
7745 }
7746 
7747 // If we can unambiguously determine whether Var can never be used
7748 // in a constant expression, return true.
7749 //  - if the variable and its initializer are non-dependent, then
7750 //    we can unambiguously check if the variable is a constant expression.
7751 //  - if the initializer is not value dependent - we can determine whether
7752 //    it can be used to initialize a constant expression.  If Init can not
7753 //    be used to initialize a constant expression we conclude that Var can
7754 //    never be a constant expression.
7755 //  - FXIME: if the initializer is dependent, we can still do some analysis and
7756 //    identify certain cases unambiguously as non-const by using a Visitor:
7757 //      - such as those that involve odr-use of a ParmVarDecl, involve a new
7758 //        delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7759 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
7760     ASTContext &Context) {
7761   if (isa<ParmVarDecl>(Var)) return true;
7762   const VarDecl *DefVD = nullptr;
7763 
7764   // If there is no initializer - this can not be a constant expression.
7765   if (!Var->getAnyInitializer(DefVD)) return true;
7766   assert(DefVD);
7767   if (DefVD->isWeak()) return false;
7768   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
7769 
7770   Expr *Init = cast<Expr>(Eval->Value);
7771 
7772   if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7773     // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7774     // of value-dependent expressions, and use it here to determine whether the
7775     // initializer is a potential constant expression.
7776     return false;
7777   }
7778 
7779   return !Var->isUsableInConstantExpressions(Context);
7780 }
7781 
7782 /// Check if the current lambda has any potential captures
7783 /// that must be captured by any of its enclosing lambdas that are ready to
7784 /// capture. If there is a lambda that can capture a nested
7785 /// potential-capture, go ahead and do so.  Also, check to see if any
7786 /// variables are uncaptureable or do not involve an odr-use so do not
7787 /// need to be captured.
7788 
7789 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7790     Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7791 
7792   assert(!S.isUnevaluatedContext());
7793   assert(S.CurContext->isDependentContext());
7794 #ifndef NDEBUG
7795   DeclContext *DC = S.CurContext;
7796   while (DC && isa<CapturedDecl>(DC))
7797     DC = DC->getParent();
7798   assert(
7799       CurrentLSI->CallOperator == DC &&
7800       "The current call operator must be synchronized with Sema's CurContext");
7801 #endif // NDEBUG
7802 
7803   const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7804 
7805   // All the potentially captureable variables in the current nested
7806   // lambda (within a generic outer lambda), must be captured by an
7807   // outer lambda that is enclosed within a non-dependent context.
7808   CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) {
7809     // If the variable is clearly identified as non-odr-used and the full
7810     // expression is not instantiation dependent, only then do we not
7811     // need to check enclosing lambda's for speculative captures.
7812     // For e.g.:
7813     // Even though 'x' is not odr-used, it should be captured.
7814     // int test() {
7815     //   const int x = 10;
7816     //   auto L = [=](auto a) {
7817     //     (void) +x + a;
7818     //   };
7819     // }
7820     if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
7821         !IsFullExprInstantiationDependent)
7822       return;
7823 
7824     // If we have a capture-capable lambda for the variable, go ahead and
7825     // capture the variable in that lambda (and all its enclosing lambdas).
7826     if (const Optional<unsigned> Index =
7827             getStackIndexOfNearestEnclosingCaptureCapableLambda(
7828                 S.FunctionScopes, Var, S))
7829       S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(),
7830                                           Index.getValue());
7831     const bool IsVarNeverAConstantExpression =
7832         VariableCanNeverBeAConstantExpression(Var, S.Context);
7833     if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7834       // This full expression is not instantiation dependent or the variable
7835       // can not be used in a constant expression - which means
7836       // this variable must be odr-used here, so diagnose a
7837       // capture violation early, if the variable is un-captureable.
7838       // This is purely for diagnosing errors early.  Otherwise, this
7839       // error would get diagnosed when the lambda becomes capture ready.
7840       QualType CaptureType, DeclRefType;
7841       SourceLocation ExprLoc = VarExpr->getExprLoc();
7842       if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7843                           /*EllipsisLoc*/ SourceLocation(),
7844                           /*BuildAndDiagnose*/false, CaptureType,
7845                           DeclRefType, nullptr)) {
7846         // We will never be able to capture this variable, and we need
7847         // to be able to in any and all instantiations, so diagnose it.
7848         S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7849                           /*EllipsisLoc*/ SourceLocation(),
7850                           /*BuildAndDiagnose*/true, CaptureType,
7851                           DeclRefType, nullptr);
7852       }
7853     }
7854   });
7855 
7856   // Check if 'this' needs to be captured.
7857   if (CurrentLSI->hasPotentialThisCapture()) {
7858     // If we have a capture-capable lambda for 'this', go ahead and capture
7859     // 'this' in that lambda (and all its enclosing lambdas).
7860     if (const Optional<unsigned> Index =
7861             getStackIndexOfNearestEnclosingCaptureCapableLambda(
7862                 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
7863       const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7864       S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7865                             /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7866                             &FunctionScopeIndexOfCapturableLambda);
7867     }
7868   }
7869 
7870   // Reset all the potential captures at the end of each full-expression.
7871   CurrentLSI->clearPotentialCaptures();
7872 }
7873 
7874 static ExprResult attemptRecovery(Sema &SemaRef,
7875                                   const TypoCorrectionConsumer &Consumer,
7876                                   const TypoCorrection &TC) {
7877   LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7878                  Consumer.getLookupResult().getLookupKind());
7879   const CXXScopeSpec *SS = Consumer.getSS();
7880   CXXScopeSpec NewSS;
7881 
7882   // Use an approprate CXXScopeSpec for building the expr.
7883   if (auto *NNS = TC.getCorrectionSpecifier())
7884     NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7885   else if (SS && !TC.WillReplaceSpecifier())
7886     NewSS = *SS;
7887 
7888   if (auto *ND = TC.getFoundDecl()) {
7889     R.setLookupName(ND->getDeclName());
7890     R.addDecl(ND);
7891     if (ND->isCXXClassMember()) {
7892       // Figure out the correct naming class to add to the LookupResult.
7893       CXXRecordDecl *Record = nullptr;
7894       if (auto *NNS = TC.getCorrectionSpecifier())
7895         Record = NNS->getAsType()->getAsCXXRecordDecl();
7896       if (!Record)
7897         Record =
7898             dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7899       if (Record)
7900         R.setNamingClass(Record);
7901 
7902       // Detect and handle the case where the decl might be an implicit
7903       // member.
7904       bool MightBeImplicitMember;
7905       if (!Consumer.isAddressOfOperand())
7906         MightBeImplicitMember = true;
7907       else if (!NewSS.isEmpty())
7908         MightBeImplicitMember = false;
7909       else if (R.isOverloadedResult())
7910         MightBeImplicitMember = false;
7911       else if (R.isUnresolvableResult())
7912         MightBeImplicitMember = true;
7913       else
7914         MightBeImplicitMember = isa<FieldDecl>(ND) ||
7915                                 isa<IndirectFieldDecl>(ND) ||
7916                                 isa<MSPropertyDecl>(ND);
7917 
7918       if (MightBeImplicitMember)
7919         return SemaRef.BuildPossibleImplicitMemberExpr(
7920             NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
7921             /*TemplateArgs*/ nullptr, /*S*/ nullptr);
7922     } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7923       return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7924                                         Ivar->getIdentifier());
7925     }
7926   }
7927 
7928   return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7929                                           /*AcceptInvalidDecl*/ true);
7930 }
7931 
7932 namespace {
7933 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7934   llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7935 
7936 public:
7937   explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7938       : TypoExprs(TypoExprs) {}
7939   bool VisitTypoExpr(TypoExpr *TE) {
7940     TypoExprs.insert(TE);
7941     return true;
7942   }
7943 };
7944 
7945 class TransformTypos : public TreeTransform<TransformTypos> {
7946   typedef TreeTransform<TransformTypos> BaseTransform;
7947 
7948   VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7949                      // process of being initialized.
7950   llvm::function_ref<ExprResult(Expr *)> ExprFilter;
7951   llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
7952   llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
7953   llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
7954 
7955   /// Emit diagnostics for all of the TypoExprs encountered.
7956   ///
7957   /// If the TypoExprs were successfully corrected, then the diagnostics should
7958   /// suggest the corrections. Otherwise the diagnostics will not suggest
7959   /// anything (having been passed an empty TypoCorrection).
7960   ///
7961   /// If we've failed to correct due to ambiguous corrections, we need to
7962   /// be sure to pass empty corrections and replacements. Otherwise it's
7963   /// possible that the Consumer has a TypoCorrection that failed to ambiguity
7964   /// and we don't want to report those diagnostics.
7965   void EmitAllDiagnostics(bool IsAmbiguous) {
7966     for (TypoExpr *TE : TypoExprs) {
7967       auto &State = SemaRef.getTypoExprState(TE);
7968       if (State.DiagHandler) {
7969         TypoCorrection TC = IsAmbiguous
7970             ? TypoCorrection() : State.Consumer->getCurrentCorrection();
7971         ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
7972 
7973         // Extract the NamedDecl from the transformed TypoExpr and add it to the
7974         // TypoCorrection, replacing the existing decls. This ensures the right
7975         // NamedDecl is used in diagnostics e.g. in the case where overload
7976         // resolution was used to select one from several possible decls that
7977         // had been stored in the TypoCorrection.
7978         if (auto *ND = getDeclFromExpr(
7979                 Replacement.isInvalid() ? nullptr : Replacement.get()))
7980           TC.setCorrectionDecl(ND);
7981 
7982         State.DiagHandler(TC);
7983       }
7984       SemaRef.clearDelayedTypo(TE);
7985     }
7986   }
7987 
7988   /// Try to advance the typo correction state of the first unfinished TypoExpr.
7989   /// We allow advancement of the correction stream by removing it from the
7990   /// TransformCache which allows `TransformTypoExpr` to advance during the
7991   /// next transformation attempt.
7992   ///
7993   /// Any substitution attempts for the previous TypoExprs (which must have been
7994   /// finished) will need to be retried since it's possible that they will now
7995   /// be invalid given the latest advancement.
7996   ///
7997   /// We need to be sure that we're making progress - it's possible that the
7998   /// tree is so malformed that the transform never makes it to the
7999   /// `TransformTypoExpr`.
8000   ///
8001   /// Returns true if there are any untried correction combinations.
8002   bool CheckAndAdvanceTypoExprCorrectionStreams() {
8003     for (auto TE : TypoExprs) {
8004       auto &State = SemaRef.getTypoExprState(TE);
8005       TransformCache.erase(TE);
8006       if (!State.Consumer->hasMadeAnyCorrectionProgress())
8007         return false;
8008       if (!State.Consumer->finished())
8009         return true;
8010       State.Consumer->resetCorrectionStream();
8011     }
8012     return false;
8013   }
8014 
8015   NamedDecl *getDeclFromExpr(Expr *E) {
8016     if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8017       E = OverloadResolution[OE];
8018 
8019     if (!E)
8020       return nullptr;
8021     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
8022       return DRE->getFoundDecl();
8023     if (auto *ME = dyn_cast<MemberExpr>(E))
8024       return ME->getFoundDecl();
8025     // FIXME: Add any other expr types that could be be seen by the delayed typo
8026     // correction TreeTransform for which the corresponding TypoCorrection could
8027     // contain multiple decls.
8028     return nullptr;
8029   }
8030 
8031   ExprResult TryTransform(Expr *E) {
8032     Sema::SFINAETrap Trap(SemaRef);
8033     ExprResult Res = TransformExpr(E);
8034     if (Trap.hasErrorOccurred() || Res.isInvalid())
8035       return ExprError();
8036 
8037     return ExprFilter(Res.get());
8038   }
8039 
8040   // Since correcting typos may intoduce new TypoExprs, this function
8041   // checks for new TypoExprs and recurses if it finds any. Note that it will
8042   // only succeed if it is able to correct all typos in the given expression.
8043   ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8044     if (Res.isInvalid()) {
8045       return Res;
8046     }
8047     // Check to see if any new TypoExprs were created. If so, we need to recurse
8048     // to check their validity.
8049     Expr *FixedExpr = Res.get();
8050 
8051     auto SavedTypoExprs = std::move(TypoExprs);
8052     auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8053     TypoExprs.clear();
8054     AmbiguousTypoExprs.clear();
8055 
8056     FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8057     if (!TypoExprs.empty()) {
8058       // Recurse to handle newly created TypoExprs. If we're not able to
8059       // handle them, discard these TypoExprs.
8060       ExprResult RecurResult =
8061           RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8062       if (RecurResult.isInvalid()) {
8063         Res = ExprError();
8064         // Recursive corrections didn't work, wipe them away and don't add
8065         // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8066         // since we don't want to clear them twice. Note: it's possible the
8067         // TypoExprs were created recursively and thus won't be in our
8068         // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8069         auto &SemaTypoExprs = SemaRef.TypoExprs;
8070         for (auto TE : TypoExprs) {
8071           TransformCache.erase(TE);
8072           SemaRef.clearDelayedTypo(TE);
8073 
8074           auto SI = find(SemaTypoExprs, TE);
8075           if (SI != SemaTypoExprs.end()) {
8076             SemaTypoExprs.erase(SI);
8077           }
8078         }
8079       } else {
8080         // TypoExpr is valid: add newly created TypoExprs since we were
8081         // able to correct them.
8082         Res = RecurResult;
8083         SavedTypoExprs.set_union(TypoExprs);
8084       }
8085     }
8086 
8087     TypoExprs = std::move(SavedTypoExprs);
8088     AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8089 
8090     return Res;
8091   }
8092 
8093   // Try to transform the given expression, looping through the correction
8094   // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8095   //
8096   // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8097   // true and this method immediately will return an `ExprError`.
8098   ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8099     ExprResult Res;
8100     auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8101     SemaRef.TypoExprs.clear();
8102 
8103     while (true) {
8104       Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8105 
8106       // Recursion encountered an ambiguous correction. This means that our
8107       // correction itself is ambiguous, so stop now.
8108       if (IsAmbiguous)
8109         break;
8110 
8111       // If the transform is still valid after checking for any new typos,
8112       // it's good to go.
8113       if (!Res.isInvalid())
8114         break;
8115 
8116       // The transform was invalid, see if we have any TypoExprs with untried
8117       // correction candidates.
8118       if (!CheckAndAdvanceTypoExprCorrectionStreams())
8119         break;
8120     }
8121 
8122     // If we found a valid result, double check to make sure it's not ambiguous.
8123     if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
8124       auto SavedTransformCache =
8125           llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8126 
8127       // Ensure none of the TypoExprs have multiple typo correction candidates
8128       // with the same edit length that pass all the checks and filters.
8129       while (!AmbiguousTypoExprs.empty()) {
8130         auto TE  = AmbiguousTypoExprs.back();
8131 
8132         // TryTransform itself can create new Typos, adding them to the TypoExpr map
8133         // and invalidating our TypoExprState, so always fetch it instead of storing.
8134         SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8135 
8136         TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8137         TypoCorrection Next;
8138         do {
8139           // Fetch the next correction by erasing the typo from the cache and calling
8140           // `TryTransform` which will iterate through corrections in
8141           // `TransformTypoExpr`.
8142           TransformCache.erase(TE);
8143           ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8144 
8145           if (!AmbigRes.isInvalid() || IsAmbiguous) {
8146             SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8147             SavedTransformCache.erase(TE);
8148             Res = ExprError();
8149             IsAmbiguous = true;
8150             break;
8151           }
8152         } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8153                  Next.getEditDistance(false) == TC.getEditDistance(false));
8154 
8155         if (IsAmbiguous)
8156           break;
8157 
8158         AmbiguousTypoExprs.remove(TE);
8159         SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8160       }
8161       TransformCache = std::move(SavedTransformCache);
8162     }
8163 
8164     // Wipe away any newly created TypoExprs that we don't know about. Since we
8165     // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8166     // possible if a `TypoExpr` is created during a transformation but then
8167     // fails before we can discover it.
8168     auto &SemaTypoExprs = SemaRef.TypoExprs;
8169     for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
8170       auto TE = *Iterator;
8171       auto FI = find(TypoExprs, TE);
8172       if (FI != TypoExprs.end()) {
8173         Iterator++;
8174         continue;
8175       }
8176       SemaRef.clearDelayedTypo(TE);
8177       Iterator = SemaTypoExprs.erase(Iterator);
8178     }
8179     SemaRef.TypoExprs = std::move(SavedTypoExprs);
8180 
8181     return Res;
8182   }
8183 
8184 public:
8185   TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
8186       : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
8187 
8188   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
8189                                    MultiExprArg Args,
8190                                    SourceLocation RParenLoc,
8191                                    Expr *ExecConfig = nullptr) {
8192     auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
8193                                                  RParenLoc, ExecConfig);
8194     if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
8195       if (Result.isUsable()) {
8196         Expr *ResultCall = Result.get();
8197         if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
8198           ResultCall = BE->getSubExpr();
8199         if (auto *CE = dyn_cast<CallExpr>(ResultCall))
8200           OverloadResolution[OE] = CE->getCallee();
8201       }
8202     }
8203     return Result;
8204   }
8205 
8206   ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
8207 
8208   ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
8209 
8210   ExprResult Transform(Expr *E) {
8211     bool IsAmbiguous = false;
8212     ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
8213 
8214     if (!Res.isUsable())
8215       FindTypoExprs(TypoExprs).TraverseStmt(E);
8216 
8217     EmitAllDiagnostics(IsAmbiguous);
8218 
8219     return Res;
8220   }
8221 
8222   ExprResult TransformTypoExpr(TypoExpr *E) {
8223     // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
8224     // cached transformation result if there is one and the TypoExpr isn't the
8225     // first one that was encountered.
8226     auto &CacheEntry = TransformCache[E];
8227     if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
8228       return CacheEntry;
8229     }
8230 
8231     auto &State = SemaRef.getTypoExprState(E);
8232     assert(State.Consumer && "Cannot transform a cleared TypoExpr");
8233 
8234     // For the first TypoExpr and an uncached TypoExpr, find the next likely
8235     // typo correction and return it.
8236     while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
8237       if (InitDecl && TC.getFoundDecl() == InitDecl)
8238         continue;
8239       // FIXME: If we would typo-correct to an invalid declaration, it's
8240       // probably best to just suppress all errors from this typo correction.
8241       ExprResult NE = State.RecoveryHandler ?
8242           State.RecoveryHandler(SemaRef, E, TC) :
8243           attemptRecovery(SemaRef, *State.Consumer, TC);
8244       if (!NE.isInvalid()) {
8245         // Check whether there may be a second viable correction with the same
8246         // edit distance; if so, remember this TypoExpr may have an ambiguous
8247         // correction so it can be more thoroughly vetted later.
8248         TypoCorrection Next;
8249         if ((Next = State.Consumer->peekNextCorrection()) &&
8250             Next.getEditDistance(false) == TC.getEditDistance(false)) {
8251           AmbiguousTypoExprs.insert(E);
8252         } else {
8253           AmbiguousTypoExprs.remove(E);
8254         }
8255         assert(!NE.isUnset() &&
8256                "Typo was transformed into a valid-but-null ExprResult");
8257         return CacheEntry = NE;
8258       }
8259     }
8260     return CacheEntry = ExprError();
8261   }
8262 };
8263 }
8264 
8265 ExprResult
8266 Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
8267                                 bool RecoverUncorrectedTypos,
8268                                 llvm::function_ref<ExprResult(Expr *)> Filter) {
8269   // If the current evaluation context indicates there are uncorrected typos
8270   // and the current expression isn't guaranteed to not have typos, try to
8271   // resolve any TypoExpr nodes that might be in the expression.
8272   if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
8273       (E->isTypeDependent() || E->isValueDependent() ||
8274        E->isInstantiationDependent())) {
8275     auto TyposResolved = DelayedTypos.size();
8276     auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
8277     TyposResolved -= DelayedTypos.size();
8278     if (Result.isInvalid() || Result.get() != E) {
8279       ExprEvalContexts.back().NumTypos -= TyposResolved;
8280       if (Result.isInvalid() && RecoverUncorrectedTypos) {
8281         struct TyposReplace : TreeTransform<TyposReplace> {
8282           TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}
8283           ExprResult TransformTypoExpr(clang::TypoExpr *E) {
8284             return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),
8285                                                     E->getEndLoc(), {});
8286           }
8287         } TT(*this);
8288         return TT.TransformExpr(E);
8289       }
8290       return Result;
8291     }
8292     assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
8293   }
8294   return E;
8295 }
8296 
8297 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
8298                                      bool DiscardedValue,
8299                                      bool IsConstexpr) {
8300   ExprResult FullExpr = FE;
8301 
8302   if (!FullExpr.get())
8303     return ExprError();
8304 
8305   if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
8306     return ExprError();
8307 
8308   if (DiscardedValue) {
8309     // Top-level expressions default to 'id' when we're in a debugger.
8310     if (getLangOpts().DebuggerCastResultToId &&
8311         FullExpr.get()->getType() == Context.UnknownAnyTy) {
8312       FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
8313       if (FullExpr.isInvalid())
8314         return ExprError();
8315     }
8316 
8317     FullExpr = CheckPlaceholderExpr(FullExpr.get());
8318     if (FullExpr.isInvalid())
8319       return ExprError();
8320 
8321     FullExpr = IgnoredValueConversions(FullExpr.get());
8322     if (FullExpr.isInvalid())
8323       return ExprError();
8324 
8325     DiagnoseUnusedExprResult(FullExpr.get());
8326   }
8327 
8328   FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,
8329                                        /*RecoverUncorrectedTypos=*/true);
8330   if (FullExpr.isInvalid())
8331     return ExprError();
8332 
8333   CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
8334 
8335   // At the end of this full expression (which could be a deeply nested
8336   // lambda), if there is a potential capture within the nested lambda,
8337   // have the outer capture-able lambda try and capture it.
8338   // Consider the following code:
8339   // void f(int, int);
8340   // void f(const int&, double);
8341   // void foo() {
8342   //  const int x = 10, y = 20;
8343   //  auto L = [=](auto a) {
8344   //      auto M = [=](auto b) {
8345   //         f(x, b); <-- requires x to be captured by L and M
8346   //         f(y, a); <-- requires y to be captured by L, but not all Ms
8347   //      };
8348   //   };
8349   // }
8350 
8351   // FIXME: Also consider what happens for something like this that involves
8352   // the gnu-extension statement-expressions or even lambda-init-captures:
8353   //   void f() {
8354   //     const int n = 0;
8355   //     auto L =  [&](auto a) {
8356   //       +n + ({ 0; a; });
8357   //     };
8358   //   }
8359   //
8360   // Here, we see +n, and then the full-expression 0; ends, so we don't
8361   // capture n (and instead remove it from our list of potential captures),
8362   // and then the full-expression +n + ({ 0; }); ends, but it's too late
8363   // for us to see that we need to capture n after all.
8364 
8365   LambdaScopeInfo *const CurrentLSI =
8366       getCurLambda(/*IgnoreCapturedRegions=*/true);
8367   // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
8368   // even if CurContext is not a lambda call operator. Refer to that Bug Report
8369   // for an example of the code that might cause this asynchrony.
8370   // By ensuring we are in the context of a lambda's call operator
8371   // we can fix the bug (we only need to check whether we need to capture
8372   // if we are within a lambda's body); but per the comments in that
8373   // PR, a proper fix would entail :
8374   //   "Alternative suggestion:
8375   //   - Add to Sema an integer holding the smallest (outermost) scope
8376   //     index that we are *lexically* within, and save/restore/set to
8377   //     FunctionScopes.size() in InstantiatingTemplate's
8378   //     constructor/destructor.
8379   //  - Teach the handful of places that iterate over FunctionScopes to
8380   //    stop at the outermost enclosing lexical scope."
8381   DeclContext *DC = CurContext;
8382   while (DC && isa<CapturedDecl>(DC))
8383     DC = DC->getParent();
8384   const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
8385   if (IsInLambdaDeclContext && CurrentLSI &&
8386       CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
8387     CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
8388                                                               *this);
8389   return MaybeCreateExprWithCleanups(FullExpr);
8390 }
8391 
8392 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
8393   if (!FullStmt) return StmtError();
8394 
8395   return MaybeCreateStmtWithCleanups(FullStmt);
8396 }
8397 
8398 Sema::IfExistsResult
8399 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
8400                                    CXXScopeSpec &SS,
8401                                    const DeclarationNameInfo &TargetNameInfo) {
8402   DeclarationName TargetName = TargetNameInfo.getName();
8403   if (!TargetName)
8404     return IER_DoesNotExist;
8405 
8406   // If the name itself is dependent, then the result is dependent.
8407   if (TargetName.isDependentName())
8408     return IER_Dependent;
8409 
8410   // Do the redeclaration lookup in the current scope.
8411   LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
8412                  Sema::NotForRedeclaration);
8413   LookupParsedName(R, S, &SS);
8414   R.suppressDiagnostics();
8415 
8416   switch (R.getResultKind()) {
8417   case LookupResult::Found:
8418   case LookupResult::FoundOverloaded:
8419   case LookupResult::FoundUnresolvedValue:
8420   case LookupResult::Ambiguous:
8421     return IER_Exists;
8422 
8423   case LookupResult::NotFound:
8424     return IER_DoesNotExist;
8425 
8426   case LookupResult::NotFoundInCurrentInstantiation:
8427     return IER_Dependent;
8428   }
8429 
8430   llvm_unreachable("Invalid LookupResult Kind!");
8431 }
8432 
8433 Sema::IfExistsResult
8434 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
8435                                    bool IsIfExists, CXXScopeSpec &SS,
8436                                    UnqualifiedId &Name) {
8437   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8438 
8439   // Check for an unexpanded parameter pack.
8440   auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
8441   if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
8442       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
8443     return IER_Error;
8444 
8445   return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
8446 }
8447 
8448 concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) {
8449   return BuildExprRequirement(E, /*IsSimple=*/true,
8450                               /*NoexceptLoc=*/SourceLocation(),
8451                               /*ReturnTypeRequirement=*/{});
8452 }
8453 
8454 concepts::Requirement *
8455 Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS,
8456                            SourceLocation NameLoc, IdentifierInfo *TypeName,
8457                            TemplateIdAnnotation *TemplateId) {
8458   assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
8459          "Exactly one of TypeName and TemplateId must be specified.");
8460   TypeSourceInfo *TSI = nullptr;
8461   if (TypeName) {
8462     QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc,
8463                                    SS.getWithLocInContext(Context), *TypeName,
8464                                    NameLoc, &TSI, /*DeducedTypeContext=*/false);
8465     if (T.isNull())
8466       return nullptr;
8467   } else {
8468     ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
8469                                TemplateId->NumArgs);
8470     TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
8471                                      TemplateId->TemplateKWLoc,
8472                                      TemplateId->Template, TemplateId->Name,
8473                                      TemplateId->TemplateNameLoc,
8474                                      TemplateId->LAngleLoc, ArgsPtr,
8475                                      TemplateId->RAngleLoc);
8476     if (T.isInvalid())
8477       return nullptr;
8478     if (GetTypeFromParser(T.get(), &TSI).isNull())
8479       return nullptr;
8480   }
8481   return BuildTypeRequirement(TSI);
8482 }
8483 
8484 concepts::Requirement *
8485 Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) {
8486   return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
8487                               /*ReturnTypeRequirement=*/{});
8488 }
8489 
8490 concepts::Requirement *
8491 Sema::ActOnCompoundRequirement(
8492     Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8493     TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
8494   // C++2a [expr.prim.req.compound] p1.3.3
8495   //   [..] the expression is deduced against an invented function template
8496   //   F [...] F is a void function template with a single type template
8497   //   parameter T declared with the constrained-parameter. Form a new
8498   //   cv-qualifier-seq cv by taking the union of const and volatile specifiers
8499   //   around the constrained-parameter. F has a single parameter whose
8500   //   type-specifier is cv T followed by the abstract-declarator. [...]
8501   //
8502   // The cv part is done in the calling function - we get the concept with
8503   // arguments and the abstract declarator with the correct CV qualification and
8504   // have to synthesize T and the single parameter of F.
8505   auto &II = Context.Idents.get("expr-type");
8506   auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext,
8507                                               SourceLocation(),
8508                                               SourceLocation(), Depth,
8509                                               /*Index=*/0, &II,
8510                                               /*Typename=*/true,
8511                                               /*ParameterPack=*/false,
8512                                               /*HasTypeConstraint=*/true);
8513 
8514   if (ActOnTypeConstraint(SS, TypeConstraint, TParam,
8515                           /*EllpsisLoc=*/SourceLocation()))
8516     // Just produce a requirement with no type requirements.
8517     return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
8518 
8519   auto *TPL = TemplateParameterList::Create(Context, SourceLocation(),
8520                                             SourceLocation(),
8521                                             ArrayRef<NamedDecl *>(TParam),
8522                                             SourceLocation(),
8523                                             /*RequiresClause=*/nullptr);
8524   return BuildExprRequirement(
8525       E, /*IsSimple=*/false, NoexceptLoc,
8526       concepts::ExprRequirement::ReturnTypeRequirement(TPL));
8527 }
8528 
8529 concepts::ExprRequirement *
8530 Sema::BuildExprRequirement(
8531     Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
8532     concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
8533   auto Status = concepts::ExprRequirement::SS_Satisfied;
8534   ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
8535   if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent())
8536     Status = concepts::ExprRequirement::SS_Dependent;
8537   else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
8538     Status = concepts::ExprRequirement::SS_NoexceptNotMet;
8539   else if (ReturnTypeRequirement.isSubstitutionFailure())
8540     Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure;
8541   else if (ReturnTypeRequirement.isTypeConstraint()) {
8542     // C++2a [expr.prim.req]p1.3.3
8543     //     The immediately-declared constraint ([temp]) of decltype((E)) shall
8544     //     be satisfied.
8545     TemplateParameterList *TPL =
8546         ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
8547     QualType MatchedType =
8548         BuildDecltypeType(E, E->getBeginLoc()).getCanonicalType();
8549     llvm::SmallVector<TemplateArgument, 1> Args;
8550     Args.push_back(TemplateArgument(MatchedType));
8551     TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args);
8552     MultiLevelTemplateArgumentList MLTAL(TAL);
8553     for (unsigned I = 0; I < TPL->getDepth(); ++I)
8554       MLTAL.addOuterRetainedLevel();
8555     Expr *IDC =
8556         cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint()
8557             ->getImmediatelyDeclaredConstraint();
8558     ExprResult Constraint = SubstExpr(IDC, MLTAL);
8559     assert(!Constraint.isInvalid() &&
8560            "Substitution cannot fail as it is simply putting a type template "
8561            "argument into a concept specialization expression's parameter.");
8562 
8563     SubstitutedConstraintExpr =
8564         cast<ConceptSpecializationExpr>(Constraint.get());
8565     if (!SubstitutedConstraintExpr->isSatisfied())
8566       Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
8567   }
8568   return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
8569                                                  ReturnTypeRequirement, Status,
8570                                                  SubstitutedConstraintExpr);
8571 }
8572 
8573 concepts::ExprRequirement *
8574 Sema::BuildExprRequirement(
8575     concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
8576     bool IsSimple, SourceLocation NoexceptLoc,
8577     concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
8578   return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
8579                                                  IsSimple, NoexceptLoc,
8580                                                  ReturnTypeRequirement);
8581 }
8582 
8583 concepts::TypeRequirement *
8584 Sema::BuildTypeRequirement(TypeSourceInfo *Type) {
8585   return new (Context) concepts::TypeRequirement(Type);
8586 }
8587 
8588 concepts::TypeRequirement *
8589 Sema::BuildTypeRequirement(
8590     concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
8591   return new (Context) concepts::TypeRequirement(SubstDiag);
8592 }
8593 
8594 concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) {
8595   return BuildNestedRequirement(Constraint);
8596 }
8597 
8598 concepts::NestedRequirement *
8599 Sema::BuildNestedRequirement(Expr *Constraint) {
8600   ConstraintSatisfaction Satisfaction;
8601   if (!Constraint->isInstantiationDependent() &&
8602       CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
8603                                   Constraint->getSourceRange(), Satisfaction))
8604     return nullptr;
8605   return new (Context) concepts::NestedRequirement(Context, Constraint,
8606                                                    Satisfaction);
8607 }
8608 
8609 concepts::NestedRequirement *
8610 Sema::BuildNestedRequirement(
8611     concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
8612   return new (Context) concepts::NestedRequirement(SubstDiag);
8613 }
8614 
8615 RequiresExprBodyDecl *
8616 Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8617                              ArrayRef<ParmVarDecl *> LocalParameters,
8618                              Scope *BodyScope) {
8619   assert(BodyScope);
8620 
8621   RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext,
8622                                                             RequiresKWLoc);
8623 
8624   PushDeclContext(BodyScope, Body);
8625 
8626   for (ParmVarDecl *Param : LocalParameters) {
8627     if (Param->hasDefaultArg())
8628       // C++2a [expr.prim.req] p4
8629       //     [...] A local parameter of a requires-expression shall not have a
8630       //     default argument. [...]
8631       Diag(Param->getDefaultArgRange().getBegin(),
8632            diag::err_requires_expr_local_parameter_default_argument);
8633     // Ignore default argument and move on
8634 
8635     Param->setDeclContext(Body);
8636     // If this has an identifier, add it to the scope stack.
8637     if (Param->getIdentifier()) {
8638       CheckShadow(BodyScope, Param);
8639       PushOnScopeChains(Param, BodyScope);
8640     }
8641   }
8642   return Body;
8643 }
8644 
8645 void Sema::ActOnFinishRequiresExpr() {
8646   assert(CurContext && "DeclContext imbalance!");
8647   CurContext = CurContext->getLexicalParent();
8648   assert(CurContext && "Popped translation unit!");
8649 }
8650 
8651 ExprResult
8652 Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8653                         RequiresExprBodyDecl *Body,
8654                         ArrayRef<ParmVarDecl *> LocalParameters,
8655                         ArrayRef<concepts::Requirement *> Requirements,
8656                         SourceLocation ClosingBraceLoc) {
8657   auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters,
8658                                   Requirements, ClosingBraceLoc);
8659   if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE))
8660     return ExprError();
8661   return RE;
8662 }
8663