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