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