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