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