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