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