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