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