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