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