• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief Implements semantic analysis for C++ expressions.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Sema/SemaInternal.h"
16 #include "TypeLocBuilder.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/RecursiveASTVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ParsedTemplate.h"
34 #include "clang/Sema/Scope.h"
35 #include "clang/Sema/ScopeInfo.h"
36 #include "clang/Sema/SemaLambda.h"
37 #include "clang/Sema/TemplateDeduction.h"
38 #include "llvm/ADT/APInt.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/Support/ErrorHandling.h"
41 using namespace clang;
42 using namespace sema;
43 
44 /// \brief Handle the result of the special case name lookup for inheriting
45 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46 /// constructor names in member using declarations, even if 'X' is not the
47 /// name of the corresponding type.
getInheritingConstructorName(CXXScopeSpec & SS,SourceLocation NameLoc,IdentifierInfo & Name)48 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49                                               SourceLocation NameLoc,
50                                               IdentifierInfo &Name) {
51   NestedNameSpecifier *NNS = SS.getScopeRep();
52 
53   // Convert the nested-name-specifier into a type.
54   QualType Type;
55   switch (NNS->getKind()) {
56   case NestedNameSpecifier::TypeSpec:
57   case NestedNameSpecifier::TypeSpecWithTemplate:
58     Type = QualType(NNS->getAsType(), 0);
59     break;
60 
61   case NestedNameSpecifier::Identifier:
62     // Strip off the last layer of the nested-name-specifier and build a
63     // typename type for it.
64     assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65     Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66                                         NNS->getAsIdentifier());
67     break;
68 
69   case NestedNameSpecifier::Global:
70   case NestedNameSpecifier::Namespace:
71   case NestedNameSpecifier::NamespaceAlias:
72     llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
73   }
74 
75   // This reference to the type is located entirely at the location of the
76   // final identifier in the qualified-id.
77   return CreateParsedType(Type,
78                           Context.getTrivialTypeSourceInfo(Type, NameLoc));
79 }
80 
getDestructorName(SourceLocation TildeLoc,IdentifierInfo & II,SourceLocation NameLoc,Scope * S,CXXScopeSpec & SS,ParsedType ObjectTypePtr,bool EnteringContext)81 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
82                                    IdentifierInfo &II,
83                                    SourceLocation NameLoc,
84                                    Scope *S, CXXScopeSpec &SS,
85                                    ParsedType ObjectTypePtr,
86                                    bool EnteringContext) {
87   // Determine where to perform name lookup.
88 
89   // FIXME: This area of the standard is very messy, and the current
90   // wording is rather unclear about which scopes we search for the
91   // destructor name; see core issues 399 and 555. Issue 399 in
92   // particular shows where the current description of destructor name
93   // lookup is completely out of line with existing practice, e.g.,
94   // this appears to be ill-formed:
95   //
96   //   namespace N {
97   //     template <typename T> struct S {
98   //       ~S();
99   //     };
100   //   }
101   //
102   //   void f(N::S<int>* s) {
103   //     s->N::S<int>::~S();
104   //   }
105   //
106   // See also PR6358 and PR6359.
107   // For this reason, we're currently only doing the C++03 version of this
108   // code; the C++0x version has to wait until we get a proper spec.
109   QualType SearchType;
110   DeclContext *LookupCtx = nullptr;
111   bool isDependent = false;
112   bool LookInScope = false;
113 
114   // If we have an object type, it's because we are in a
115   // pseudo-destructor-expression or a member access expression, and
116   // we know what type we're looking for.
117   if (ObjectTypePtr)
118     SearchType = GetTypeFromParser(ObjectTypePtr);
119 
120   if (SS.isSet()) {
121     NestedNameSpecifier *NNS = SS.getScopeRep();
122 
123     bool AlreadySearched = false;
124     bool LookAtPrefix = true;
125     // C++11 [basic.lookup.qual]p6:
126     //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
127     //   the type-names are looked up as types in the scope designated by the
128     //   nested-name-specifier. Similarly, in a qualified-id of the form:
129     //
130     //     nested-name-specifier[opt] class-name :: ~ class-name
131     //
132     //   the second class-name is looked up in the same scope as the first.
133     //
134     // Here, we determine whether the code below is permitted to look at the
135     // prefix of the nested-name-specifier.
136     DeclContext *DC = computeDeclContext(SS, EnteringContext);
137     if (DC && DC->isFileContext()) {
138       AlreadySearched = true;
139       LookupCtx = DC;
140       isDependent = false;
141     } else if (DC && isa<CXXRecordDecl>(DC)) {
142       LookAtPrefix = false;
143       LookInScope = true;
144     }
145 
146     // The second case from the C++03 rules quoted further above.
147     NestedNameSpecifier *Prefix = nullptr;
148     if (AlreadySearched) {
149       // Nothing left to do.
150     } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
151       CXXScopeSpec PrefixSS;
152       PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
153       LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
154       isDependent = isDependentScopeSpecifier(PrefixSS);
155     } else if (ObjectTypePtr) {
156       LookupCtx = computeDeclContext(SearchType);
157       isDependent = SearchType->isDependentType();
158     } else {
159       LookupCtx = computeDeclContext(SS, EnteringContext);
160       isDependent = LookupCtx && LookupCtx->isDependentContext();
161     }
162   } else if (ObjectTypePtr) {
163     // C++ [basic.lookup.classref]p3:
164     //   If the unqualified-id is ~type-name, the type-name is looked up
165     //   in the context of the entire postfix-expression. If the type T
166     //   of the object expression is of a class type C, the type-name is
167     //   also looked up in the scope of class C. At least one of the
168     //   lookups shall find a name that refers to (possibly
169     //   cv-qualified) T.
170     LookupCtx = computeDeclContext(SearchType);
171     isDependent = SearchType->isDependentType();
172     assert((isDependent || !SearchType->isIncompleteType()) &&
173            "Caller should have completed object type");
174 
175     LookInScope = true;
176   } else {
177     // Perform lookup into the current scope (only).
178     LookInScope = true;
179   }
180 
181   TypeDecl *NonMatchingTypeDecl = nullptr;
182   LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
183   for (unsigned Step = 0; Step != 2; ++Step) {
184     // Look for the name first in the computed lookup context (if we
185     // have one) and, if that fails to find a match, in the scope (if
186     // we're allowed to look there).
187     Found.clear();
188     if (Step == 0 && LookupCtx)
189       LookupQualifiedName(Found, LookupCtx);
190     else if (Step == 1 && LookInScope && S)
191       LookupName(Found, S);
192     else
193       continue;
194 
195     // FIXME: Should we be suppressing ambiguities here?
196     if (Found.isAmbiguous())
197       return ParsedType();
198 
199     if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
200       QualType T = Context.getTypeDeclType(Type);
201 
202       if (SearchType.isNull() || SearchType->isDependentType() ||
203           Context.hasSameUnqualifiedType(T, SearchType)) {
204         // We found our type!
205 
206         return CreateParsedType(T,
207                                 Context.getTrivialTypeSourceInfo(T, NameLoc));
208       }
209 
210       if (!SearchType.isNull())
211         NonMatchingTypeDecl = Type;
212     }
213 
214     // If the name that we found is a class template name, and it is
215     // the same name as the template name in the last part of the
216     // nested-name-specifier (if present) or the object type, then
217     // this is the destructor for that class.
218     // FIXME: This is a workaround until we get real drafting for core
219     // issue 399, for which there isn't even an obvious direction.
220     if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
221       QualType MemberOfType;
222       if (SS.isSet()) {
223         if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
224           // Figure out the type of the context, if it has one.
225           if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
226             MemberOfType = Context.getTypeDeclType(Record);
227         }
228       }
229       if (MemberOfType.isNull())
230         MemberOfType = SearchType;
231 
232       if (MemberOfType.isNull())
233         continue;
234 
235       // We're referring into a class template specialization. If the
236       // class template we found is the same as the template being
237       // specialized, we found what we are looking for.
238       if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
239         if (ClassTemplateSpecializationDecl *Spec
240               = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
241           if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
242                 Template->getCanonicalDecl())
243             return CreateParsedType(
244                 MemberOfType,
245                 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
246         }
247 
248         continue;
249       }
250 
251       // We're referring to an unresolved class template
252       // specialization. Determine whether we class template we found
253       // is the same as the template being specialized or, if we don't
254       // know which template is being specialized, that it at least
255       // has the same name.
256       if (const TemplateSpecializationType *SpecType
257             = MemberOfType->getAs<TemplateSpecializationType>()) {
258         TemplateName SpecName = SpecType->getTemplateName();
259 
260         // The class template we found is the same template being
261         // specialized.
262         if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
263           if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
264             return CreateParsedType(
265                 MemberOfType,
266                 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
267 
268           continue;
269         }
270 
271         // The class template we found has the same name as the
272         // (dependent) template name being specialized.
273         if (DependentTemplateName *DepTemplate
274                                     = SpecName.getAsDependentTemplateName()) {
275           if (DepTemplate->isIdentifier() &&
276               DepTemplate->getIdentifier() == Template->getIdentifier())
277             return CreateParsedType(
278                 MemberOfType,
279                 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
280 
281           continue;
282         }
283       }
284     }
285   }
286 
287   if (isDependent) {
288     // We didn't find our type, but that's okay: it's dependent
289     // anyway.
290 
291     // FIXME: What if we have no nested-name-specifier?
292     QualType T = CheckTypenameType(ETK_None, SourceLocation(),
293                                    SS.getWithLocInContext(Context),
294                                    II, NameLoc);
295     return ParsedType::make(T);
296   }
297 
298   if (NonMatchingTypeDecl) {
299     QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
300     Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
301       << T << SearchType;
302     Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
303       << T;
304   } else if (ObjectTypePtr)
305     Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
306       << &II;
307   else {
308     SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
309                                           diag::err_destructor_class_name);
310     if (S) {
311       const DeclContext *Ctx = S->getEntity();
312       if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
313         DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
314                                                  Class->getNameAsString());
315     }
316   }
317 
318   return ParsedType();
319 }
320 
getDestructorType(const DeclSpec & DS,ParsedType ObjectType)321 ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
322     if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
323       return ParsedType();
324     assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
325            && "only get destructor types from declspecs");
326     QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
327     QualType SearchType = GetTypeFromParser(ObjectType);
328     if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
329       return ParsedType::make(T);
330     }
331 
332     Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
333       << T << SearchType;
334     return ParsedType();
335 }
336 
checkLiteralOperatorId(const CXXScopeSpec & SS,const UnqualifiedId & Name)337 bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
338                                   const UnqualifiedId &Name) {
339   assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
340 
341   if (!SS.isValid())
342     return false;
343 
344   switch (SS.getScopeRep()->getKind()) {
345   case NestedNameSpecifier::Identifier:
346   case NestedNameSpecifier::TypeSpec:
347   case NestedNameSpecifier::TypeSpecWithTemplate:
348     // Per C++11 [over.literal]p2, literal operators can only be declared at
349     // namespace scope. Therefore, this unqualified-id cannot name anything.
350     // Reject it early, because we have no AST representation for this in the
351     // case where the scope is dependent.
352     Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
353       << SS.getScopeRep();
354     return true;
355 
356   case NestedNameSpecifier::Global:
357   case NestedNameSpecifier::Namespace:
358   case NestedNameSpecifier::NamespaceAlias:
359     return false;
360   }
361 
362   llvm_unreachable("unknown nested name specifier kind");
363 }
364 
365 /// \brief Build a C++ typeid expression with a type operand.
BuildCXXTypeId(QualType TypeInfoType,SourceLocation TypeidLoc,TypeSourceInfo * Operand,SourceLocation RParenLoc)366 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
367                                 SourceLocation TypeidLoc,
368                                 TypeSourceInfo *Operand,
369                                 SourceLocation RParenLoc) {
370   // C++ [expr.typeid]p4:
371   //   The top-level cv-qualifiers of the lvalue expression or the type-id
372   //   that is the operand of typeid are always ignored.
373   //   If the type of the type-id is a class type or a reference to a class
374   //   type, the class shall be completely-defined.
375   Qualifiers Quals;
376   QualType T
377     = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
378                                       Quals);
379   if (T->getAs<RecordType>() &&
380       RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
381     return ExprError();
382 
383   return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
384                                      SourceRange(TypeidLoc, RParenLoc));
385 }
386 
387 /// \brief Build a C++ typeid expression with an expression operand.
BuildCXXTypeId(QualType TypeInfoType,SourceLocation TypeidLoc,Expr * E,SourceLocation RParenLoc)388 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
389                                 SourceLocation TypeidLoc,
390                                 Expr *E,
391                                 SourceLocation RParenLoc) {
392   if (E && !E->isTypeDependent()) {
393     if (E->getType()->isPlaceholderType()) {
394       ExprResult result = CheckPlaceholderExpr(E);
395       if (result.isInvalid()) return ExprError();
396       E = result.get();
397     }
398 
399     QualType T = E->getType();
400     if (const RecordType *RecordT = T->getAs<RecordType>()) {
401       CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
402       // C++ [expr.typeid]p3:
403       //   [...] If the type of the expression is a class type, the class
404       //   shall be completely-defined.
405       if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
406         return ExprError();
407 
408       // C++ [expr.typeid]p3:
409       //   When typeid is applied to an expression other than an glvalue of a
410       //   polymorphic class type [...] [the] expression is an unevaluated
411       //   operand. [...]
412       if (RecordD->isPolymorphic() && E->isGLValue()) {
413         // The subexpression is potentially evaluated; switch the context
414         // and recheck the subexpression.
415         ExprResult Result = TransformToPotentiallyEvaluated(E);
416         if (Result.isInvalid()) return ExprError();
417         E = Result.get();
418 
419         // We require a vtable to query the type at run time.
420         MarkVTableUsed(TypeidLoc, RecordD);
421       }
422     }
423 
424     // C++ [expr.typeid]p4:
425     //   [...] If the type of the type-id is a reference to a possibly
426     //   cv-qualified type, the result of the typeid expression refers to a
427     //   std::type_info object representing the cv-unqualified referenced
428     //   type.
429     Qualifiers Quals;
430     QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
431     if (!Context.hasSameType(T, UnqualT)) {
432       T = UnqualT;
433       E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
434     }
435   }
436 
437   return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
438                                      SourceRange(TypeidLoc, RParenLoc));
439 }
440 
441 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
442 ExprResult
ActOnCXXTypeid(SourceLocation OpLoc,SourceLocation LParenLoc,bool isType,void * TyOrExpr,SourceLocation RParenLoc)443 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
444                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
445   // Find the std::type_info type.
446   if (!getStdNamespace())
447     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
448 
449   if (!CXXTypeInfoDecl) {
450     IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
451     LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
452     LookupQualifiedName(R, getStdNamespace());
453     CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
454     // Microsoft's typeinfo doesn't have type_info in std but in the global
455     // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
456     if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
457       LookupQualifiedName(R, Context.getTranslationUnitDecl());
458       CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
459     }
460     if (!CXXTypeInfoDecl)
461       return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
462   }
463 
464   if (!getLangOpts().RTTI) {
465     return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
466   }
467 
468   QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
469 
470   if (isType) {
471     // The operand is a type; handle it as such.
472     TypeSourceInfo *TInfo = nullptr;
473     QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
474                                    &TInfo);
475     if (T.isNull())
476       return ExprError();
477 
478     if (!TInfo)
479       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
480 
481     return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
482   }
483 
484   // The operand is an expression.
485   return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
486 }
487 
488 /// \brief Build a Microsoft __uuidof expression with a type operand.
BuildCXXUuidof(QualType TypeInfoType,SourceLocation TypeidLoc,TypeSourceInfo * Operand,SourceLocation RParenLoc)489 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
490                                 SourceLocation TypeidLoc,
491                                 TypeSourceInfo *Operand,
492                                 SourceLocation RParenLoc) {
493   if (!Operand->getType()->isDependentType()) {
494     bool HasMultipleGUIDs = false;
495     if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType(),
496                                           &HasMultipleGUIDs)) {
497       if (HasMultipleGUIDs)
498         return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
499       else
500         return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
501     }
502   }
503 
504   return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand,
505                                      SourceRange(TypeidLoc, RParenLoc));
506 }
507 
508 /// \brief Build a Microsoft __uuidof expression with an expression operand.
BuildCXXUuidof(QualType TypeInfoType,SourceLocation TypeidLoc,Expr * E,SourceLocation RParenLoc)509 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
510                                 SourceLocation TypeidLoc,
511                                 Expr *E,
512                                 SourceLocation RParenLoc) {
513   if (!E->getType()->isDependentType()) {
514     bool HasMultipleGUIDs = false;
515     if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType(), &HasMultipleGUIDs) &&
516         !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
517       if (HasMultipleGUIDs)
518         return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
519       else
520         return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
521     }
522   }
523 
524   return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E,
525                                      SourceRange(TypeidLoc, RParenLoc));
526 }
527 
528 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
529 ExprResult
ActOnCXXUuidof(SourceLocation OpLoc,SourceLocation LParenLoc,bool isType,void * TyOrExpr,SourceLocation RParenLoc)530 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
531                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
532   // If MSVCGuidDecl has not been cached, do the lookup.
533   if (!MSVCGuidDecl) {
534     IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
535     LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
536     LookupQualifiedName(R, Context.getTranslationUnitDecl());
537     MSVCGuidDecl = R.getAsSingle<RecordDecl>();
538     if (!MSVCGuidDecl)
539       return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
540   }
541 
542   QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
543 
544   if (isType) {
545     // The operand is a type; handle it as such.
546     TypeSourceInfo *TInfo = nullptr;
547     QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
548                                    &TInfo);
549     if (T.isNull())
550       return ExprError();
551 
552     if (!TInfo)
553       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
554 
555     return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
556   }
557 
558   // The operand is an expression.
559   return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
560 }
561 
562 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
563 ExprResult
ActOnCXXBoolLiteral(SourceLocation OpLoc,tok::TokenKind Kind)564 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
565   assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
566          "Unknown C++ Boolean value!");
567   return new (Context)
568       CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
569 }
570 
571 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
572 ExprResult
ActOnCXXNullPtrLiteral(SourceLocation Loc)573 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
574   return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
575 }
576 
577 /// ActOnCXXThrow - Parse throw expressions.
578 ExprResult
ActOnCXXThrow(Scope * S,SourceLocation OpLoc,Expr * Ex)579 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
580   bool IsThrownVarInScope = false;
581   if (Ex) {
582     // C++0x [class.copymove]p31:
583     //   When certain criteria are met, an implementation is allowed to omit the
584     //   copy/move construction of a class object [...]
585     //
586     //     - in a throw-expression, when the operand is the name of a
587     //       non-volatile automatic object (other than a function or catch-
588     //       clause parameter) whose scope does not extend beyond the end of the
589     //       innermost enclosing try-block (if there is one), the copy/move
590     //       operation from the operand to the exception object (15.1) can be
591     //       omitted by constructing the automatic object directly into the
592     //       exception object
593     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
594       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
595         if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
596           for( ; S; S = S->getParent()) {
597             if (S->isDeclScope(Var)) {
598               IsThrownVarInScope = true;
599               break;
600             }
601 
602             if (S->getFlags() &
603                 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
604                  Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
605                  Scope::TryScope))
606               break;
607           }
608         }
609       }
610   }
611 
612   return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
613 }
614 
BuildCXXThrow(SourceLocation OpLoc,Expr * Ex,bool IsThrownVarInScope)615 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
616                                bool IsThrownVarInScope) {
617   // Don't report an error if 'throw' is used in system headers.
618   if (!getLangOpts().CXXExceptions &&
619       !getSourceManager().isInSystemHeader(OpLoc))
620     Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
621 
622   if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
623     Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
624 
625   if (Ex && !Ex->isTypeDependent()) {
626     ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
627     if (ExRes.isInvalid())
628       return ExprError();
629     Ex = ExRes.get();
630   }
631 
632   return new (Context)
633       CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
634 }
635 
636 /// CheckCXXThrowOperand - Validate the operand of a throw.
CheckCXXThrowOperand(SourceLocation ThrowLoc,Expr * E,bool IsThrownVarInScope)637 ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
638                                       bool IsThrownVarInScope) {
639   // C++ [except.throw]p3:
640   //   A throw-expression initializes a temporary object, called the exception
641   //   object, the type of which is determined by removing any top-level
642   //   cv-qualifiers from the static type of the operand of throw and adjusting
643   //   the type from "array of T" or "function returning T" to "pointer to T"
644   //   or "pointer to function returning T", [...]
645   if (E->getType().hasQualifiers())
646     E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
647                           E->getValueKind()).get();
648 
649   ExprResult Res = DefaultFunctionArrayConversion(E);
650   if (Res.isInvalid())
651     return ExprError();
652   E = Res.get();
653 
654   //   If the type of the exception would be an incomplete type or a pointer
655   //   to an incomplete type other than (cv) void the program is ill-formed.
656   QualType Ty = E->getType();
657   bool isPointer = false;
658   if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
659     Ty = Ptr->getPointeeType();
660     isPointer = true;
661   }
662   if (!isPointer || !Ty->isVoidType()) {
663     if (RequireCompleteType(ThrowLoc, Ty,
664                             isPointer? diag::err_throw_incomplete_ptr
665                                      : diag::err_throw_incomplete,
666                             E->getSourceRange()))
667       return ExprError();
668 
669     if (RequireNonAbstractType(ThrowLoc, E->getType(),
670                                diag::err_throw_abstract_type, E))
671       return ExprError();
672   }
673 
674   // Initialize the exception result.  This implicitly weeds out
675   // abstract types or types with inaccessible copy constructors.
676 
677   // C++0x [class.copymove]p31:
678   //   When certain criteria are met, an implementation is allowed to omit the
679   //   copy/move construction of a class object [...]
680   //
681   //     - in a throw-expression, when the operand is the name of a
682   //       non-volatile automatic object (other than a function or catch-clause
683   //       parameter) whose scope does not extend beyond the end of the
684   //       innermost enclosing try-block (if there is one), the copy/move
685   //       operation from the operand to the exception object (15.1) can be
686   //       omitted by constructing the automatic object directly into the
687   //       exception object
688   const VarDecl *NRVOVariable = nullptr;
689   if (IsThrownVarInScope)
690     NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
691 
692   InitializedEntity Entity =
693       InitializedEntity::InitializeException(ThrowLoc, E->getType(),
694                                              /*NRVO=*/NRVOVariable != nullptr);
695   Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
696                                         QualType(), E,
697                                         IsThrownVarInScope);
698   if (Res.isInvalid())
699     return ExprError();
700   E = Res.get();
701 
702   // If the exception has class type, we need additional handling.
703   const RecordType *RecordTy = Ty->getAs<RecordType>();
704   if (!RecordTy)
705     return E;
706   CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
707 
708   // If we are throwing a polymorphic class type or pointer thereof,
709   // exception handling will make use of the vtable.
710   MarkVTableUsed(ThrowLoc, RD);
711 
712   // If a pointer is thrown, the referenced object will not be destroyed.
713   if (isPointer)
714     return E;
715 
716   // If the class has a destructor, we must be able to call it.
717   if (RD->hasIrrelevantDestructor())
718     return E;
719 
720   CXXDestructorDecl *Destructor = LookupDestructor(RD);
721   if (!Destructor)
722     return E;
723 
724   MarkFunctionReferenced(E->getExprLoc(), Destructor);
725   CheckDestructorAccess(E->getExprLoc(), Destructor,
726                         PDiag(diag::err_access_dtor_exception) << Ty);
727   if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
728     return ExprError();
729   return E;
730 }
731 
getCurrentThisType()732 QualType Sema::getCurrentThisType() {
733   DeclContext *DC = getFunctionLevelDeclContext();
734   QualType ThisTy = CXXThisTypeOverride;
735   if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
736     if (method && method->isInstance())
737       ThisTy = method->getThisType(Context);
738   }
739   if (ThisTy.isNull()) {
740     if (isGenericLambdaCallOperatorSpecialization(CurContext) &&
741         CurContext->getParent()->getParent()->isRecord()) {
742       // This is a generic lambda call operator that is being instantiated
743       // within a default initializer - so use the enclosing class as 'this'.
744       // There is no enclosing member function to retrieve the 'this' pointer
745       // from.
746       QualType ClassTy = Context.getTypeDeclType(
747           cast<CXXRecordDecl>(CurContext->getParent()->getParent()));
748       // There are no cv-qualifiers for 'this' within default initializers,
749       // per [expr.prim.general]p4.
750       return Context.getPointerType(ClassTy);
751     }
752   }
753   return ThisTy;
754 }
755 
CXXThisScopeRAII(Sema & S,Decl * ContextDecl,unsigned CXXThisTypeQuals,bool Enabled)756 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
757                                          Decl *ContextDecl,
758                                          unsigned CXXThisTypeQuals,
759                                          bool Enabled)
760   : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
761 {
762   if (!Enabled || !ContextDecl)
763     return;
764 
765   CXXRecordDecl *Record = nullptr;
766   if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
767     Record = Template->getTemplatedDecl();
768   else
769     Record = cast<CXXRecordDecl>(ContextDecl);
770 
771   S.CXXThisTypeOverride
772     = S.Context.getPointerType(
773         S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
774 
775   this->Enabled = true;
776 }
777 
778 
~CXXThisScopeRAII()779 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
780   if (Enabled) {
781     S.CXXThisTypeOverride = OldCXXThisTypeOverride;
782   }
783 }
784 
captureThis(ASTContext & Context,RecordDecl * RD,QualType ThisTy,SourceLocation Loc)785 static Expr *captureThis(ASTContext &Context, RecordDecl *RD,
786                          QualType ThisTy, SourceLocation Loc) {
787   FieldDecl *Field
788     = FieldDecl::Create(Context, RD, Loc, Loc, nullptr, ThisTy,
789                         Context.getTrivialTypeSourceInfo(ThisTy, Loc),
790                         nullptr, false, ICIS_NoInit);
791   Field->setImplicit(true);
792   Field->setAccess(AS_private);
793   RD->addDecl(Field);
794   return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/true);
795 }
796 
CheckCXXThisCapture(SourceLocation Loc,bool Explicit,bool BuildAndDiagnose,const unsigned * const FunctionScopeIndexToStopAt)797 bool Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit,
798     bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt) {
799   // We don't need to capture this in an unevaluated context.
800   if (isUnevaluatedContext() && !Explicit)
801     return true;
802 
803   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
804     *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
805  // Otherwise, check that we can capture 'this'.
806   unsigned NumClosures = 0;
807   for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
808     if (CapturingScopeInfo *CSI =
809             dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
810       if (CSI->CXXThisCaptureIndex != 0) {
811         // 'this' is already being captured; there isn't anything more to do.
812         break;
813       }
814       LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
815       if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
816         // This context can't implicitly capture 'this'; fail out.
817         if (BuildAndDiagnose)
818           Diag(Loc, diag::err_this_capture) << Explicit;
819         return true;
820       }
821       if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
822           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
823           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
824           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
825           Explicit) {
826         // This closure can capture 'this'; continue looking upwards.
827         NumClosures++;
828         Explicit = false;
829         continue;
830       }
831       // This context can't implicitly capture 'this'; fail out.
832       if (BuildAndDiagnose)
833         Diag(Loc, diag::err_this_capture) << Explicit;
834       return true;
835     }
836     break;
837   }
838   if (!BuildAndDiagnose) return false;
839   // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
840   // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
841   // contexts.
842   for (unsigned idx = MaxFunctionScopesIndex; NumClosures;
843       --idx, --NumClosures) {
844     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
845     Expr *ThisExpr = nullptr;
846     QualType ThisTy = getCurrentThisType();
847     if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI))
848       // For lambda expressions, build a field and an initializing expression.
849       ThisExpr = captureThis(Context, LSI->Lambda, ThisTy, Loc);
850     else if (CapturedRegionScopeInfo *RSI
851         = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
852       ThisExpr = captureThis(Context, RSI->TheRecordDecl, ThisTy, Loc);
853 
854     bool isNested = NumClosures > 1;
855     CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
856   }
857   return false;
858 }
859 
ActOnCXXThis(SourceLocation Loc)860 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
861   /// C++ 9.3.2: In the body of a non-static member function, the keyword this
862   /// is a non-lvalue expression whose value is the address of the object for
863   /// which the function is called.
864 
865   QualType ThisTy = getCurrentThisType();
866   if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
867 
868   CheckCXXThisCapture(Loc);
869   return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
870 }
871 
isThisOutsideMemberFunctionBody(QualType BaseType)872 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
873   // If we're outside the body of a member function, then we'll have a specified
874   // type for 'this'.
875   if (CXXThisTypeOverride.isNull())
876     return false;
877 
878   // Determine whether we're looking into a class that's currently being
879   // defined.
880   CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
881   return Class && Class->isBeingDefined();
882 }
883 
884 ExprResult
ActOnCXXTypeConstructExpr(ParsedType TypeRep,SourceLocation LParenLoc,MultiExprArg exprs,SourceLocation RParenLoc)885 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
886                                 SourceLocation LParenLoc,
887                                 MultiExprArg exprs,
888                                 SourceLocation RParenLoc) {
889   if (!TypeRep)
890     return ExprError();
891 
892   TypeSourceInfo *TInfo;
893   QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
894   if (!TInfo)
895     TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
896 
897   return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
898 }
899 
900 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
901 /// Can be interpreted either as function-style casting ("int(x)")
902 /// or class type construction ("ClassType(x,y,z)")
903 /// or creation of a value-initialized type ("int()").
904 ExprResult
BuildCXXTypeConstructExpr(TypeSourceInfo * TInfo,SourceLocation LParenLoc,MultiExprArg Exprs,SourceLocation RParenLoc)905 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
906                                 SourceLocation LParenLoc,
907                                 MultiExprArg Exprs,
908                                 SourceLocation RParenLoc) {
909   QualType Ty = TInfo->getType();
910   SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
911 
912   if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
913     return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
914                                               RParenLoc);
915   }
916 
917   bool ListInitialization = LParenLoc.isInvalid();
918   assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
919          && "List initialization must have initializer list as expression.");
920   SourceRange FullRange = SourceRange(TyBeginLoc,
921       ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
922 
923   // C++ [expr.type.conv]p1:
924   // If the expression list is a single expression, the type conversion
925   // expression is equivalent (in definedness, and if defined in meaning) to the
926   // corresponding cast expression.
927   if (Exprs.size() == 1 && !ListInitialization) {
928     Expr *Arg = Exprs[0];
929     return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
930   }
931 
932   QualType ElemTy = Ty;
933   if (Ty->isArrayType()) {
934     if (!ListInitialization)
935       return ExprError(Diag(TyBeginLoc,
936                             diag::err_value_init_for_array_type) << FullRange);
937     ElemTy = Context.getBaseElementType(Ty);
938   }
939 
940   if (!Ty->isVoidType() &&
941       RequireCompleteType(TyBeginLoc, ElemTy,
942                           diag::err_invalid_incomplete_type_use, FullRange))
943     return ExprError();
944 
945   if (RequireNonAbstractType(TyBeginLoc, Ty,
946                              diag::err_allocation_of_abstract_type))
947     return ExprError();
948 
949   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
950   InitializationKind Kind =
951       Exprs.size() ? ListInitialization
952       ? InitializationKind::CreateDirectList(TyBeginLoc)
953       : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
954       : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
955   InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
956   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
957 
958   if (Result.isInvalid() || !ListInitialization)
959     return Result;
960 
961   Expr *Inner = Result.get();
962   if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
963     Inner = BTE->getSubExpr();
964   if (isa<InitListExpr>(Inner)) {
965     // If the list-initialization doesn't involve a constructor call, we'll get
966     // the initializer-list (with corrected type) back, but that's not what we
967     // want, since it will be treated as an initializer list in further
968     // processing. Explicitly insert a cast here.
969     QualType ResultType = Result.get()->getType();
970     Result = CXXFunctionalCastExpr::Create(
971         Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
972         CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
973   }
974 
975   // FIXME: Improve AST representation?
976   return Result;
977 }
978 
979 /// doesUsualArrayDeleteWantSize - Answers whether the usual
980 /// operator delete[] for the given type has a size_t parameter.
doesUsualArrayDeleteWantSize(Sema & S,SourceLocation loc,QualType allocType)981 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
982                                          QualType allocType) {
983   const RecordType *record =
984     allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
985   if (!record) return false;
986 
987   // Try to find an operator delete[] in class scope.
988 
989   DeclarationName deleteName =
990     S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
991   LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
992   S.LookupQualifiedName(ops, record->getDecl());
993 
994   // We're just doing this for information.
995   ops.suppressDiagnostics();
996 
997   // Very likely: there's no operator delete[].
998   if (ops.empty()) return false;
999 
1000   // If it's ambiguous, it should be illegal to call operator delete[]
1001   // on this thing, so it doesn't matter if we allocate extra space or not.
1002   if (ops.isAmbiguous()) return false;
1003 
1004   LookupResult::Filter filter = ops.makeFilter();
1005   while (filter.hasNext()) {
1006     NamedDecl *del = filter.next()->getUnderlyingDecl();
1007 
1008     // C++0x [basic.stc.dynamic.deallocation]p2:
1009     //   A template instance is never a usual deallocation function,
1010     //   regardless of its signature.
1011     if (isa<FunctionTemplateDecl>(del)) {
1012       filter.erase();
1013       continue;
1014     }
1015 
1016     // C++0x [basic.stc.dynamic.deallocation]p2:
1017     //   If class T does not declare [an operator delete[] with one
1018     //   parameter] but does declare a member deallocation function
1019     //   named operator delete[] with exactly two parameters, the
1020     //   second of which has type std::size_t, then this function
1021     //   is a usual deallocation function.
1022     if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
1023       filter.erase();
1024       continue;
1025     }
1026   }
1027   filter.done();
1028 
1029   if (!ops.isSingleResult()) return false;
1030 
1031   const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
1032   return (del->getNumParams() == 2);
1033 }
1034 
1035 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
1036 ///
1037 /// E.g.:
1038 /// @code new (memory) int[size][4] @endcode
1039 /// or
1040 /// @code ::new Foo(23, "hello") @endcode
1041 ///
1042 /// \param StartLoc The first location of the expression.
1043 /// \param UseGlobal True if 'new' was prefixed with '::'.
1044 /// \param PlacementLParen Opening paren of the placement arguments.
1045 /// \param PlacementArgs Placement new arguments.
1046 /// \param PlacementRParen Closing paren of the placement arguments.
1047 /// \param TypeIdParens If the type is in parens, the source range.
1048 /// \param D The type to be allocated, as well as array dimensions.
1049 /// \param Initializer The initializing expression or initializer-list, or null
1050 ///   if there is none.
1051 ExprResult
ActOnCXXNew(SourceLocation StartLoc,bool UseGlobal,SourceLocation PlacementLParen,MultiExprArg PlacementArgs,SourceLocation PlacementRParen,SourceRange TypeIdParens,Declarator & D,Expr * Initializer)1052 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1053                   SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1054                   SourceLocation PlacementRParen, SourceRange TypeIdParens,
1055                   Declarator &D, Expr *Initializer) {
1056   bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
1057 
1058   Expr *ArraySize = nullptr;
1059   // If the specified type is an array, unwrap it and save the expression.
1060   if (D.getNumTypeObjects() > 0 &&
1061       D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1062      DeclaratorChunk &Chunk = D.getTypeObject(0);
1063     if (TypeContainsAuto)
1064       return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1065         << D.getSourceRange());
1066     if (Chunk.Arr.hasStatic)
1067       return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1068         << D.getSourceRange());
1069     if (!Chunk.Arr.NumElts)
1070       return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1071         << D.getSourceRange());
1072 
1073     ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1074     D.DropFirstTypeObject();
1075   }
1076 
1077   // Every dimension shall be of constant size.
1078   if (ArraySize) {
1079     for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1080       if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1081         break;
1082 
1083       DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1084       if (Expr *NumElts = (Expr *)Array.NumElts) {
1085         if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1086           if (getLangOpts().CPlusPlus1y) {
1087 	    // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1088 	    //   shall be a converted constant expression (5.19) of type std::size_t
1089 	    //   and shall evaluate to a strictly positive value.
1090             unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1091             assert(IntWidth && "Builtin type of size 0?");
1092             llvm::APSInt Value(IntWidth);
1093             Array.NumElts
1094              = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1095                                                 CCEK_NewExpr)
1096                  .get();
1097           } else {
1098             Array.NumElts
1099               = VerifyIntegerConstantExpression(NumElts, nullptr,
1100                                                 diag::err_new_array_nonconst)
1101                   .get();
1102           }
1103           if (!Array.NumElts)
1104             return ExprError();
1105         }
1106       }
1107     }
1108   }
1109 
1110   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1111   QualType AllocType = TInfo->getType();
1112   if (D.isInvalidType())
1113     return ExprError();
1114 
1115   SourceRange DirectInitRange;
1116   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1117     DirectInitRange = List->getSourceRange();
1118 
1119   return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
1120                      PlacementLParen,
1121                      PlacementArgs,
1122                      PlacementRParen,
1123                      TypeIdParens,
1124                      AllocType,
1125                      TInfo,
1126                      ArraySize,
1127                      DirectInitRange,
1128                      Initializer,
1129                      TypeContainsAuto);
1130 }
1131 
isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,Expr * Init)1132 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1133                                        Expr *Init) {
1134   if (!Init)
1135     return true;
1136   if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1137     return PLE->getNumExprs() == 0;
1138   if (isa<ImplicitValueInitExpr>(Init))
1139     return true;
1140   else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1141     return !CCE->isListInitialization() &&
1142            CCE->getConstructor()->isDefaultConstructor();
1143   else if (Style == CXXNewExpr::ListInit) {
1144     assert(isa<InitListExpr>(Init) &&
1145            "Shouldn't create list CXXConstructExprs for arrays.");
1146     return true;
1147   }
1148   return false;
1149 }
1150 
1151 ExprResult
BuildCXXNew(SourceRange Range,bool UseGlobal,SourceLocation PlacementLParen,MultiExprArg PlacementArgs,SourceLocation PlacementRParen,SourceRange TypeIdParens,QualType AllocType,TypeSourceInfo * AllocTypeInfo,Expr * ArraySize,SourceRange DirectInitRange,Expr * Initializer,bool TypeMayContainAuto)1152 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1153                   SourceLocation PlacementLParen,
1154                   MultiExprArg PlacementArgs,
1155                   SourceLocation PlacementRParen,
1156                   SourceRange TypeIdParens,
1157                   QualType AllocType,
1158                   TypeSourceInfo *AllocTypeInfo,
1159                   Expr *ArraySize,
1160                   SourceRange DirectInitRange,
1161                   Expr *Initializer,
1162                   bool TypeMayContainAuto) {
1163   SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1164   SourceLocation StartLoc = Range.getBegin();
1165 
1166   CXXNewExpr::InitializationStyle initStyle;
1167   if (DirectInitRange.isValid()) {
1168     assert(Initializer && "Have parens but no initializer.");
1169     initStyle = CXXNewExpr::CallInit;
1170   } else if (Initializer && isa<InitListExpr>(Initializer))
1171     initStyle = CXXNewExpr::ListInit;
1172   else {
1173     assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1174             isa<CXXConstructExpr>(Initializer)) &&
1175            "Initializer expression that cannot have been implicitly created.");
1176     initStyle = CXXNewExpr::NoInit;
1177   }
1178 
1179   Expr **Inits = &Initializer;
1180   unsigned NumInits = Initializer ? 1 : 0;
1181   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1182     assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1183     Inits = List->getExprs();
1184     NumInits = List->getNumExprs();
1185   }
1186 
1187   // Determine whether we've already built the initializer.
1188   bool HaveCompleteInit = false;
1189   if (Initializer && isa<CXXConstructExpr>(Initializer) &&
1190       !isa<CXXTemporaryObjectExpr>(Initializer))
1191     HaveCompleteInit = true;
1192   else if (Initializer && isa<ImplicitValueInitExpr>(Initializer))
1193     HaveCompleteInit = true;
1194 
1195   // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1196   if (TypeMayContainAuto && AllocType->isUndeducedType()) {
1197     if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1198       return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1199                        << AllocType << TypeRange);
1200     if (initStyle == CXXNewExpr::ListInit ||
1201         (NumInits == 1 && isa<InitListExpr>(Inits[0])))
1202       return ExprError(Diag(Inits[0]->getLocStart(),
1203                             diag::err_auto_new_list_init)
1204                        << AllocType << TypeRange);
1205     if (NumInits > 1) {
1206       Expr *FirstBad = Inits[1];
1207       return ExprError(Diag(FirstBad->getLocStart(),
1208                             diag::err_auto_new_ctor_multiple_expressions)
1209                        << AllocType << TypeRange);
1210     }
1211     Expr *Deduce = Inits[0];
1212     QualType DeducedType;
1213     if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1214       return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1215                        << AllocType << Deduce->getType()
1216                        << TypeRange << Deduce->getSourceRange());
1217     if (DeducedType.isNull())
1218       return ExprError();
1219     AllocType = DeducedType;
1220   }
1221 
1222   // Per C++0x [expr.new]p5, the type being constructed may be a
1223   // typedef of an array type.
1224   if (!ArraySize) {
1225     if (const ConstantArrayType *Array
1226                               = Context.getAsConstantArrayType(AllocType)) {
1227       ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1228                                          Context.getSizeType(),
1229                                          TypeRange.getEnd());
1230       AllocType = Array->getElementType();
1231     }
1232   }
1233 
1234   if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1235     return ExprError();
1236 
1237   if (initStyle == CXXNewExpr::ListInit &&
1238       isStdInitializerList(AllocType, nullptr)) {
1239     Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1240          diag::warn_dangling_std_initializer_list)
1241         << /*at end of FE*/0 << Inits[0]->getSourceRange();
1242   }
1243 
1244   // In ARC, infer 'retaining' for the allocated
1245   if (getLangOpts().ObjCAutoRefCount &&
1246       AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1247       AllocType->isObjCLifetimeType()) {
1248     AllocType = Context.getLifetimeQualifiedType(AllocType,
1249                                     AllocType->getObjCARCImplicitLifetime());
1250   }
1251 
1252   QualType ResultType = Context.getPointerType(AllocType);
1253 
1254   if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1255     ExprResult result = CheckPlaceholderExpr(ArraySize);
1256     if (result.isInvalid()) return ExprError();
1257     ArraySize = result.get();
1258   }
1259   // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1260   //   integral or enumeration type with a non-negative value."
1261   // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1262   //   enumeration type, or a class type for which a single non-explicit
1263   //   conversion function to integral or unscoped enumeration type exists.
1264   // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1265   //   std::size_t.
1266   if (ArraySize && !ArraySize->isTypeDependent()) {
1267     ExprResult ConvertedSize;
1268     if (getLangOpts().CPlusPlus1y) {
1269       assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1270 
1271       ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1272 						AA_Converting);
1273 
1274       if (!ConvertedSize.isInvalid() &&
1275           ArraySize->getType()->getAs<RecordType>())
1276         // Diagnose the compatibility of this conversion.
1277         Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1278           << ArraySize->getType() << 0 << "'size_t'";
1279     } else {
1280       class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1281       protected:
1282         Expr *ArraySize;
1283 
1284       public:
1285         SizeConvertDiagnoser(Expr *ArraySize)
1286             : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1287               ArraySize(ArraySize) {}
1288 
1289         SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1290                                              QualType T) override {
1291           return S.Diag(Loc, diag::err_array_size_not_integral)
1292                    << S.getLangOpts().CPlusPlus11 << T;
1293         }
1294 
1295         SemaDiagnosticBuilder diagnoseIncomplete(
1296             Sema &S, SourceLocation Loc, QualType T) override {
1297           return S.Diag(Loc, diag::err_array_size_incomplete_type)
1298                    << T << ArraySize->getSourceRange();
1299         }
1300 
1301         SemaDiagnosticBuilder diagnoseExplicitConv(
1302             Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1303           return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1304         }
1305 
1306         SemaDiagnosticBuilder noteExplicitConv(
1307             Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1308           return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1309                    << ConvTy->isEnumeralType() << ConvTy;
1310         }
1311 
1312         SemaDiagnosticBuilder diagnoseAmbiguous(
1313             Sema &S, SourceLocation Loc, QualType T) override {
1314           return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1315         }
1316 
1317         SemaDiagnosticBuilder noteAmbiguous(
1318             Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1319           return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1320                    << ConvTy->isEnumeralType() << ConvTy;
1321         }
1322 
1323         virtual SemaDiagnosticBuilder diagnoseConversion(
1324             Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1325           return S.Diag(Loc,
1326                         S.getLangOpts().CPlusPlus11
1327                           ? diag::warn_cxx98_compat_array_size_conversion
1328                           : diag::ext_array_size_conversion)
1329                    << T << ConvTy->isEnumeralType() << ConvTy;
1330         }
1331       } SizeDiagnoser(ArraySize);
1332 
1333       ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1334                                                           SizeDiagnoser);
1335     }
1336     if (ConvertedSize.isInvalid())
1337       return ExprError();
1338 
1339     ArraySize = ConvertedSize.get();
1340     QualType SizeType = ArraySize->getType();
1341 
1342     if (!SizeType->isIntegralOrUnscopedEnumerationType())
1343       return ExprError();
1344 
1345     // C++98 [expr.new]p7:
1346     //   The expression in a direct-new-declarator shall have integral type
1347     //   with a non-negative value.
1348     //
1349     // Let's see if this is a constant < 0. If so, we reject it out of
1350     // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1351     // array type.
1352     //
1353     // Note: such a construct has well-defined semantics in C++11: it throws
1354     // std::bad_array_new_length.
1355     if (!ArraySize->isValueDependent()) {
1356       llvm::APSInt Value;
1357       // We've already performed any required implicit conversion to integer or
1358       // unscoped enumeration type.
1359       if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1360         if (Value < llvm::APSInt(
1361                         llvm::APInt::getNullValue(Value.getBitWidth()),
1362                                  Value.isUnsigned())) {
1363           if (getLangOpts().CPlusPlus11)
1364             Diag(ArraySize->getLocStart(),
1365                  diag::warn_typecheck_negative_array_new_size)
1366               << ArraySize->getSourceRange();
1367           else
1368             return ExprError(Diag(ArraySize->getLocStart(),
1369                                   diag::err_typecheck_negative_array_size)
1370                              << ArraySize->getSourceRange());
1371         } else if (!AllocType->isDependentType()) {
1372           unsigned ActiveSizeBits =
1373             ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1374           if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1375             if (getLangOpts().CPlusPlus11)
1376               Diag(ArraySize->getLocStart(),
1377                    diag::warn_array_new_too_large)
1378                 << Value.toString(10)
1379                 << ArraySize->getSourceRange();
1380             else
1381               return ExprError(Diag(ArraySize->getLocStart(),
1382                                     diag::err_array_too_large)
1383                                << Value.toString(10)
1384                                << ArraySize->getSourceRange());
1385           }
1386         }
1387       } else if (TypeIdParens.isValid()) {
1388         // Can't have dynamic array size when the type-id is in parentheses.
1389         Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1390           << ArraySize->getSourceRange()
1391           << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1392           << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1393 
1394         TypeIdParens = SourceRange();
1395       }
1396     }
1397 
1398     // Note that we do *not* convert the argument in any way.  It can
1399     // be signed, larger than size_t, whatever.
1400   }
1401 
1402   FunctionDecl *OperatorNew = nullptr;
1403   FunctionDecl *OperatorDelete = nullptr;
1404 
1405   if (!AllocType->isDependentType() &&
1406       !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
1407       FindAllocationFunctions(StartLoc,
1408                               SourceRange(PlacementLParen, PlacementRParen),
1409                               UseGlobal, AllocType, ArraySize, PlacementArgs,
1410                               OperatorNew, OperatorDelete))
1411     return ExprError();
1412 
1413   // If this is an array allocation, compute whether the usual array
1414   // deallocation function for the type has a size_t parameter.
1415   bool UsualArrayDeleteWantsSize = false;
1416   if (ArraySize && !AllocType->isDependentType())
1417     UsualArrayDeleteWantsSize
1418       = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1419 
1420   SmallVector<Expr *, 8> AllPlaceArgs;
1421   if (OperatorNew) {
1422     const FunctionProtoType *Proto =
1423         OperatorNew->getType()->getAs<FunctionProtoType>();
1424     VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1425                                                     : VariadicDoesNotApply;
1426 
1427     // We've already converted the placement args, just fill in any default
1428     // arguments. Skip the first parameter because we don't have a corresponding
1429     // argument.
1430     if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1,
1431                                PlacementArgs, AllPlaceArgs, CallType))
1432       return ExprError();
1433 
1434     if (!AllPlaceArgs.empty())
1435       PlacementArgs = AllPlaceArgs;
1436 
1437     // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
1438     DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
1439 
1440     // FIXME: Missing call to CheckFunctionCall or equivalent
1441   }
1442 
1443   // Warn if the type is over-aligned and is being allocated by global operator
1444   // new.
1445   if (PlacementArgs.empty() && OperatorNew &&
1446       (OperatorNew->isImplicit() ||
1447        getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1448     if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1449       unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1450       if (Align > SuitableAlign)
1451         Diag(StartLoc, diag::warn_overaligned_type)
1452             << AllocType
1453             << unsigned(Align / Context.getCharWidth())
1454             << unsigned(SuitableAlign / Context.getCharWidth());
1455     }
1456   }
1457 
1458   QualType InitType = AllocType;
1459   // Array 'new' can't have any initializers except empty parentheses.
1460   // Initializer lists are also allowed, in C++11. Rely on the parser for the
1461   // dialect distinction.
1462   if (ResultType->isArrayType() || ArraySize) {
1463     if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1464       SourceRange InitRange(Inits[0]->getLocStart(),
1465                             Inits[NumInits - 1]->getLocEnd());
1466       Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1467       return ExprError();
1468     }
1469     if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1470       // We do the initialization typechecking against the array type
1471       // corresponding to the number of initializers + 1 (to also check
1472       // default-initialization).
1473       unsigned NumElements = ILE->getNumInits() + 1;
1474       InitType = Context.getConstantArrayType(AllocType,
1475           llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1476                                               ArrayType::Normal, 0);
1477     }
1478   }
1479 
1480   // If we can perform the initialization, and we've not already done so,
1481   // do it now.
1482   if (!AllocType->isDependentType() &&
1483       !Expr::hasAnyTypeDependentArguments(
1484         llvm::makeArrayRef(Inits, NumInits)) &&
1485       !HaveCompleteInit) {
1486     // C++11 [expr.new]p15:
1487     //   A new-expression that creates an object of type T initializes that
1488     //   object as follows:
1489     InitializationKind Kind
1490     //     - If the new-initializer is omitted, the object is default-
1491     //       initialized (8.5); if no initialization is performed,
1492     //       the object has indeterminate value
1493       = initStyle == CXXNewExpr::NoInit
1494           ? InitializationKind::CreateDefault(TypeRange.getBegin())
1495     //     - Otherwise, the new-initializer is interpreted according to the
1496     //       initialization rules of 8.5 for direct-initialization.
1497           : initStyle == CXXNewExpr::ListInit
1498               ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1499               : InitializationKind::CreateDirect(TypeRange.getBegin(),
1500                                                  DirectInitRange.getBegin(),
1501                                                  DirectInitRange.getEnd());
1502 
1503     InitializedEntity Entity
1504       = InitializedEntity::InitializeNew(StartLoc, InitType);
1505     InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1506     ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1507                                           MultiExprArg(Inits, NumInits));
1508     if (FullInit.isInvalid())
1509       return ExprError();
1510 
1511     // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1512     // we don't want the initialized object to be destructed.
1513     if (CXXBindTemporaryExpr *Binder =
1514             dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1515       FullInit = Binder->getSubExpr();
1516 
1517     Initializer = FullInit.get();
1518   }
1519 
1520   // Mark the new and delete operators as referenced.
1521   if (OperatorNew) {
1522     if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1523       return ExprError();
1524     MarkFunctionReferenced(StartLoc, OperatorNew);
1525   }
1526   if (OperatorDelete) {
1527     if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1528       return ExprError();
1529     MarkFunctionReferenced(StartLoc, OperatorDelete);
1530   }
1531 
1532   // C++0x [expr.new]p17:
1533   //   If the new expression creates an array of objects of class type,
1534   //   access and ambiguity control are done for the destructor.
1535   QualType BaseAllocType = Context.getBaseElementType(AllocType);
1536   if (ArraySize && !BaseAllocType->isDependentType()) {
1537     if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1538       if (CXXDestructorDecl *dtor = LookupDestructor(
1539               cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1540         MarkFunctionReferenced(StartLoc, dtor);
1541         CheckDestructorAccess(StartLoc, dtor,
1542                               PDiag(diag::err_access_dtor)
1543                                 << BaseAllocType);
1544         if (DiagnoseUseOfDecl(dtor, StartLoc))
1545           return ExprError();
1546       }
1547     }
1548   }
1549 
1550   return new (Context)
1551       CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete,
1552                  UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
1553                  ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
1554                  Range, DirectInitRange);
1555 }
1556 
1557 /// \brief Checks that a type is suitable as the allocated type
1558 /// in a new-expression.
CheckAllocatedType(QualType AllocType,SourceLocation Loc,SourceRange R)1559 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1560                               SourceRange R) {
1561   // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1562   //   abstract class type or array thereof.
1563   if (AllocType->isFunctionType())
1564     return Diag(Loc, diag::err_bad_new_type)
1565       << AllocType << 0 << R;
1566   else if (AllocType->isReferenceType())
1567     return Diag(Loc, diag::err_bad_new_type)
1568       << AllocType << 1 << R;
1569   else if (!AllocType->isDependentType() &&
1570            RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
1571     return true;
1572   else if (RequireNonAbstractType(Loc, AllocType,
1573                                   diag::err_allocation_of_abstract_type))
1574     return true;
1575   else if (AllocType->isVariablyModifiedType())
1576     return Diag(Loc, diag::err_variably_modified_new_type)
1577              << AllocType;
1578   else if (unsigned AddressSpace = AllocType.getAddressSpace())
1579     return Diag(Loc, diag::err_address_space_qualified_new)
1580       << AllocType.getUnqualifiedType() << AddressSpace;
1581   else if (getLangOpts().ObjCAutoRefCount) {
1582     if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1583       QualType BaseAllocType = Context.getBaseElementType(AT);
1584       if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1585           BaseAllocType->isObjCLifetimeType())
1586         return Diag(Loc, diag::err_arc_new_array_without_ownership)
1587           << BaseAllocType;
1588     }
1589   }
1590 
1591   return false;
1592 }
1593 
1594 /// \brief Determine whether the given function is a non-placement
1595 /// deallocation function.
isNonPlacementDeallocationFunction(Sema & S,FunctionDecl * FD)1596 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1597   if (FD->isInvalidDecl())
1598     return false;
1599 
1600   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1601     return Method->isUsualDeallocationFunction();
1602 
1603   if (FD->getOverloadedOperator() != OO_Delete &&
1604       FD->getOverloadedOperator() != OO_Array_Delete)
1605     return false;
1606 
1607   if (FD->getNumParams() == 1)
1608     return true;
1609 
1610   return S.getLangOpts().SizedDeallocation && FD->getNumParams() == 2 &&
1611          S.Context.hasSameUnqualifiedType(FD->getParamDecl(1)->getType(),
1612                                           S.Context.getSizeType());
1613 }
1614 
1615 /// FindAllocationFunctions - Finds the overloads of operator new and delete
1616 /// that are appropriate for the allocation.
FindAllocationFunctions(SourceLocation StartLoc,SourceRange Range,bool UseGlobal,QualType AllocType,bool IsArray,MultiExprArg PlaceArgs,FunctionDecl * & OperatorNew,FunctionDecl * & OperatorDelete)1617 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1618                                    bool UseGlobal, QualType AllocType,
1619                                    bool IsArray, MultiExprArg PlaceArgs,
1620                                    FunctionDecl *&OperatorNew,
1621                                    FunctionDecl *&OperatorDelete) {
1622   // --- Choosing an allocation function ---
1623   // C++ 5.3.4p8 - 14 & 18
1624   // 1) If UseGlobal is true, only look in the global scope. Else, also look
1625   //   in the scope of the allocated class.
1626   // 2) If an array size is given, look for operator new[], else look for
1627   //   operator new.
1628   // 3) The first argument is always size_t. Append the arguments from the
1629   //   placement form.
1630 
1631   SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size());
1632   // We don't care about the actual value of this argument.
1633   // FIXME: Should the Sema create the expression and embed it in the syntax
1634   // tree? Or should the consumer just recalculate the value?
1635   IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1636                       Context.getTargetInfo().getPointerWidth(0)),
1637                       Context.getSizeType(),
1638                       SourceLocation());
1639   AllocArgs[0] = &Size;
1640   std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1);
1641 
1642   // C++ [expr.new]p8:
1643   //   If the allocated type is a non-array type, the allocation
1644   //   function's name is operator new and the deallocation function's
1645   //   name is operator delete. If the allocated type is an array
1646   //   type, the allocation function's name is operator new[] and the
1647   //   deallocation function's name is operator delete[].
1648   DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1649                                         IsArray ? OO_Array_New : OO_New);
1650   DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1651                                         IsArray ? OO_Array_Delete : OO_Delete);
1652 
1653   QualType AllocElemType = Context.getBaseElementType(AllocType);
1654 
1655   if (AllocElemType->isRecordType() && !UseGlobal) {
1656     CXXRecordDecl *Record
1657       = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1658     if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record,
1659                                /*AllowMissing=*/true, OperatorNew))
1660       return true;
1661   }
1662 
1663   if (!OperatorNew) {
1664     // Didn't find a member overload. Look for a global one.
1665     DeclareGlobalNewDelete();
1666     DeclContext *TUDecl = Context.getTranslationUnitDecl();
1667     bool FallbackEnabled = IsArray && Context.getLangOpts().MSVCCompat;
1668     if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
1669                                /*AllowMissing=*/FallbackEnabled, OperatorNew,
1670                                /*Diagnose=*/!FallbackEnabled)) {
1671       if (!FallbackEnabled)
1672         return true;
1673 
1674       // MSVC will fall back on trying to find a matching global operator new
1675       // if operator new[] cannot be found.  Also, MSVC will leak by not
1676       // generating a call to operator delete or operator delete[], but we
1677       // will not replicate that bug.
1678       NewName = Context.DeclarationNames.getCXXOperatorName(OO_New);
1679       DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
1680       if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
1681                                /*AllowMissing=*/false, OperatorNew))
1682       return true;
1683     }
1684   }
1685 
1686   // We don't need an operator delete if we're running under
1687   // -fno-exceptions.
1688   if (!getLangOpts().Exceptions) {
1689     OperatorDelete = nullptr;
1690     return false;
1691   }
1692 
1693   // C++ [expr.new]p19:
1694   //
1695   //   If the new-expression begins with a unary :: operator, the
1696   //   deallocation function's name is looked up in the global
1697   //   scope. Otherwise, if the allocated type is a class type T or an
1698   //   array thereof, the deallocation function's name is looked up in
1699   //   the scope of T. If this lookup fails to find the name, or if
1700   //   the allocated type is not a class type or array thereof, the
1701   //   deallocation function's name is looked up in the global scope.
1702   LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1703   if (AllocElemType->isRecordType() && !UseGlobal) {
1704     CXXRecordDecl *RD
1705       = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1706     LookupQualifiedName(FoundDelete, RD);
1707   }
1708   if (FoundDelete.isAmbiguous())
1709     return true; // FIXME: clean up expressions?
1710 
1711   if (FoundDelete.empty()) {
1712     DeclareGlobalNewDelete();
1713     LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1714   }
1715 
1716   FoundDelete.suppressDiagnostics();
1717 
1718   SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1719 
1720   // Whether we're looking for a placement operator delete is dictated
1721   // by whether we selected a placement operator new, not by whether
1722   // we had explicit placement arguments.  This matters for things like
1723   //   struct A { void *operator new(size_t, int = 0); ... };
1724   //   A *a = new A()
1725   bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1);
1726 
1727   if (isPlacementNew) {
1728     // C++ [expr.new]p20:
1729     //   A declaration of a placement deallocation function matches the
1730     //   declaration of a placement allocation function if it has the
1731     //   same number of parameters and, after parameter transformations
1732     //   (8.3.5), all parameter types except the first are
1733     //   identical. [...]
1734     //
1735     // To perform this comparison, we compute the function type that
1736     // the deallocation function should have, and use that type both
1737     // for template argument deduction and for comparison purposes.
1738     //
1739     // FIXME: this comparison should ignore CC and the like.
1740     QualType ExpectedFunctionType;
1741     {
1742       const FunctionProtoType *Proto
1743         = OperatorNew->getType()->getAs<FunctionProtoType>();
1744 
1745       SmallVector<QualType, 4> ArgTypes;
1746       ArgTypes.push_back(Context.VoidPtrTy);
1747       for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
1748         ArgTypes.push_back(Proto->getParamType(I));
1749 
1750       FunctionProtoType::ExtProtoInfo EPI;
1751       EPI.Variadic = Proto->isVariadic();
1752 
1753       ExpectedFunctionType
1754         = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
1755     }
1756 
1757     for (LookupResult::iterator D = FoundDelete.begin(),
1758                              DEnd = FoundDelete.end();
1759          D != DEnd; ++D) {
1760       FunctionDecl *Fn = nullptr;
1761       if (FunctionTemplateDecl *FnTmpl
1762             = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1763         // Perform template argument deduction to try to match the
1764         // expected function type.
1765         TemplateDeductionInfo Info(StartLoc);
1766         if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
1767                                     Info))
1768           continue;
1769       } else
1770         Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1771 
1772       if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1773         Matches.push_back(std::make_pair(D.getPair(), Fn));
1774     }
1775   } else {
1776     // C++ [expr.new]p20:
1777     //   [...] Any non-placement deallocation function matches a
1778     //   non-placement allocation function. [...]
1779     for (LookupResult::iterator D = FoundDelete.begin(),
1780                              DEnd = FoundDelete.end();
1781          D != DEnd; ++D) {
1782       if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1783         if (isNonPlacementDeallocationFunction(*this, Fn))
1784           Matches.push_back(std::make_pair(D.getPair(), Fn));
1785     }
1786 
1787     // C++1y [expr.new]p22:
1788     //   For a non-placement allocation function, the normal deallocation
1789     //   function lookup is used
1790     // C++1y [expr.delete]p?:
1791     //   If [...] deallocation function lookup finds both a usual deallocation
1792     //   function with only a pointer parameter and a usual deallocation
1793     //   function with both a pointer parameter and a size parameter, then the
1794     //   selected deallocation function shall be the one with two parameters.
1795     //   Otherwise, the selected deallocation function shall be the function
1796     //   with one parameter.
1797     if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
1798       if (Matches[0].second->getNumParams() == 1)
1799         Matches.erase(Matches.begin());
1800       else
1801         Matches.erase(Matches.begin() + 1);
1802       assert(Matches[0].second->getNumParams() == 2 &&
1803              "found an unexpected usual deallocation function");
1804     }
1805   }
1806 
1807   // C++ [expr.new]p20:
1808   //   [...] If the lookup finds a single matching deallocation
1809   //   function, that function will be called; otherwise, no
1810   //   deallocation function will be called.
1811   if (Matches.size() == 1) {
1812     OperatorDelete = Matches[0].second;
1813 
1814     // C++0x [expr.new]p20:
1815     //   If the lookup finds the two-parameter form of a usual
1816     //   deallocation function (3.7.4.2) and that function, considered
1817     //   as a placement deallocation function, would have been
1818     //   selected as a match for the allocation function, the program
1819     //   is ill-formed.
1820     if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 &&
1821         isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
1822       Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1823         << SourceRange(PlaceArgs.front()->getLocStart(),
1824                        PlaceArgs.back()->getLocEnd());
1825       if (!OperatorDelete->isImplicit())
1826         Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1827           << DeleteName;
1828     } else {
1829       CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1830                             Matches[0].first);
1831     }
1832   }
1833 
1834   return false;
1835 }
1836 
1837 /// \brief Find an fitting overload for the allocation function
1838 /// in the specified scope.
1839 ///
1840 /// \param StartLoc The location of the 'new' token.
1841 /// \param Range The range of the placement arguments.
1842 /// \param Name The name of the function ('operator new' or 'operator new[]').
1843 /// \param Args The placement arguments specified.
1844 /// \param Ctx The scope in which we should search; either a class scope or the
1845 ///        translation unit.
1846 /// \param AllowMissing If \c true, report an error if we can't find any
1847 ///        allocation functions. Otherwise, succeed but don't fill in \p
1848 ///        Operator.
1849 /// \param Operator Filled in with the found allocation function. Unchanged if
1850 ///        no allocation function was found.
1851 /// \param Diagnose If \c true, issue errors if the allocation function is not
1852 ///        usable.
FindAllocationOverload(SourceLocation StartLoc,SourceRange Range,DeclarationName Name,MultiExprArg Args,DeclContext * Ctx,bool AllowMissing,FunctionDecl * & Operator,bool Diagnose)1853 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1854                                   DeclarationName Name, MultiExprArg Args,
1855                                   DeclContext *Ctx,
1856                                   bool AllowMissing, FunctionDecl *&Operator,
1857                                   bool Diagnose) {
1858   LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1859   LookupQualifiedName(R, Ctx);
1860   if (R.empty()) {
1861     if (AllowMissing || !Diagnose)
1862       return false;
1863     return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1864       << Name << Range;
1865   }
1866 
1867   if (R.isAmbiguous())
1868     return true;
1869 
1870   R.suppressDiagnostics();
1871 
1872   OverloadCandidateSet Candidates(StartLoc, OverloadCandidateSet::CSK_Normal);
1873   for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1874        Alloc != AllocEnd; ++Alloc) {
1875     // Even member operator new/delete are implicitly treated as
1876     // static, so don't use AddMemberCandidate.
1877     NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1878 
1879     if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1880       AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1881                                    /*ExplicitTemplateArgs=*/nullptr,
1882                                    Args, Candidates,
1883                                    /*SuppressUserConversions=*/false);
1884       continue;
1885     }
1886 
1887     FunctionDecl *Fn = cast<FunctionDecl>(D);
1888     AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
1889                          /*SuppressUserConversions=*/false);
1890   }
1891 
1892   // Do the resolution.
1893   OverloadCandidateSet::iterator Best;
1894   switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1895   case OR_Success: {
1896     // Got one!
1897     FunctionDecl *FnDecl = Best->Function;
1898     if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1899                               Best->FoundDecl, Diagnose) == AR_inaccessible)
1900       return true;
1901 
1902     Operator = FnDecl;
1903     return false;
1904   }
1905 
1906   case OR_No_Viable_Function:
1907     if (Diagnose) {
1908       Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1909         << Name << Range;
1910       Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
1911     }
1912     return true;
1913 
1914   case OR_Ambiguous:
1915     if (Diagnose) {
1916       Diag(StartLoc, diag::err_ovl_ambiguous_call)
1917         << Name << Range;
1918       Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args);
1919     }
1920     return true;
1921 
1922   case OR_Deleted: {
1923     if (Diagnose) {
1924       Diag(StartLoc, diag::err_ovl_deleted_call)
1925         << Best->Function->isDeleted()
1926         << Name
1927         << getDeletedOrUnavailableSuffix(Best->Function)
1928         << Range;
1929       Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
1930     }
1931     return true;
1932   }
1933   }
1934   llvm_unreachable("Unreachable, bad result from BestViableFunction");
1935 }
1936 
1937 
1938 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
1939 /// delete. These are:
1940 /// @code
1941 ///   // C++03:
1942 ///   void* operator new(std::size_t) throw(std::bad_alloc);
1943 ///   void* operator new[](std::size_t) throw(std::bad_alloc);
1944 ///   void operator delete(void *) throw();
1945 ///   void operator delete[](void *) throw();
1946 ///   // C++11:
1947 ///   void* operator new(std::size_t);
1948 ///   void* operator new[](std::size_t);
1949 ///   void operator delete(void *) noexcept;
1950 ///   void operator delete[](void *) noexcept;
1951 ///   // C++1y:
1952 ///   void* operator new(std::size_t);
1953 ///   void* operator new[](std::size_t);
1954 ///   void operator delete(void *) noexcept;
1955 ///   void operator delete[](void *) noexcept;
1956 ///   void operator delete(void *, std::size_t) noexcept;
1957 ///   void operator delete[](void *, std::size_t) noexcept;
1958 /// @endcode
1959 /// Note that the placement and nothrow forms of new are *not* implicitly
1960 /// declared. Their use requires including \<new\>.
DeclareGlobalNewDelete()1961 void Sema::DeclareGlobalNewDelete() {
1962   if (GlobalNewDeleteDeclared)
1963     return;
1964 
1965   // C++ [basic.std.dynamic]p2:
1966   //   [...] The following allocation and deallocation functions (18.4) are
1967   //   implicitly declared in global scope in each translation unit of a
1968   //   program
1969   //
1970   //     C++03:
1971   //     void* operator new(std::size_t) throw(std::bad_alloc);
1972   //     void* operator new[](std::size_t) throw(std::bad_alloc);
1973   //     void  operator delete(void*) throw();
1974   //     void  operator delete[](void*) throw();
1975   //     C++11:
1976   //     void* operator new(std::size_t);
1977   //     void* operator new[](std::size_t);
1978   //     void  operator delete(void*) noexcept;
1979   //     void  operator delete[](void*) noexcept;
1980   //     C++1y:
1981   //     void* operator new(std::size_t);
1982   //     void* operator new[](std::size_t);
1983   //     void  operator delete(void*) noexcept;
1984   //     void  operator delete[](void*) noexcept;
1985   //     void  operator delete(void*, std::size_t) noexcept;
1986   //     void  operator delete[](void*, std::size_t) noexcept;
1987   //
1988   //   These implicit declarations introduce only the function names operator
1989   //   new, operator new[], operator delete, operator delete[].
1990   //
1991   // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1992   // "std" or "bad_alloc" as necessary to form the exception specification.
1993   // However, we do not make these implicit declarations visible to name
1994   // lookup.
1995   if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
1996     // The "std::bad_alloc" class has not yet been declared, so build it
1997     // implicitly.
1998     StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1999                                         getOrCreateStdNamespace(),
2000                                         SourceLocation(), SourceLocation(),
2001                                       &PP.getIdentifierTable().get("bad_alloc"),
2002                                         nullptr);
2003     getStdBadAlloc()->setImplicit(true);
2004   }
2005 
2006   GlobalNewDeleteDeclared = true;
2007 
2008   QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2009   QualType SizeT = Context.getSizeType();
2010   bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
2011 
2012   DeclareGlobalAllocationFunction(
2013       Context.DeclarationNames.getCXXOperatorName(OO_New),
2014       VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
2015   DeclareGlobalAllocationFunction(
2016       Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
2017       VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
2018   DeclareGlobalAllocationFunction(
2019       Context.DeclarationNames.getCXXOperatorName(OO_Delete),
2020       Context.VoidTy, VoidPtr);
2021   DeclareGlobalAllocationFunction(
2022       Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2023       Context.VoidTy, VoidPtr);
2024   if (getLangOpts().SizedDeallocation) {
2025     DeclareGlobalAllocationFunction(
2026         Context.DeclarationNames.getCXXOperatorName(OO_Delete),
2027         Context.VoidTy, VoidPtr, Context.getSizeType());
2028     DeclareGlobalAllocationFunction(
2029         Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2030         Context.VoidTy, VoidPtr, Context.getSizeType());
2031   }
2032 }
2033 
2034 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2035 /// allocation function if it doesn't already exist.
DeclareGlobalAllocationFunction(DeclarationName Name,QualType Return,QualType Param1,QualType Param2,bool AddMallocAttr)2036 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2037                                            QualType Return,
2038                                            QualType Param1, QualType Param2,
2039                                            bool AddMallocAttr) {
2040   DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2041   unsigned NumParams = Param2.isNull() ? 1 : 2;
2042 
2043   // Check if this function is already declared.
2044   DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2045   for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2046        Alloc != AllocEnd; ++Alloc) {
2047     // Only look at non-template functions, as it is the predefined,
2048     // non-templated allocation function we are trying to declare here.
2049     if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2050       if (Func->getNumParams() == NumParams) {
2051         QualType InitialParam1Type =
2052             Context.getCanonicalType(Func->getParamDecl(0)
2053                                          ->getType().getUnqualifiedType());
2054         QualType InitialParam2Type =
2055             NumParams == 2
2056                 ? Context.getCanonicalType(Func->getParamDecl(1)
2057                                                ->getType().getUnqualifiedType())
2058                 : QualType();
2059         // FIXME: Do we need to check for default arguments here?
2060         if (InitialParam1Type == Param1 &&
2061             (NumParams == 1 || InitialParam2Type == Param2)) {
2062           if (AddMallocAttr && !Func->hasAttr<MallocAttr>())
2063             Func->addAttr(MallocAttr::CreateImplicit(Context));
2064           // Make the function visible to name lookup, even if we found it in
2065           // an unimported module. It either is an implicitly-declared global
2066           // allocation function, or is suppressing that function.
2067           Func->setHidden(false);
2068           return;
2069         }
2070       }
2071     }
2072   }
2073 
2074   FunctionProtoType::ExtProtoInfo EPI;
2075 
2076   QualType BadAllocType;
2077   bool HasBadAllocExceptionSpec
2078     = (Name.getCXXOverloadedOperator() == OO_New ||
2079        Name.getCXXOverloadedOperator() == OO_Array_New);
2080   if (HasBadAllocExceptionSpec) {
2081     if (!getLangOpts().CPlusPlus11) {
2082       BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2083       assert(StdBadAlloc && "Must have std::bad_alloc declared");
2084       EPI.ExceptionSpecType = EST_Dynamic;
2085       EPI.NumExceptions = 1;
2086       EPI.Exceptions = &BadAllocType;
2087     }
2088   } else {
2089     EPI.ExceptionSpecType = getLangOpts().CPlusPlus11 ?
2090                                 EST_BasicNoexcept : EST_DynamicNone;
2091   }
2092 
2093   QualType Params[] = { Param1, Param2 };
2094 
2095   QualType FnType = Context.getFunctionType(
2096       Return, ArrayRef<QualType>(Params, NumParams), EPI);
2097   FunctionDecl *Alloc =
2098     FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
2099                          SourceLocation(), Name,
2100                          FnType, /*TInfo=*/nullptr, SC_None, false, true);
2101   Alloc->setImplicit();
2102 
2103   if (AddMallocAttr)
2104     Alloc->addAttr(MallocAttr::CreateImplicit(Context));
2105 
2106   ParmVarDecl *ParamDecls[2];
2107   for (unsigned I = 0; I != NumParams; ++I) {
2108     ParamDecls[I] = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
2109                                         SourceLocation(), nullptr,
2110                                         Params[I], /*TInfo=*/nullptr,
2111                                         SC_None, nullptr);
2112     ParamDecls[I]->setImplicit();
2113   }
2114   Alloc->setParams(ArrayRef<ParmVarDecl*>(ParamDecls, NumParams));
2115 
2116   Context.getTranslationUnitDecl()->addDecl(Alloc);
2117   IdResolver.tryAddTopLevelDecl(Alloc, Name);
2118 }
2119 
FindUsualDeallocationFunction(SourceLocation StartLoc,bool CanProvideSize,DeclarationName Name)2120 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2121                                                   bool CanProvideSize,
2122                                                   DeclarationName Name) {
2123   DeclareGlobalNewDelete();
2124 
2125   LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2126   LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2127 
2128   // C++ [expr.new]p20:
2129   //   [...] Any non-placement deallocation function matches a
2130   //   non-placement allocation function. [...]
2131   llvm::SmallVector<FunctionDecl*, 2> Matches;
2132   for (LookupResult::iterator D = FoundDelete.begin(),
2133                            DEnd = FoundDelete.end();
2134        D != DEnd; ++D) {
2135     if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*D))
2136       if (isNonPlacementDeallocationFunction(*this, Fn))
2137         Matches.push_back(Fn);
2138   }
2139 
2140   // C++1y [expr.delete]p?:
2141   //   If the type is complete and deallocation function lookup finds both a
2142   //   usual deallocation function with only a pointer parameter and a usual
2143   //   deallocation function with both a pointer parameter and a size
2144   //   parameter, then the selected deallocation function shall be the one
2145   //   with two parameters.  Otherwise, the selected deallocation function
2146   //   shall be the function with one parameter.
2147   if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
2148     unsigned NumArgs = CanProvideSize ? 2 : 1;
2149     if (Matches[0]->getNumParams() != NumArgs)
2150       Matches.erase(Matches.begin());
2151     else
2152       Matches.erase(Matches.begin() + 1);
2153     assert(Matches[0]->getNumParams() == NumArgs &&
2154            "found an unexpected usual deallocation function");
2155   }
2156 
2157   assert(Matches.size() == 1 &&
2158          "unexpectedly have multiple usual deallocation functions");
2159   return Matches.front();
2160 }
2161 
FindDeallocationFunction(SourceLocation StartLoc,CXXRecordDecl * RD,DeclarationName Name,FunctionDecl * & Operator,bool Diagnose)2162 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2163                                     DeclarationName Name,
2164                                     FunctionDecl* &Operator, bool Diagnose) {
2165   LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2166   // Try to find operator delete/operator delete[] in class scope.
2167   LookupQualifiedName(Found, RD);
2168 
2169   if (Found.isAmbiguous())
2170     return true;
2171 
2172   Found.suppressDiagnostics();
2173 
2174   SmallVector<DeclAccessPair,4> Matches;
2175   for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2176        F != FEnd; ++F) {
2177     NamedDecl *ND = (*F)->getUnderlyingDecl();
2178 
2179     // Ignore template operator delete members from the check for a usual
2180     // deallocation function.
2181     if (isa<FunctionTemplateDecl>(ND))
2182       continue;
2183 
2184     if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
2185       Matches.push_back(F.getPair());
2186   }
2187 
2188   // There's exactly one suitable operator;  pick it.
2189   if (Matches.size() == 1) {
2190     Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
2191 
2192     if (Operator->isDeleted()) {
2193       if (Diagnose) {
2194         Diag(StartLoc, diag::err_deleted_function_use);
2195         NoteDeletedFunction(Operator);
2196       }
2197       return true;
2198     }
2199 
2200     if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2201                               Matches[0], Diagnose) == AR_inaccessible)
2202       return true;
2203 
2204     return false;
2205 
2206   // We found multiple suitable operators;  complain about the ambiguity.
2207   } else if (!Matches.empty()) {
2208     if (Diagnose) {
2209       Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2210         << Name << RD;
2211 
2212       for (SmallVectorImpl<DeclAccessPair>::iterator
2213              F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
2214         Diag((*F)->getUnderlyingDecl()->getLocation(),
2215              diag::note_member_declared_here) << Name;
2216     }
2217     return true;
2218   }
2219 
2220   // We did find operator delete/operator delete[] declarations, but
2221   // none of them were suitable.
2222   if (!Found.empty()) {
2223     if (Diagnose) {
2224       Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2225         << Name << RD;
2226 
2227       for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2228            F != FEnd; ++F)
2229         Diag((*F)->getUnderlyingDecl()->getLocation(),
2230              diag::note_member_declared_here) << Name;
2231     }
2232     return true;
2233   }
2234 
2235   Operator = nullptr;
2236   return false;
2237 }
2238 
2239 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2240 /// @code ::delete ptr; @endcode
2241 /// or
2242 /// @code delete [] ptr; @endcode
2243 ExprResult
ActOnCXXDelete(SourceLocation StartLoc,bool UseGlobal,bool ArrayForm,Expr * ExE)2244 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
2245                      bool ArrayForm, Expr *ExE) {
2246   // C++ [expr.delete]p1:
2247   //   The operand shall have a pointer type, or a class type having a single
2248   //   non-explicit conversion function to a pointer type. The result has type
2249   //   void.
2250   //
2251   // DR599 amends "pointer type" to "pointer to object type" in both cases.
2252 
2253   ExprResult Ex = ExE;
2254   FunctionDecl *OperatorDelete = nullptr;
2255   bool ArrayFormAsWritten = ArrayForm;
2256   bool UsualArrayDeleteWantsSize = false;
2257 
2258   if (!Ex.get()->isTypeDependent()) {
2259     // Perform lvalue-to-rvalue cast, if needed.
2260     Ex = DefaultLvalueConversion(Ex.get());
2261     if (Ex.isInvalid())
2262       return ExprError();
2263 
2264     QualType Type = Ex.get()->getType();
2265 
2266     class DeleteConverter : public ContextualImplicitConverter {
2267     public:
2268       DeleteConverter() : ContextualImplicitConverter(false, true) {}
2269 
2270       bool match(QualType ConvType) override {
2271         // FIXME: If we have an operator T* and an operator void*, we must pick
2272         // the operator T*.
2273         if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
2274           if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
2275             return true;
2276         return false;
2277       }
2278 
2279       SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2280                                             QualType T) override {
2281         return S.Diag(Loc, diag::err_delete_operand) << T;
2282       }
2283 
2284       SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2285                                                QualType T) override {
2286         return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
2287       }
2288 
2289       SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2290                                                  QualType T,
2291                                                  QualType ConvTy) override {
2292         return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
2293       }
2294 
2295       SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2296                                              QualType ConvTy) override {
2297         return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2298           << ConvTy;
2299       }
2300 
2301       SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2302                                               QualType T) override {
2303         return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
2304       }
2305 
2306       SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2307                                           QualType ConvTy) override {
2308         return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2309           << ConvTy;
2310       }
2311 
2312       SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2313                                                QualType T,
2314                                                QualType ConvTy) override {
2315         llvm_unreachable("conversion functions are permitted");
2316       }
2317     } Converter;
2318 
2319     Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
2320     if (Ex.isInvalid())
2321       return ExprError();
2322     Type = Ex.get()->getType();
2323     if (!Converter.match(Type))
2324       // FIXME: PerformContextualImplicitConversion should return ExprError
2325       //        itself in this case.
2326       return ExprError();
2327 
2328     QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
2329     QualType PointeeElem = Context.getBaseElementType(Pointee);
2330 
2331     if (unsigned AddressSpace = Pointee.getAddressSpace())
2332       return Diag(Ex.get()->getLocStart(),
2333                   diag::err_address_space_qualified_delete)
2334                << Pointee.getUnqualifiedType() << AddressSpace;
2335 
2336     CXXRecordDecl *PointeeRD = nullptr;
2337     if (Pointee->isVoidType() && !isSFINAEContext()) {
2338       // The C++ standard bans deleting a pointer to a non-object type, which
2339       // effectively bans deletion of "void*". However, most compilers support
2340       // this, so we treat it as a warning unless we're in a SFINAE context.
2341       Diag(StartLoc, diag::ext_delete_void_ptr_operand)
2342         << Type << Ex.get()->getSourceRange();
2343     } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
2344       return ExprError(Diag(StartLoc, diag::err_delete_operand)
2345         << Type << Ex.get()->getSourceRange());
2346     } else if (!Pointee->isDependentType()) {
2347       if (!RequireCompleteType(StartLoc, Pointee,
2348                                diag::warn_delete_incomplete, Ex.get())) {
2349         if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2350           PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2351       }
2352     }
2353 
2354     // C++ [expr.delete]p2:
2355     //   [Note: a pointer to a const type can be the operand of a
2356     //   delete-expression; it is not necessary to cast away the constness
2357     //   (5.2.11) of the pointer expression before it is used as the operand
2358     //   of the delete-expression. ]
2359 
2360     if (Pointee->isArrayType() && !ArrayForm) {
2361       Diag(StartLoc, diag::warn_delete_array_type)
2362           << Type << Ex.get()->getSourceRange()
2363           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2364       ArrayForm = true;
2365     }
2366 
2367     DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2368                                       ArrayForm ? OO_Array_Delete : OO_Delete);
2369 
2370     if (PointeeRD) {
2371       if (!UseGlobal &&
2372           FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2373                                    OperatorDelete))
2374         return ExprError();
2375 
2376       // If we're allocating an array of records, check whether the
2377       // usual operator delete[] has a size_t parameter.
2378       if (ArrayForm) {
2379         // If the user specifically asked to use the global allocator,
2380         // we'll need to do the lookup into the class.
2381         if (UseGlobal)
2382           UsualArrayDeleteWantsSize =
2383             doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2384 
2385         // Otherwise, the usual operator delete[] should be the
2386         // function we just found.
2387         else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
2388           UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2389       }
2390 
2391       if (!PointeeRD->hasIrrelevantDestructor())
2392         if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2393           MarkFunctionReferenced(StartLoc,
2394                                     const_cast<CXXDestructorDecl*>(Dtor));
2395           if (DiagnoseUseOfDecl(Dtor, StartLoc))
2396             return ExprError();
2397         }
2398 
2399       // C++ [expr.delete]p3:
2400       //   In the first alternative (delete object), if the static type of the
2401       //   object to be deleted is different from its dynamic type, the static
2402       //   type shall be a base class of the dynamic type of the object to be
2403       //   deleted and the static type shall have a virtual destructor or the
2404       //   behavior is undefined.
2405       //
2406       // Note: a final class cannot be derived from, no issue there
2407       if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
2408         CXXDestructorDecl *dtor = PointeeRD->getDestructor();
2409         if (dtor && !dtor->isVirtual()) {
2410           if (PointeeRD->isAbstract()) {
2411             // If the class is abstract, we warn by default, because we're
2412             // sure the code has undefined behavior.
2413             Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2414                 << PointeeElem;
2415           } else if (!ArrayForm) {
2416             // Otherwise, if this is not an array delete, it's a bit suspect,
2417             // but not necessarily wrong.
2418             Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2419           }
2420         }
2421       }
2422 
2423     }
2424 
2425     if (!OperatorDelete)
2426       // Look for a global declaration.
2427       OperatorDelete = FindUsualDeallocationFunction(
2428           StartLoc, !RequireCompleteType(StartLoc, Pointee, 0) &&
2429                     (!ArrayForm || UsualArrayDeleteWantsSize ||
2430                      Pointee.isDestructedType()),
2431           DeleteName);
2432 
2433     MarkFunctionReferenced(StartLoc, OperatorDelete);
2434 
2435     // Check access and ambiguity of operator delete and destructor.
2436     if (PointeeRD) {
2437       if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2438           CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
2439                       PDiag(diag::err_access_dtor) << PointeeElem);
2440       }
2441     }
2442   }
2443 
2444   return new (Context) CXXDeleteExpr(
2445       Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
2446       UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
2447 }
2448 
2449 /// \brief Check the use of the given variable as a C++ condition in an if,
2450 /// while, do-while, or switch statement.
CheckConditionVariable(VarDecl * ConditionVar,SourceLocation StmtLoc,bool ConvertToBoolean)2451 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
2452                                         SourceLocation StmtLoc,
2453                                         bool ConvertToBoolean) {
2454   if (ConditionVar->isInvalidDecl())
2455     return ExprError();
2456 
2457   QualType T = ConditionVar->getType();
2458 
2459   // C++ [stmt.select]p2:
2460   //   The declarator shall not specify a function or an array.
2461   if (T->isFunctionType())
2462     return ExprError(Diag(ConditionVar->getLocation(),
2463                           diag::err_invalid_use_of_function_type)
2464                        << ConditionVar->getSourceRange());
2465   else if (T->isArrayType())
2466     return ExprError(Diag(ConditionVar->getLocation(),
2467                           diag::err_invalid_use_of_array_type)
2468                      << ConditionVar->getSourceRange());
2469 
2470   ExprResult Condition = DeclRefExpr::Create(
2471       Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
2472       /*enclosing*/ false, ConditionVar->getLocation(),
2473       ConditionVar->getType().getNonReferenceType(), VK_LValue);
2474 
2475   MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
2476 
2477   if (ConvertToBoolean) {
2478     Condition = CheckBooleanCondition(Condition.get(), StmtLoc);
2479     if (Condition.isInvalid())
2480       return ExprError();
2481   }
2482 
2483   return Condition;
2484 }
2485 
2486 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
CheckCXXBooleanCondition(Expr * CondExpr)2487 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
2488   // C++ 6.4p4:
2489   // The value of a condition that is an initialized declaration in a statement
2490   // other than a switch statement is the value of the declared variable
2491   // implicitly converted to type bool. If that conversion is ill-formed, the
2492   // program is ill-formed.
2493   // The value of a condition that is an expression is the value of the
2494   // expression, implicitly converted to bool.
2495   //
2496   return PerformContextuallyConvertToBool(CondExpr);
2497 }
2498 
2499 /// Helper function to determine whether this is the (deprecated) C++
2500 /// conversion from a string literal to a pointer to non-const char or
2501 /// non-const wchar_t (for narrow and wide string literals,
2502 /// respectively).
2503 bool
IsStringLiteralToNonConstPointerConversion(Expr * From,QualType ToType)2504 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2505   // Look inside the implicit cast, if it exists.
2506   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2507     From = Cast->getSubExpr();
2508 
2509   // A string literal (2.13.4) that is not a wide string literal can
2510   // be converted to an rvalue of type "pointer to char"; a wide
2511   // string literal can be converted to an rvalue of type "pointer
2512   // to wchar_t" (C++ 4.2p2).
2513   if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
2514     if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
2515       if (const BuiltinType *ToPointeeType
2516           = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
2517         // This conversion is considered only when there is an
2518         // explicit appropriate pointer target type (C++ 4.2p2).
2519         if (!ToPtrType->getPointeeType().hasQualifiers()) {
2520           switch (StrLit->getKind()) {
2521             case StringLiteral::UTF8:
2522             case StringLiteral::UTF16:
2523             case StringLiteral::UTF32:
2524               // We don't allow UTF literals to be implicitly converted
2525               break;
2526             case StringLiteral::Ascii:
2527               return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2528                       ToPointeeType->getKind() == BuiltinType::Char_S);
2529             case StringLiteral::Wide:
2530               return ToPointeeType->isWideCharType();
2531           }
2532         }
2533       }
2534 
2535   return false;
2536 }
2537 
BuildCXXCastArgument(Sema & S,SourceLocation CastLoc,QualType Ty,CastKind Kind,CXXMethodDecl * Method,DeclAccessPair FoundDecl,bool HadMultipleCandidates,Expr * From)2538 static ExprResult BuildCXXCastArgument(Sema &S,
2539                                        SourceLocation CastLoc,
2540                                        QualType Ty,
2541                                        CastKind Kind,
2542                                        CXXMethodDecl *Method,
2543                                        DeclAccessPair FoundDecl,
2544                                        bool HadMultipleCandidates,
2545                                        Expr *From) {
2546   switch (Kind) {
2547   default: llvm_unreachable("Unhandled cast kind!");
2548   case CK_ConstructorConversion: {
2549     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
2550     SmallVector<Expr*, 8> ConstructorArgs;
2551 
2552     if (S.RequireNonAbstractType(CastLoc, Ty,
2553                                  diag::err_allocation_of_abstract_type))
2554       return ExprError();
2555 
2556     if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
2557       return ExprError();
2558 
2559     S.CheckConstructorAccess(CastLoc, Constructor,
2560                              InitializedEntity::InitializeTemporary(Ty),
2561                              Constructor->getAccess());
2562 
2563     ExprResult Result
2564       = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2565                                 ConstructorArgs, HadMultipleCandidates,
2566                                 /*ListInit*/ false, /*ZeroInit*/ false,
2567                                 CXXConstructExpr::CK_Complete, SourceRange());
2568     if (Result.isInvalid())
2569       return ExprError();
2570 
2571     return S.MaybeBindToTemporary(Result.getAs<Expr>());
2572   }
2573 
2574   case CK_UserDefinedConversion: {
2575     assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2576 
2577     // Create an implicit call expr that calls it.
2578     CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2579     ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
2580                                                  HadMultipleCandidates);
2581     if (Result.isInvalid())
2582       return ExprError();
2583     // Record usage of conversion in an implicit cast.
2584     Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
2585                                       CK_UserDefinedConversion, Result.get(),
2586                                       nullptr, Result.get()->getValueKind());
2587 
2588     S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
2589 
2590     return S.MaybeBindToTemporary(Result.get());
2591   }
2592   }
2593 }
2594 
2595 /// PerformImplicitConversion - Perform an implicit conversion of the
2596 /// expression From to the type ToType using the pre-computed implicit
2597 /// conversion sequence ICS. Returns the converted
2598 /// expression. Action is the kind of conversion we're performing,
2599 /// used in the error message.
2600 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,const ImplicitConversionSequence & ICS,AssignmentAction Action,CheckedConversionKind CCK)2601 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2602                                 const ImplicitConversionSequence &ICS,
2603                                 AssignmentAction Action,
2604                                 CheckedConversionKind CCK) {
2605   switch (ICS.getKind()) {
2606   case ImplicitConversionSequence::StandardConversion: {
2607     ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2608                                                Action, CCK);
2609     if (Res.isInvalid())
2610       return ExprError();
2611     From = Res.get();
2612     break;
2613   }
2614 
2615   case ImplicitConversionSequence::UserDefinedConversion: {
2616 
2617       FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
2618       CastKind CastKind;
2619       QualType BeforeToType;
2620       assert(FD && "FIXME: aggregate initialization from init list");
2621       if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
2622         CastKind = CK_UserDefinedConversion;
2623 
2624         // If the user-defined conversion is specified by a conversion function,
2625         // the initial standard conversion sequence converts the source type to
2626         // the implicit object parameter of the conversion function.
2627         BeforeToType = Context.getTagDeclType(Conv->getParent());
2628       } else {
2629         const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
2630         CastKind = CK_ConstructorConversion;
2631         // Do no conversion if dealing with ... for the first conversion.
2632         if (!ICS.UserDefined.EllipsisConversion) {
2633           // If the user-defined conversion is specified by a constructor, the
2634           // initial standard conversion sequence converts the source type to the
2635           // type required by the argument of the constructor
2636           BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2637         }
2638       }
2639       // Watch out for ellipsis conversion.
2640       if (!ICS.UserDefined.EllipsisConversion) {
2641         ExprResult Res =
2642           PerformImplicitConversion(From, BeforeToType,
2643                                     ICS.UserDefined.Before, AA_Converting,
2644                                     CCK);
2645         if (Res.isInvalid())
2646           return ExprError();
2647         From = Res.get();
2648       }
2649 
2650       ExprResult CastArg
2651         = BuildCXXCastArgument(*this,
2652                                From->getLocStart(),
2653                                ToType.getNonReferenceType(),
2654                                CastKind, cast<CXXMethodDecl>(FD),
2655                                ICS.UserDefined.FoundConversionFunction,
2656                                ICS.UserDefined.HadMultipleCandidates,
2657                                From);
2658 
2659       if (CastArg.isInvalid())
2660         return ExprError();
2661 
2662       From = CastArg.get();
2663 
2664       return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2665                                        AA_Converting, CCK);
2666   }
2667 
2668   case ImplicitConversionSequence::AmbiguousConversion:
2669     ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
2670                           PDiag(diag::err_typecheck_ambiguous_condition)
2671                             << From->getSourceRange());
2672      return ExprError();
2673 
2674   case ImplicitConversionSequence::EllipsisConversion:
2675     llvm_unreachable("Cannot perform an ellipsis conversion");
2676 
2677   case ImplicitConversionSequence::BadConversion:
2678     return ExprError();
2679   }
2680 
2681   // Everything went well.
2682   return From;
2683 }
2684 
2685 /// PerformImplicitConversion - Perform an implicit conversion of the
2686 /// expression From to the type ToType by following the standard
2687 /// conversion sequence SCS. Returns the converted
2688 /// expression. Flavor is the context in which we're performing this
2689 /// conversion, for use in error messages.
2690 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,const StandardConversionSequence & SCS,AssignmentAction Action,CheckedConversionKind CCK)2691 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2692                                 const StandardConversionSequence& SCS,
2693                                 AssignmentAction Action,
2694                                 CheckedConversionKind CCK) {
2695   bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2696 
2697   // Overall FIXME: we are recomputing too many types here and doing far too
2698   // much extra work. What this means is that we need to keep track of more
2699   // information that is computed when we try the implicit conversion initially,
2700   // so that we don't need to recompute anything here.
2701   QualType FromType = From->getType();
2702 
2703   if (SCS.CopyConstructor) {
2704     // FIXME: When can ToType be a reference type?
2705     assert(!ToType->isReferenceType());
2706     if (SCS.Second == ICK_Derived_To_Base) {
2707       SmallVector<Expr*, 8> ConstructorArgs;
2708       if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
2709                                   From, /*FIXME:ConstructLoc*/SourceLocation(),
2710                                   ConstructorArgs))
2711         return ExprError();
2712       return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2713                                    ToType, SCS.CopyConstructor,
2714                                    ConstructorArgs,
2715                                    /*HadMultipleCandidates*/ false,
2716                                    /*ListInit*/ false, /*ZeroInit*/ false,
2717                                    CXXConstructExpr::CK_Complete,
2718                                    SourceRange());
2719     }
2720     return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2721                                  ToType, SCS.CopyConstructor,
2722                                  From, /*HadMultipleCandidates*/ false,
2723                                  /*ListInit*/ false, /*ZeroInit*/ false,
2724                                  CXXConstructExpr::CK_Complete,
2725                                  SourceRange());
2726   }
2727 
2728   // Resolve overloaded function references.
2729   if (Context.hasSameType(FromType, Context.OverloadTy)) {
2730     DeclAccessPair Found;
2731     FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2732                                                           true, Found);
2733     if (!Fn)
2734       return ExprError();
2735 
2736     if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
2737       return ExprError();
2738 
2739     From = FixOverloadedFunctionReference(From, Found, Fn);
2740     FromType = From->getType();
2741   }
2742 
2743   // If we're converting to an atomic type, first convert to the corresponding
2744   // non-atomic type.
2745   QualType ToAtomicType;
2746   if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
2747     ToAtomicType = ToType;
2748     ToType = ToAtomic->getValueType();
2749   }
2750 
2751   // Perform the first implicit conversion.
2752   switch (SCS.First) {
2753   case ICK_Identity:
2754     // Nothing to do.
2755     break;
2756 
2757   case ICK_Lvalue_To_Rvalue: {
2758     assert(From->getObjectKind() != OK_ObjCProperty);
2759     FromType = FromType.getUnqualifiedType();
2760     ExprResult FromRes = DefaultLvalueConversion(From);
2761     assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2762     From = FromRes.get();
2763     break;
2764   }
2765 
2766   case ICK_Array_To_Pointer:
2767     FromType = Context.getArrayDecayedType(FromType);
2768     From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2769                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2770     break;
2771 
2772   case ICK_Function_To_Pointer:
2773     FromType = Context.getPointerType(FromType);
2774     From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2775                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2776     break;
2777 
2778   default:
2779     llvm_unreachable("Improper first standard conversion");
2780   }
2781 
2782   // Perform the second implicit conversion
2783   switch (SCS.Second) {
2784   case ICK_Identity:
2785     // If both sides are functions (or pointers/references to them), there could
2786     // be incompatible exception declarations.
2787     if (CheckExceptionSpecCompatibility(From, ToType))
2788       return ExprError();
2789     // Nothing else to do.
2790     break;
2791 
2792   case ICK_NoReturn_Adjustment:
2793     // If both sides are functions (or pointers/references to them), there could
2794     // be incompatible exception declarations.
2795     if (CheckExceptionSpecCompatibility(From, ToType))
2796       return ExprError();
2797 
2798     From = ImpCastExprToType(From, ToType, CK_NoOp,
2799                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2800     break;
2801 
2802   case ICK_Integral_Promotion:
2803   case ICK_Integral_Conversion:
2804     if (ToType->isBooleanType()) {
2805       assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
2806              SCS.Second == ICK_Integral_Promotion &&
2807              "only enums with fixed underlying type can promote to bool");
2808       From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
2809                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
2810     } else {
2811       From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2812                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
2813     }
2814     break;
2815 
2816   case ICK_Floating_Promotion:
2817   case ICK_Floating_Conversion:
2818     From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2819                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2820     break;
2821 
2822   case ICK_Complex_Promotion:
2823   case ICK_Complex_Conversion: {
2824     QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2825     QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2826     CastKind CK;
2827     if (FromEl->isRealFloatingType()) {
2828       if (ToEl->isRealFloatingType())
2829         CK = CK_FloatingComplexCast;
2830       else
2831         CK = CK_FloatingComplexToIntegralComplex;
2832     } else if (ToEl->isRealFloatingType()) {
2833       CK = CK_IntegralComplexToFloatingComplex;
2834     } else {
2835       CK = CK_IntegralComplexCast;
2836     }
2837     From = ImpCastExprToType(From, ToType, CK,
2838                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2839     break;
2840   }
2841 
2842   case ICK_Floating_Integral:
2843     if (ToType->isRealFloatingType())
2844       From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2845                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
2846     else
2847       From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2848                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
2849     break;
2850 
2851   case ICK_Compatible_Conversion:
2852       From = ImpCastExprToType(From, ToType, CK_NoOp,
2853                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
2854     break;
2855 
2856   case ICK_Writeback_Conversion:
2857   case ICK_Pointer_Conversion: {
2858     if (SCS.IncompatibleObjC && Action != AA_Casting) {
2859       // Diagnose incompatible Objective-C conversions
2860       if (Action == AA_Initializing || Action == AA_Assigning)
2861         Diag(From->getLocStart(),
2862              diag::ext_typecheck_convert_incompatible_pointer)
2863           << ToType << From->getType() << Action
2864           << From->getSourceRange() << 0;
2865       else
2866         Diag(From->getLocStart(),
2867              diag::ext_typecheck_convert_incompatible_pointer)
2868           << From->getType() << ToType << Action
2869           << From->getSourceRange() << 0;
2870 
2871       if (From->getType()->isObjCObjectPointerType() &&
2872           ToType->isObjCObjectPointerType())
2873         EmitRelatedResultTypeNote(From);
2874     }
2875     else if (getLangOpts().ObjCAutoRefCount &&
2876              !CheckObjCARCUnavailableWeakConversion(ToType,
2877                                                     From->getType())) {
2878       if (Action == AA_Initializing)
2879         Diag(From->getLocStart(),
2880              diag::err_arc_weak_unavailable_assign);
2881       else
2882         Diag(From->getLocStart(),
2883              diag::err_arc_convesion_of_weak_unavailable)
2884           << (Action == AA_Casting) << From->getType() << ToType
2885           << From->getSourceRange();
2886     }
2887 
2888     CastKind Kind = CK_Invalid;
2889     CXXCastPath BasePath;
2890     if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2891       return ExprError();
2892 
2893     // Make sure we extend blocks if necessary.
2894     // FIXME: doing this here is really ugly.
2895     if (Kind == CK_BlockPointerToObjCPointerCast) {
2896       ExprResult E = From;
2897       (void) PrepareCastToObjCObjectPointer(E);
2898       From = E.get();
2899     }
2900     if (getLangOpts().ObjCAutoRefCount)
2901       CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
2902     From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2903              .get();
2904     break;
2905   }
2906 
2907   case ICK_Pointer_Member: {
2908     CastKind Kind = CK_Invalid;
2909     CXXCastPath BasePath;
2910     if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2911       return ExprError();
2912     if (CheckExceptionSpecCompatibility(From, ToType))
2913       return ExprError();
2914     From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2915              .get();
2916     break;
2917   }
2918 
2919   case ICK_Boolean_Conversion:
2920     // Perform half-to-boolean conversion via float.
2921     if (From->getType()->isHalfType()) {
2922       From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
2923       FromType = Context.FloatTy;
2924     }
2925 
2926     From = ImpCastExprToType(From, Context.BoolTy,
2927                              ScalarTypeToBooleanCastKind(FromType),
2928                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2929     break;
2930 
2931   case ICK_Derived_To_Base: {
2932     CXXCastPath BasePath;
2933     if (CheckDerivedToBaseConversion(From->getType(),
2934                                      ToType.getNonReferenceType(),
2935                                      From->getLocStart(),
2936                                      From->getSourceRange(),
2937                                      &BasePath,
2938                                      CStyle))
2939       return ExprError();
2940 
2941     From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2942                       CK_DerivedToBase, From->getValueKind(),
2943                       &BasePath, CCK).get();
2944     break;
2945   }
2946 
2947   case ICK_Vector_Conversion:
2948     From = ImpCastExprToType(From, ToType, CK_BitCast,
2949                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2950     break;
2951 
2952   case ICK_Vector_Splat:
2953     From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2954                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2955     break;
2956 
2957   case ICK_Complex_Real:
2958     // Case 1.  x -> _Complex y
2959     if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2960       QualType ElType = ToComplex->getElementType();
2961       bool isFloatingComplex = ElType->isRealFloatingType();
2962 
2963       // x -> y
2964       if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2965         // do nothing
2966       } else if (From->getType()->isRealFloatingType()) {
2967         From = ImpCastExprToType(From, ElType,
2968                 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
2969       } else {
2970         assert(From->getType()->isIntegerType());
2971         From = ImpCastExprToType(From, ElType,
2972                 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
2973       }
2974       // y -> _Complex y
2975       From = ImpCastExprToType(From, ToType,
2976                    isFloatingComplex ? CK_FloatingRealToComplex
2977                                      : CK_IntegralRealToComplex).get();
2978 
2979     // Case 2.  _Complex x -> y
2980     } else {
2981       const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2982       assert(FromComplex);
2983 
2984       QualType ElType = FromComplex->getElementType();
2985       bool isFloatingComplex = ElType->isRealFloatingType();
2986 
2987       // _Complex x -> x
2988       From = ImpCastExprToType(From, ElType,
2989                    isFloatingComplex ? CK_FloatingComplexToReal
2990                                      : CK_IntegralComplexToReal,
2991                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
2992 
2993       // x -> y
2994       if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2995         // do nothing
2996       } else if (ToType->isRealFloatingType()) {
2997         From = ImpCastExprToType(From, ToType,
2998                    isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2999                                  VK_RValue, /*BasePath=*/nullptr, CCK).get();
3000       } else {
3001         assert(ToType->isIntegerType());
3002         From = ImpCastExprToType(From, ToType,
3003                    isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
3004                                  VK_RValue, /*BasePath=*/nullptr, CCK).get();
3005       }
3006     }
3007     break;
3008 
3009   case ICK_Block_Pointer_Conversion: {
3010     From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
3011                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
3012     break;
3013   }
3014 
3015   case ICK_TransparentUnionConversion: {
3016     ExprResult FromRes = From;
3017     Sema::AssignConvertType ConvTy =
3018       CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3019     if (FromRes.isInvalid())
3020       return ExprError();
3021     From = FromRes.get();
3022     assert ((ConvTy == Sema::Compatible) &&
3023             "Improper transparent union conversion");
3024     (void)ConvTy;
3025     break;
3026   }
3027 
3028   case ICK_Zero_Event_Conversion:
3029     From = ImpCastExprToType(From, ToType,
3030                              CK_ZeroToOCLEvent,
3031                              From->getValueKind()).get();
3032     break;
3033 
3034   case ICK_Lvalue_To_Rvalue:
3035   case ICK_Array_To_Pointer:
3036   case ICK_Function_To_Pointer:
3037   case ICK_Qualification:
3038   case ICK_Num_Conversion_Kinds:
3039     llvm_unreachable("Improper second standard conversion");
3040   }
3041 
3042   switch (SCS.Third) {
3043   case ICK_Identity:
3044     // Nothing to do.
3045     break;
3046 
3047   case ICK_Qualification: {
3048     // The qualification keeps the category of the inner expression, unless the
3049     // target type isn't a reference.
3050     ExprValueKind VK = ToType->isReferenceType() ?
3051                                   From->getValueKind() : VK_RValue;
3052     From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
3053                              CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
3054 
3055     if (SCS.DeprecatedStringLiteralToCharPtr &&
3056         !getLangOpts().WritableStrings) {
3057       Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3058            ? diag::ext_deprecated_string_literal_conversion
3059            : diag::warn_deprecated_string_literal_conversion)
3060         << ToType.getNonReferenceType();
3061     }
3062 
3063     break;
3064   }
3065 
3066   default:
3067     llvm_unreachable("Improper third standard conversion");
3068   }
3069 
3070   // If this conversion sequence involved a scalar -> atomic conversion, perform
3071   // that conversion now.
3072   if (!ToAtomicType.isNull()) {
3073     assert(Context.hasSameType(
3074         ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3075     From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
3076                              VK_RValue, nullptr, CCK).get();
3077   }
3078 
3079   return From;
3080 }
3081 
3082 /// \brief Check the completeness of a type in a unary type trait.
3083 ///
3084 /// If the particular type trait requires a complete type, tries to complete
3085 /// it. If completing the type fails, a diagnostic is emitted and false
3086 /// returned. If completing the type succeeds or no completion was required,
3087 /// returns true.
CheckUnaryTypeTraitTypeCompleteness(Sema & S,TypeTrait UTT,SourceLocation Loc,QualType ArgTy)3088 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
3089                                                 SourceLocation Loc,
3090                                                 QualType ArgTy) {
3091   // C++0x [meta.unary.prop]p3:
3092   //   For all of the class templates X declared in this Clause, instantiating
3093   //   that template with a template argument that is a class template
3094   //   specialization may result in the implicit instantiation of the template
3095   //   argument if and only if the semantics of X require that the argument
3096   //   must be a complete type.
3097   // We apply this rule to all the type trait expressions used to implement
3098   // these class templates. We also try to follow any GCC documented behavior
3099   // in these expressions to ensure portability of standard libraries.
3100   switch (UTT) {
3101   default: llvm_unreachable("not a UTT");
3102     // is_complete_type somewhat obviously cannot require a complete type.
3103   case UTT_IsCompleteType:
3104     // Fall-through
3105 
3106     // These traits are modeled on the type predicates in C++0x
3107     // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3108     // requiring a complete type, as whether or not they return true cannot be
3109     // impacted by the completeness of the type.
3110   case UTT_IsVoid:
3111   case UTT_IsIntegral:
3112   case UTT_IsFloatingPoint:
3113   case UTT_IsArray:
3114   case UTT_IsPointer:
3115   case UTT_IsLvalueReference:
3116   case UTT_IsRvalueReference:
3117   case UTT_IsMemberFunctionPointer:
3118   case UTT_IsMemberObjectPointer:
3119   case UTT_IsEnum:
3120   case UTT_IsUnion:
3121   case UTT_IsClass:
3122   case UTT_IsFunction:
3123   case UTT_IsReference:
3124   case UTT_IsArithmetic:
3125   case UTT_IsFundamental:
3126   case UTT_IsObject:
3127   case UTT_IsScalar:
3128   case UTT_IsCompound:
3129   case UTT_IsMemberPointer:
3130     // Fall-through
3131 
3132     // These traits are modeled on type predicates in C++0x [meta.unary.prop]
3133     // which requires some of its traits to have the complete type. However,
3134     // the completeness of the type cannot impact these traits' semantics, and
3135     // so they don't require it. This matches the comments on these traits in
3136     // Table 49.
3137   case UTT_IsConst:
3138   case UTT_IsVolatile:
3139   case UTT_IsSigned:
3140   case UTT_IsUnsigned:
3141     return true;
3142 
3143     // C++0x [meta.unary.prop] Table 49 requires the following traits to be
3144     // applied to a complete type.
3145   case UTT_IsTrivial:
3146   case UTT_IsTriviallyCopyable:
3147   case UTT_IsStandardLayout:
3148   case UTT_IsPOD:
3149   case UTT_IsLiteral:
3150   case UTT_IsEmpty:
3151   case UTT_IsPolymorphic:
3152   case UTT_IsAbstract:
3153   case UTT_IsInterfaceClass:
3154   case UTT_IsDestructible:
3155   case UTT_IsNothrowDestructible:
3156     // Fall-through
3157 
3158   // These traits require a complete type.
3159   case UTT_IsFinal:
3160   case UTT_IsSealed:
3161 
3162     // These trait expressions are designed to help implement predicates in
3163     // [meta.unary.prop] despite not being named the same. They are specified
3164     // by both GCC and the Embarcadero C++ compiler, and require the complete
3165     // type due to the overarching C++0x type predicates being implemented
3166     // requiring the complete type.
3167   case UTT_HasNothrowAssign:
3168   case UTT_HasNothrowMoveAssign:
3169   case UTT_HasNothrowConstructor:
3170   case UTT_HasNothrowCopy:
3171   case UTT_HasTrivialAssign:
3172   case UTT_HasTrivialMoveAssign:
3173   case UTT_HasTrivialDefaultConstructor:
3174   case UTT_HasTrivialMoveConstructor:
3175   case UTT_HasTrivialCopy:
3176   case UTT_HasTrivialDestructor:
3177   case UTT_HasVirtualDestructor:
3178     // Arrays of unknown bound are expressly allowed.
3179     QualType ElTy = ArgTy;
3180     if (ArgTy->isIncompleteArrayType())
3181       ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
3182 
3183     // The void type is expressly allowed.
3184     if (ElTy->isVoidType())
3185       return true;
3186 
3187     return !S.RequireCompleteType(
3188       Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
3189   }
3190 }
3191 
HasNoThrowOperator(const RecordType * RT,OverloadedOperatorKind Op,Sema & Self,SourceLocation KeyLoc,ASTContext & C,bool (CXXRecordDecl::* HasTrivial)()const,bool (CXXRecordDecl::* HasNonTrivial)()const,bool (CXXMethodDecl::* IsDesiredOp)()const)3192 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
3193                                Sema &Self, SourceLocation KeyLoc, ASTContext &C,
3194                                bool (CXXRecordDecl::*HasTrivial)() const,
3195                                bool (CXXRecordDecl::*HasNonTrivial)() const,
3196                                bool (CXXMethodDecl::*IsDesiredOp)() const)
3197 {
3198   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3199   if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
3200     return true;
3201 
3202   DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
3203   DeclarationNameInfo NameInfo(Name, KeyLoc);
3204   LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
3205   if (Self.LookupQualifiedName(Res, RD)) {
3206     bool FoundOperator = false;
3207     Res.suppressDiagnostics();
3208     for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3209          Op != OpEnd; ++Op) {
3210       if (isa<FunctionTemplateDecl>(*Op))
3211         continue;
3212 
3213       CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3214       if((Operator->*IsDesiredOp)()) {
3215         FoundOperator = true;
3216         const FunctionProtoType *CPT =
3217           Operator->getType()->getAs<FunctionProtoType>();
3218         CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3219         if (!CPT || !CPT->isNothrow(C))
3220           return false;
3221       }
3222     }
3223     return FoundOperator;
3224   }
3225   return false;
3226 }
3227 
EvaluateUnaryTypeTrait(Sema & Self,TypeTrait UTT,SourceLocation KeyLoc,QualType T)3228 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
3229                                    SourceLocation KeyLoc, QualType T) {
3230   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3231 
3232   ASTContext &C = Self.Context;
3233   switch(UTT) {
3234   default: llvm_unreachable("not a UTT");
3235     // Type trait expressions corresponding to the primary type category
3236     // predicates in C++0x [meta.unary.cat].
3237   case UTT_IsVoid:
3238     return T->isVoidType();
3239   case UTT_IsIntegral:
3240     return T->isIntegralType(C);
3241   case UTT_IsFloatingPoint:
3242     return T->isFloatingType();
3243   case UTT_IsArray:
3244     return T->isArrayType();
3245   case UTT_IsPointer:
3246     return T->isPointerType();
3247   case UTT_IsLvalueReference:
3248     return T->isLValueReferenceType();
3249   case UTT_IsRvalueReference:
3250     return T->isRValueReferenceType();
3251   case UTT_IsMemberFunctionPointer:
3252     return T->isMemberFunctionPointerType();
3253   case UTT_IsMemberObjectPointer:
3254     return T->isMemberDataPointerType();
3255   case UTT_IsEnum:
3256     return T->isEnumeralType();
3257   case UTT_IsUnion:
3258     return T->isUnionType();
3259   case UTT_IsClass:
3260     return T->isClassType() || T->isStructureType() || T->isInterfaceType();
3261   case UTT_IsFunction:
3262     return T->isFunctionType();
3263 
3264     // Type trait expressions which correspond to the convenient composition
3265     // predicates in C++0x [meta.unary.comp].
3266   case UTT_IsReference:
3267     return T->isReferenceType();
3268   case UTT_IsArithmetic:
3269     return T->isArithmeticType() && !T->isEnumeralType();
3270   case UTT_IsFundamental:
3271     return T->isFundamentalType();
3272   case UTT_IsObject:
3273     return T->isObjectType();
3274   case UTT_IsScalar:
3275     // Note: semantic analysis depends on Objective-C lifetime types to be
3276     // considered scalar types. However, such types do not actually behave
3277     // like scalar types at run time (since they may require retain/release
3278     // operations), so we report them as non-scalar.
3279     if (T->isObjCLifetimeType()) {
3280       switch (T.getObjCLifetime()) {
3281       case Qualifiers::OCL_None:
3282       case Qualifiers::OCL_ExplicitNone:
3283         return true;
3284 
3285       case Qualifiers::OCL_Strong:
3286       case Qualifiers::OCL_Weak:
3287       case Qualifiers::OCL_Autoreleasing:
3288         return false;
3289       }
3290     }
3291 
3292     return T->isScalarType();
3293   case UTT_IsCompound:
3294     return T->isCompoundType();
3295   case UTT_IsMemberPointer:
3296     return T->isMemberPointerType();
3297 
3298     // Type trait expressions which correspond to the type property predicates
3299     // in C++0x [meta.unary.prop].
3300   case UTT_IsConst:
3301     return T.isConstQualified();
3302   case UTT_IsVolatile:
3303     return T.isVolatileQualified();
3304   case UTT_IsTrivial:
3305     return T.isTrivialType(Self.Context);
3306   case UTT_IsTriviallyCopyable:
3307     return T.isTriviallyCopyableType(Self.Context);
3308   case UTT_IsStandardLayout:
3309     return T->isStandardLayoutType();
3310   case UTT_IsPOD:
3311     return T.isPODType(Self.Context);
3312   case UTT_IsLiteral:
3313     return T->isLiteralType(Self.Context);
3314   case UTT_IsEmpty:
3315     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3316       return !RD->isUnion() && RD->isEmpty();
3317     return false;
3318   case UTT_IsPolymorphic:
3319     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3320       return RD->isPolymorphic();
3321     return false;
3322   case UTT_IsAbstract:
3323     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3324       return RD->isAbstract();
3325     return false;
3326   case UTT_IsInterfaceClass:
3327     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3328       return RD->isInterface();
3329     return false;
3330   case UTT_IsFinal:
3331     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3332       return RD->hasAttr<FinalAttr>();
3333     return false;
3334   case UTT_IsSealed:
3335     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3336       if (FinalAttr *FA = RD->getAttr<FinalAttr>())
3337         return FA->isSpelledAsSealed();
3338     return false;
3339   case UTT_IsSigned:
3340     return T->isSignedIntegerType();
3341   case UTT_IsUnsigned:
3342     return T->isUnsignedIntegerType();
3343 
3344     // Type trait expressions which query classes regarding their construction,
3345     // destruction, and copying. Rather than being based directly on the
3346     // related type predicates in the standard, they are specified by both
3347     // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3348     // specifications.
3349     //
3350     //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3351     //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3352     //
3353     // Note that these builtins do not behave as documented in g++: if a class
3354     // has both a trivial and a non-trivial special member of a particular kind,
3355     // they return false! For now, we emulate this behavior.
3356     // FIXME: This appears to be a g++ bug: more complex cases reveal that it
3357     // does not correctly compute triviality in the presence of multiple special
3358     // members of the same kind. Revisit this once the g++ bug is fixed.
3359   case UTT_HasTrivialDefaultConstructor:
3360     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3361     //   If __is_pod (type) is true then the trait is true, else if type is
3362     //   a cv class or union type (or array thereof) with a trivial default
3363     //   constructor ([class.ctor]) then the trait is true, else it is false.
3364     if (T.isPODType(Self.Context))
3365       return true;
3366     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3367       return RD->hasTrivialDefaultConstructor() &&
3368              !RD->hasNonTrivialDefaultConstructor();
3369     return false;
3370   case UTT_HasTrivialMoveConstructor:
3371     //  This trait is implemented by MSVC 2012 and needed to parse the
3372     //  standard library headers. Specifically this is used as the logic
3373     //  behind std::is_trivially_move_constructible (20.9.4.3).
3374     if (T.isPODType(Self.Context))
3375       return true;
3376     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3377       return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
3378     return false;
3379   case UTT_HasTrivialCopy:
3380     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3381     //   If __is_pod (type) is true or type is a reference type then
3382     //   the trait is true, else if type is a cv class or union type
3383     //   with a trivial copy constructor ([class.copy]) then the trait
3384     //   is true, else it is false.
3385     if (T.isPODType(Self.Context) || T->isReferenceType())
3386       return true;
3387     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3388       return RD->hasTrivialCopyConstructor() &&
3389              !RD->hasNonTrivialCopyConstructor();
3390     return false;
3391   case UTT_HasTrivialMoveAssign:
3392     //  This trait is implemented by MSVC 2012 and needed to parse the
3393     //  standard library headers. Specifically it is used as the logic
3394     //  behind std::is_trivially_move_assignable (20.9.4.3)
3395     if (T.isPODType(Self.Context))
3396       return true;
3397     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3398       return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
3399     return false;
3400   case UTT_HasTrivialAssign:
3401     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3402     //   If type is const qualified or is a reference type then the
3403     //   trait is false. Otherwise if __is_pod (type) is true then the
3404     //   trait is true, else if type is a cv class or union type with
3405     //   a trivial copy assignment ([class.copy]) then the trait is
3406     //   true, else it is false.
3407     // Note: the const and reference restrictions are interesting,
3408     // given that const and reference members don't prevent a class
3409     // from having a trivial copy assignment operator (but do cause
3410     // errors if the copy assignment operator is actually used, q.v.
3411     // [class.copy]p12).
3412 
3413     if (T.isConstQualified())
3414       return false;
3415     if (T.isPODType(Self.Context))
3416       return true;
3417     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3418       return RD->hasTrivialCopyAssignment() &&
3419              !RD->hasNonTrivialCopyAssignment();
3420     return false;
3421   case UTT_IsDestructible:
3422   case UTT_IsNothrowDestructible:
3423     // FIXME: Implement UTT_IsDestructible and UTT_IsNothrowDestructible.
3424     // For now, let's fall through.
3425   case UTT_HasTrivialDestructor:
3426     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
3427     //   If __is_pod (type) is true or type is a reference type
3428     //   then the trait is true, else if type is a cv class or union
3429     //   type (or array thereof) with a trivial destructor
3430     //   ([class.dtor]) then the trait is true, else it is
3431     //   false.
3432     if (T.isPODType(Self.Context) || T->isReferenceType())
3433       return true;
3434 
3435     // Objective-C++ ARC: autorelease types don't require destruction.
3436     if (T->isObjCLifetimeType() &&
3437         T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3438       return true;
3439 
3440     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3441       return RD->hasTrivialDestructor();
3442     return false;
3443   // TODO: Propagate nothrowness for implicitly declared special members.
3444   case UTT_HasNothrowAssign:
3445     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3446     //   If type is const qualified or is a reference type then the
3447     //   trait is false. Otherwise if __has_trivial_assign (type)
3448     //   is true then the trait is true, else if type is a cv class
3449     //   or union type with copy assignment operators that are known
3450     //   not to throw an exception then the trait is true, else it is
3451     //   false.
3452     if (C.getBaseElementType(T).isConstQualified())
3453       return false;
3454     if (T->isReferenceType())
3455       return false;
3456     if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3457       return true;
3458 
3459     if (const RecordType *RT = T->getAs<RecordType>())
3460       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3461                                 &CXXRecordDecl::hasTrivialCopyAssignment,
3462                                 &CXXRecordDecl::hasNonTrivialCopyAssignment,
3463                                 &CXXMethodDecl::isCopyAssignmentOperator);
3464     return false;
3465   case UTT_HasNothrowMoveAssign:
3466     //  This trait is implemented by MSVC 2012 and needed to parse the
3467     //  standard library headers. Specifically this is used as the logic
3468     //  behind std::is_nothrow_move_assignable (20.9.4.3).
3469     if (T.isPODType(Self.Context))
3470       return true;
3471 
3472     if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
3473       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3474                                 &CXXRecordDecl::hasTrivialMoveAssignment,
3475                                 &CXXRecordDecl::hasNonTrivialMoveAssignment,
3476                                 &CXXMethodDecl::isMoveAssignmentOperator);
3477     return false;
3478   case UTT_HasNothrowCopy:
3479     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3480     //   If __has_trivial_copy (type) is true then the trait is true, else
3481     //   if type is a cv class or union type with copy constructors that are
3482     //   known not to throw an exception then the trait is true, else it is
3483     //   false.
3484     if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
3485       return true;
3486     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
3487       if (RD->hasTrivialCopyConstructor() &&
3488           !RD->hasNonTrivialCopyConstructor())
3489         return true;
3490 
3491       bool FoundConstructor = false;
3492       unsigned FoundTQs;
3493       DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3494       for (DeclContext::lookup_const_iterator Con = R.begin(),
3495            ConEnd = R.end(); Con != ConEnd; ++Con) {
3496         // A template constructor is never a copy constructor.
3497         // FIXME: However, it may actually be selected at the actual overload
3498         // resolution point.
3499         if (isa<FunctionTemplateDecl>(*Con))
3500           continue;
3501         CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3502         if (Constructor->isCopyConstructor(FoundTQs)) {
3503           FoundConstructor = true;
3504           const FunctionProtoType *CPT
3505               = Constructor->getType()->getAs<FunctionProtoType>();
3506           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3507           if (!CPT)
3508             return false;
3509           // TODO: check whether evaluating default arguments can throw.
3510           // For now, we'll be conservative and assume that they can throw.
3511           if (!CPT->isNothrow(Self.Context) || CPT->getNumParams() > 1)
3512             return false;
3513         }
3514       }
3515 
3516       return FoundConstructor;
3517     }
3518     return false;
3519   case UTT_HasNothrowConstructor:
3520     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
3521     //   If __has_trivial_constructor (type) is true then the trait is
3522     //   true, else if type is a cv class or union type (or array
3523     //   thereof) with a default constructor that is known not to
3524     //   throw an exception then the trait is true, else it is false.
3525     if (T.isPODType(C) || T->isObjCLifetimeType())
3526       return true;
3527     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
3528       if (RD->hasTrivialDefaultConstructor() &&
3529           !RD->hasNonTrivialDefaultConstructor())
3530         return true;
3531 
3532       bool FoundConstructor = false;
3533       DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3534       for (DeclContext::lookup_const_iterator Con = R.begin(),
3535            ConEnd = R.end(); Con != ConEnd; ++Con) {
3536         // FIXME: In C++0x, a constructor template can be a default constructor.
3537         if (isa<FunctionTemplateDecl>(*Con))
3538           continue;
3539         CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3540         if (Constructor->isDefaultConstructor()) {
3541           FoundConstructor = true;
3542           const FunctionProtoType *CPT
3543               = Constructor->getType()->getAs<FunctionProtoType>();
3544           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3545           if (!CPT)
3546             return false;
3547           // FIXME: check whether evaluating default arguments can throw.
3548           // For now, we'll be conservative and assume that they can throw.
3549           if (!CPT->isNothrow(Self.Context) || CPT->getNumParams() > 0)
3550             return false;
3551         }
3552       }
3553       return FoundConstructor;
3554     }
3555     return false;
3556   case UTT_HasVirtualDestructor:
3557     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3558     //   If type is a class type with a virtual destructor ([class.dtor])
3559     //   then the trait is true, else it is false.
3560     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3561       if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
3562         return Destructor->isVirtual();
3563     return false;
3564 
3565     // These type trait expressions are modeled on the specifications for the
3566     // Embarcadero C++0x type trait functions:
3567     //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3568   case UTT_IsCompleteType:
3569     // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3570     //   Returns True if and only if T is a complete type at the point of the
3571     //   function call.
3572     return !T->isIncompleteType();
3573   }
3574 }
3575 
3576 /// \brief Determine whether T has a non-trivial Objective-C lifetime in
3577 /// ARC mode.
hasNontrivialObjCLifetime(QualType T)3578 static bool hasNontrivialObjCLifetime(QualType T) {
3579   switch (T.getObjCLifetime()) {
3580   case Qualifiers::OCL_ExplicitNone:
3581     return false;
3582 
3583   case Qualifiers::OCL_Strong:
3584   case Qualifiers::OCL_Weak:
3585   case Qualifiers::OCL_Autoreleasing:
3586     return true;
3587 
3588   case Qualifiers::OCL_None:
3589     return T->isObjCLifetimeType();
3590   }
3591 
3592   llvm_unreachable("Unknown ObjC lifetime qualifier");
3593 }
3594 
3595 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
3596                                     QualType RhsT, SourceLocation KeyLoc);
3597 
evaluateTypeTrait(Sema & S,TypeTrait Kind,SourceLocation KWLoc,ArrayRef<TypeSourceInfo * > Args,SourceLocation RParenLoc)3598 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3599                               ArrayRef<TypeSourceInfo *> Args,
3600                               SourceLocation RParenLoc) {
3601   if (Kind <= UTT_Last)
3602     return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
3603 
3604   if (Kind <= BTT_Last)
3605     return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
3606                                    Args[1]->getType(), RParenLoc);
3607 
3608   switch (Kind) {
3609   case clang::TT_IsConstructible:
3610   case clang::TT_IsNothrowConstructible:
3611   case clang::TT_IsTriviallyConstructible: {
3612     // C++11 [meta.unary.prop]:
3613     //   is_trivially_constructible is defined as:
3614     //
3615     //     is_constructible<T, Args...>::value is true and the variable
3616     //     definition for is_constructible, as defined below, is known to call
3617     //     no operation that is not trivial.
3618     //
3619     //   The predicate condition for a template specialization
3620     //   is_constructible<T, Args...> shall be satisfied if and only if the
3621     //   following variable definition would be well-formed for some invented
3622     //   variable t:
3623     //
3624     //     T t(create<Args>()...);
3625     assert(!Args.empty());
3626 
3627     // Precondition: T and all types in the parameter pack Args shall be
3628     // complete types, (possibly cv-qualified) void, or arrays of
3629     // unknown bound.
3630     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3631       QualType ArgTy = Args[I]->getType();
3632       if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
3633         continue;
3634 
3635       if (S.RequireCompleteType(KWLoc, ArgTy,
3636           diag::err_incomplete_type_used_in_type_trait_expr))
3637         return false;
3638     }
3639 
3640     // Make sure the first argument is a complete type.
3641     if (Args[0]->getType()->isIncompleteType())
3642       return false;
3643 
3644     // Make sure the first argument is not an abstract type.
3645     CXXRecordDecl *RD = Args[0]->getType()->getAsCXXRecordDecl();
3646     if (RD && RD->isAbstract())
3647       return false;
3648 
3649     SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3650     SmallVector<Expr *, 2> ArgExprs;
3651     ArgExprs.reserve(Args.size() - 1);
3652     for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3653       QualType T = Args[I]->getType();
3654       if (T->isObjectType() || T->isFunctionType())
3655         T = S.Context.getRValueReferenceType(T);
3656       OpaqueArgExprs.push_back(
3657         OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
3658                         T.getNonLValueExprType(S.Context),
3659                         Expr::getValueKindForType(T)));
3660       ArgExprs.push_back(&OpaqueArgExprs.back());
3661     }
3662 
3663     // Perform the initialization in an unevaluated context within a SFINAE
3664     // trap at translation unit scope.
3665     EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3666     Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3667     Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3668     InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3669     InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3670                                                                  RParenLoc));
3671     InitializationSequence Init(S, To, InitKind, ArgExprs);
3672     if (Init.Failed())
3673       return false;
3674 
3675     ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
3676     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3677       return false;
3678 
3679     if (Kind == clang::TT_IsConstructible)
3680       return true;
3681 
3682     if (Kind == clang::TT_IsNothrowConstructible)
3683       return S.canThrow(Result.get()) == CT_Cannot;
3684 
3685     if (Kind == clang::TT_IsTriviallyConstructible) {
3686       // Under Objective-C ARC, if the destination has non-trivial Objective-C
3687       // lifetime, this is a non-trivial construction.
3688       if (S.getLangOpts().ObjCAutoRefCount &&
3689           hasNontrivialObjCLifetime(Args[0]->getType().getNonReferenceType()))
3690         return false;
3691 
3692       // The initialization succeeded; now make sure there are no non-trivial
3693       // calls.
3694       return !Result.get()->hasNonTrivialCall(S.Context);
3695     }
3696 
3697     llvm_unreachable("unhandled type trait");
3698     return false;
3699   }
3700     default: llvm_unreachable("not a TT");
3701   }
3702 
3703   return false;
3704 }
3705 
BuildTypeTrait(TypeTrait Kind,SourceLocation KWLoc,ArrayRef<TypeSourceInfo * > Args,SourceLocation RParenLoc)3706 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3707                                 ArrayRef<TypeSourceInfo *> Args,
3708                                 SourceLocation RParenLoc) {
3709   QualType ResultType = Context.getLogicalOperationType();
3710 
3711   if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
3712                                *this, Kind, KWLoc, Args[0]->getType()))
3713     return ExprError();
3714 
3715   bool Dependent = false;
3716   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3717     if (Args[I]->getType()->isDependentType()) {
3718       Dependent = true;
3719       break;
3720     }
3721   }
3722 
3723   bool Result = false;
3724   if (!Dependent)
3725     Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3726 
3727   return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
3728                                RParenLoc, Result);
3729 }
3730 
ActOnTypeTrait(TypeTrait Kind,SourceLocation KWLoc,ArrayRef<ParsedType> Args,SourceLocation RParenLoc)3731 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3732                                 ArrayRef<ParsedType> Args,
3733                                 SourceLocation RParenLoc) {
3734   SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
3735   ConvertedArgs.reserve(Args.size());
3736 
3737   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3738     TypeSourceInfo *TInfo;
3739     QualType T = GetTypeFromParser(Args[I], &TInfo);
3740     if (!TInfo)
3741       TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3742 
3743     ConvertedArgs.push_back(TInfo);
3744   }
3745 
3746   return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3747 }
3748 
EvaluateBinaryTypeTrait(Sema & Self,TypeTrait BTT,QualType LhsT,QualType RhsT,SourceLocation KeyLoc)3749 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
3750                                     QualType RhsT, SourceLocation KeyLoc) {
3751   assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3752          "Cannot evaluate traits of dependent types");
3753 
3754   switch(BTT) {
3755   case BTT_IsBaseOf: {
3756     // C++0x [meta.rel]p2
3757     // Base is a base class of Derived without regard to cv-qualifiers or
3758     // Base and Derived are not unions and name the same class type without
3759     // regard to cv-qualifiers.
3760 
3761     const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3762     if (!lhsRecord) return false;
3763 
3764     const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3765     if (!rhsRecord) return false;
3766 
3767     assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3768              == (lhsRecord == rhsRecord));
3769 
3770     if (lhsRecord == rhsRecord)
3771       return !lhsRecord->getDecl()->isUnion();
3772 
3773     // C++0x [meta.rel]p2:
3774     //   If Base and Derived are class types and are different types
3775     //   (ignoring possible cv-qualifiers) then Derived shall be a
3776     //   complete type.
3777     if (Self.RequireCompleteType(KeyLoc, RhsT,
3778                           diag::err_incomplete_type_used_in_type_trait_expr))
3779       return false;
3780 
3781     return cast<CXXRecordDecl>(rhsRecord->getDecl())
3782       ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3783   }
3784   case BTT_IsSame:
3785     return Self.Context.hasSameType(LhsT, RhsT);
3786   case BTT_TypeCompatible:
3787     return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3788                                            RhsT.getUnqualifiedType());
3789   case BTT_IsConvertible:
3790   case BTT_IsConvertibleTo: {
3791     // C++0x [meta.rel]p4:
3792     //   Given the following function prototype:
3793     //
3794     //     template <class T>
3795     //       typename add_rvalue_reference<T>::type create();
3796     //
3797     //   the predicate condition for a template specialization
3798     //   is_convertible<From, To> shall be satisfied if and only if
3799     //   the return expression in the following code would be
3800     //   well-formed, including any implicit conversions to the return
3801     //   type of the function:
3802     //
3803     //     To test() {
3804     //       return create<From>();
3805     //     }
3806     //
3807     //   Access checking is performed as if in a context unrelated to To and
3808     //   From. Only the validity of the immediate context of the expression
3809     //   of the return-statement (including conversions to the return type)
3810     //   is considered.
3811     //
3812     // We model the initialization as a copy-initialization of a temporary
3813     // of the appropriate type, which for this expression is identical to the
3814     // return statement (since NRVO doesn't apply).
3815 
3816     // Functions aren't allowed to return function or array types.
3817     if (RhsT->isFunctionType() || RhsT->isArrayType())
3818       return false;
3819 
3820     // A return statement in a void function must have void type.
3821     if (RhsT->isVoidType())
3822       return LhsT->isVoidType();
3823 
3824     // A function definition requires a complete, non-abstract return type.
3825     if (Self.RequireCompleteType(KeyLoc, RhsT, 0) ||
3826         Self.RequireNonAbstractType(KeyLoc, RhsT, 0))
3827       return false;
3828 
3829     // Compute the result of add_rvalue_reference.
3830     if (LhsT->isObjectType() || LhsT->isFunctionType())
3831       LhsT = Self.Context.getRValueReferenceType(LhsT);
3832 
3833     // Build a fake source and destination for initialization.
3834     InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
3835     OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3836                          Expr::getValueKindForType(LhsT));
3837     Expr *FromPtr = &From;
3838     InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3839                                                            SourceLocation()));
3840 
3841     // Perform the initialization in an unevaluated context within a SFINAE
3842     // trap at translation unit scope.
3843     EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3844     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3845     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3846     InitializationSequence Init(Self, To, Kind, FromPtr);
3847     if (Init.Failed())
3848       return false;
3849 
3850     ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
3851     return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3852   }
3853 
3854   case BTT_IsNothrowAssignable:
3855   case BTT_IsTriviallyAssignable: {
3856     // C++11 [meta.unary.prop]p3:
3857     //   is_trivially_assignable is defined as:
3858     //     is_assignable<T, U>::value is true and the assignment, as defined by
3859     //     is_assignable, is known to call no operation that is not trivial
3860     //
3861     //   is_assignable is defined as:
3862     //     The expression declval<T>() = declval<U>() is well-formed when
3863     //     treated as an unevaluated operand (Clause 5).
3864     //
3865     //   For both, T and U shall be complete types, (possibly cv-qualified)
3866     //   void, or arrays of unknown bound.
3867     if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3868         Self.RequireCompleteType(KeyLoc, LhsT,
3869           diag::err_incomplete_type_used_in_type_trait_expr))
3870       return false;
3871     if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3872         Self.RequireCompleteType(KeyLoc, RhsT,
3873           diag::err_incomplete_type_used_in_type_trait_expr))
3874       return false;
3875 
3876     // cv void is never assignable.
3877     if (LhsT->isVoidType() || RhsT->isVoidType())
3878       return false;
3879 
3880     // Build expressions that emulate the effect of declval<T>() and
3881     // declval<U>().
3882     if (LhsT->isObjectType() || LhsT->isFunctionType())
3883       LhsT = Self.Context.getRValueReferenceType(LhsT);
3884     if (RhsT->isObjectType() || RhsT->isFunctionType())
3885       RhsT = Self.Context.getRValueReferenceType(RhsT);
3886     OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3887                         Expr::getValueKindForType(LhsT));
3888     OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3889                         Expr::getValueKindForType(RhsT));
3890 
3891     // Attempt the assignment in an unevaluated context within a SFINAE
3892     // trap at translation unit scope.
3893     EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3894     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3895     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3896     ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
3897                                         &Rhs);
3898     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3899       return false;
3900 
3901     if (BTT == BTT_IsNothrowAssignable)
3902       return Self.canThrow(Result.get()) == CT_Cannot;
3903 
3904     if (BTT == BTT_IsTriviallyAssignable) {
3905       // Under Objective-C ARC, if the destination has non-trivial Objective-C
3906       // lifetime, this is a non-trivial assignment.
3907       if (Self.getLangOpts().ObjCAutoRefCount &&
3908           hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
3909         return false;
3910 
3911       return !Result.get()->hasNonTrivialCall(Self.Context);
3912     }
3913 
3914     llvm_unreachable("unhandled type trait");
3915     return false;
3916   }
3917     default: llvm_unreachable("not a BTT");
3918   }
3919   llvm_unreachable("Unknown type trait or not implemented");
3920 }
3921 
ActOnArrayTypeTrait(ArrayTypeTrait ATT,SourceLocation KWLoc,ParsedType Ty,Expr * DimExpr,SourceLocation RParen)3922 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3923                                      SourceLocation KWLoc,
3924                                      ParsedType Ty,
3925                                      Expr* DimExpr,
3926                                      SourceLocation RParen) {
3927   TypeSourceInfo *TSInfo;
3928   QualType T = GetTypeFromParser(Ty, &TSInfo);
3929   if (!TSInfo)
3930     TSInfo = Context.getTrivialTypeSourceInfo(T);
3931 
3932   return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3933 }
3934 
EvaluateArrayTypeTrait(Sema & Self,ArrayTypeTrait ATT,QualType T,Expr * DimExpr,SourceLocation KeyLoc)3935 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3936                                            QualType T, Expr *DimExpr,
3937                                            SourceLocation KeyLoc) {
3938   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3939 
3940   switch(ATT) {
3941   case ATT_ArrayRank:
3942     if (T->isArrayType()) {
3943       unsigned Dim = 0;
3944       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3945         ++Dim;
3946         T = AT->getElementType();
3947       }
3948       return Dim;
3949     }
3950     return 0;
3951 
3952   case ATT_ArrayExtent: {
3953     llvm::APSInt Value;
3954     uint64_t Dim;
3955     if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
3956           diag::err_dimension_expr_not_constant_integer,
3957           false).isInvalid())
3958       return 0;
3959     if (Value.isSigned() && Value.isNegative()) {
3960       Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3961         << DimExpr->getSourceRange();
3962       return 0;
3963     }
3964     Dim = Value.getLimitedValue();
3965 
3966     if (T->isArrayType()) {
3967       unsigned D = 0;
3968       bool Matched = false;
3969       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3970         if (Dim == D) {
3971           Matched = true;
3972           break;
3973         }
3974         ++D;
3975         T = AT->getElementType();
3976       }
3977 
3978       if (Matched && T->isArrayType()) {
3979         if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3980           return CAT->getSize().getLimitedValue();
3981       }
3982     }
3983     return 0;
3984   }
3985   }
3986   llvm_unreachable("Unknown type trait or not implemented");
3987 }
3988 
BuildArrayTypeTrait(ArrayTypeTrait ATT,SourceLocation KWLoc,TypeSourceInfo * TSInfo,Expr * DimExpr,SourceLocation RParen)3989 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3990                                      SourceLocation KWLoc,
3991                                      TypeSourceInfo *TSInfo,
3992                                      Expr* DimExpr,
3993                                      SourceLocation RParen) {
3994   QualType T = TSInfo->getType();
3995 
3996   // FIXME: This should likely be tracked as an APInt to remove any host
3997   // assumptions about the width of size_t on the target.
3998   uint64_t Value = 0;
3999   if (!T->isDependentType())
4000     Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4001 
4002   // While the specification for these traits from the Embarcadero C++
4003   // compiler's documentation says the return type is 'unsigned int', Clang
4004   // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4005   // compiler, there is no difference. On several other platforms this is an
4006   // important distinction.
4007   return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4008                                           RParen, Context.getSizeType());
4009 }
4010 
ActOnExpressionTrait(ExpressionTrait ET,SourceLocation KWLoc,Expr * Queried,SourceLocation RParen)4011 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
4012                                       SourceLocation KWLoc,
4013                                       Expr *Queried,
4014                                       SourceLocation RParen) {
4015   // If error parsing the expression, ignore.
4016   if (!Queried)
4017     return ExprError();
4018 
4019   ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
4020 
4021   return Result;
4022 }
4023 
EvaluateExpressionTrait(ExpressionTrait ET,Expr * E)4024 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4025   switch (ET) {
4026   case ET_IsLValueExpr: return E->isLValue();
4027   case ET_IsRValueExpr: return E->isRValue();
4028   }
4029   llvm_unreachable("Expression trait not covered by switch");
4030 }
4031 
BuildExpressionTrait(ExpressionTrait ET,SourceLocation KWLoc,Expr * Queried,SourceLocation RParen)4032 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
4033                                       SourceLocation KWLoc,
4034                                       Expr *Queried,
4035                                       SourceLocation RParen) {
4036   if (Queried->isTypeDependent()) {
4037     // Delay type-checking for type-dependent expressions.
4038   } else if (Queried->getType()->isPlaceholderType()) {
4039     ExprResult PE = CheckPlaceholderExpr(Queried);
4040     if (PE.isInvalid()) return ExprError();
4041     return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
4042   }
4043 
4044   bool Value = EvaluateExpressionTrait(ET, Queried);
4045 
4046   return new (Context)
4047       ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
4048 }
4049 
CheckPointerToMemberOperands(ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,SourceLocation Loc,bool isIndirect)4050 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
4051                                             ExprValueKind &VK,
4052                                             SourceLocation Loc,
4053                                             bool isIndirect) {
4054   assert(!LHS.get()->getType()->isPlaceholderType() &&
4055          !RHS.get()->getType()->isPlaceholderType() &&
4056          "placeholders should have been weeded out by now");
4057 
4058   // The LHS undergoes lvalue conversions if this is ->*.
4059   if (isIndirect) {
4060     LHS = DefaultLvalueConversion(LHS.get());
4061     if (LHS.isInvalid()) return QualType();
4062   }
4063 
4064   // The RHS always undergoes lvalue conversions.
4065   RHS = DefaultLvalueConversion(RHS.get());
4066   if (RHS.isInvalid()) return QualType();
4067 
4068   const char *OpSpelling = isIndirect ? "->*" : ".*";
4069   // C++ 5.5p2
4070   //   The binary operator .* [p3: ->*] binds its second operand, which shall
4071   //   be of type "pointer to member of T" (where T is a completely-defined
4072   //   class type) [...]
4073   QualType RHSType = RHS.get()->getType();
4074   const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
4075   if (!MemPtr) {
4076     Diag(Loc, diag::err_bad_memptr_rhs)
4077       << OpSpelling << RHSType << RHS.get()->getSourceRange();
4078     return QualType();
4079   }
4080 
4081   QualType Class(MemPtr->getClass(), 0);
4082 
4083   // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
4084   // member pointer points must be completely-defined. However, there is no
4085   // reason for this semantic distinction, and the rule is not enforced by
4086   // other compilers. Therefore, we do not check this property, as it is
4087   // likely to be considered a defect.
4088 
4089   // C++ 5.5p2
4090   //   [...] to its first operand, which shall be of class T or of a class of
4091   //   which T is an unambiguous and accessible base class. [p3: a pointer to
4092   //   such a class]
4093   QualType LHSType = LHS.get()->getType();
4094   if (isIndirect) {
4095     if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4096       LHSType = Ptr->getPointeeType();
4097     else {
4098       Diag(Loc, diag::err_bad_memptr_lhs)
4099         << OpSpelling << 1 << LHSType
4100         << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
4101       return QualType();
4102     }
4103   }
4104 
4105   if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
4106     // If we want to check the hierarchy, we need a complete type.
4107     if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
4108                             OpSpelling, (int)isIndirect)) {
4109       return QualType();
4110     }
4111 
4112     if (!IsDerivedFrom(LHSType, Class)) {
4113       Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
4114         << (int)isIndirect << LHS.get()->getType();
4115       return QualType();
4116     }
4117 
4118     CXXCastPath BasePath;
4119     if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
4120                                      SourceRange(LHS.get()->getLocStart(),
4121                                                  RHS.get()->getLocEnd()),
4122                                      &BasePath))
4123       return QualType();
4124 
4125     // Cast LHS to type of use.
4126     QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
4127     ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
4128     LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
4129                             &BasePath);
4130   }
4131 
4132   if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
4133     // Diagnose use of pointer-to-member type which when used as
4134     // the functional cast in a pointer-to-member expression.
4135     Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
4136      return QualType();
4137   }
4138 
4139   // C++ 5.5p2
4140   //   The result is an object or a function of the type specified by the
4141   //   second operand.
4142   // The cv qualifiers are the union of those in the pointer and the left side,
4143   // in accordance with 5.5p5 and 5.2.5.
4144   QualType Result = MemPtr->getPointeeType();
4145   Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
4146 
4147   // C++0x [expr.mptr.oper]p6:
4148   //   In a .* expression whose object expression is an rvalue, the program is
4149   //   ill-formed if the second operand is a pointer to member function with
4150   //   ref-qualifier &. In a ->* expression or in a .* expression whose object
4151   //   expression is an lvalue, the program is ill-formed if the second operand
4152   //   is a pointer to member function with ref-qualifier &&.
4153   if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
4154     switch (Proto->getRefQualifier()) {
4155     case RQ_None:
4156       // Do nothing
4157       break;
4158 
4159     case RQ_LValue:
4160       if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
4161         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4162           << RHSType << 1 << LHS.get()->getSourceRange();
4163       break;
4164 
4165     case RQ_RValue:
4166       if (isIndirect || !LHS.get()->Classify(Context).isRValue())
4167         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4168           << RHSType << 0 << LHS.get()->getSourceRange();
4169       break;
4170     }
4171   }
4172 
4173   // C++ [expr.mptr.oper]p6:
4174   //   The result of a .* expression whose second operand is a pointer
4175   //   to a data member is of the same value category as its
4176   //   first operand. The result of a .* expression whose second
4177   //   operand is a pointer to a member function is a prvalue. The
4178   //   result of an ->* expression is an lvalue if its second operand
4179   //   is a pointer to data member and a prvalue otherwise.
4180   if (Result->isFunctionType()) {
4181     VK = VK_RValue;
4182     return Context.BoundMemberTy;
4183   } else if (isIndirect) {
4184     VK = VK_LValue;
4185   } else {
4186     VK = LHS.get()->getValueKind();
4187   }
4188 
4189   return Result;
4190 }
4191 
4192 /// \brief Try to convert a type to another according to C++0x 5.16p3.
4193 ///
4194 /// This is part of the parameter validation for the ? operator. If either
4195 /// value operand is a class type, the two operands are attempted to be
4196 /// converted to each other. This function does the conversion in one direction.
4197 /// It returns true if the program is ill-formed and has already been diagnosed
4198 /// as such.
TryClassUnification(Sema & Self,Expr * From,Expr * To,SourceLocation QuestionLoc,bool & HaveConversion,QualType & ToType)4199 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
4200                                 SourceLocation QuestionLoc,
4201                                 bool &HaveConversion,
4202                                 QualType &ToType) {
4203   HaveConversion = false;
4204   ToType = To->getType();
4205 
4206   InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
4207                                                            SourceLocation());
4208   // C++0x 5.16p3
4209   //   The process for determining whether an operand expression E1 of type T1
4210   //   can be converted to match an operand expression E2 of type T2 is defined
4211   //   as follows:
4212   //   -- If E2 is an lvalue:
4213   bool ToIsLvalue = To->isLValue();
4214   if (ToIsLvalue) {
4215     //   E1 can be converted to match E2 if E1 can be implicitly converted to
4216     //   type "lvalue reference to T2", subject to the constraint that in the
4217     //   conversion the reference must bind directly to E1.
4218     QualType T = Self.Context.getLValueReferenceType(ToType);
4219     InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4220 
4221     InitializationSequence InitSeq(Self, Entity, Kind, From);
4222     if (InitSeq.isDirectReferenceBinding()) {
4223       ToType = T;
4224       HaveConversion = true;
4225       return false;
4226     }
4227 
4228     if (InitSeq.isAmbiguous())
4229       return InitSeq.Diagnose(Self, Entity, Kind, From);
4230   }
4231 
4232   //   -- If E2 is an rvalue, or if the conversion above cannot be done:
4233   //      -- if E1 and E2 have class type, and the underlying class types are
4234   //         the same or one is a base class of the other:
4235   QualType FTy = From->getType();
4236   QualType TTy = To->getType();
4237   const RecordType *FRec = FTy->getAs<RecordType>();
4238   const RecordType *TRec = TTy->getAs<RecordType>();
4239   bool FDerivedFromT = FRec && TRec && FRec != TRec &&
4240                        Self.IsDerivedFrom(FTy, TTy);
4241   if (FRec && TRec &&
4242       (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
4243     //         E1 can be converted to match E2 if the class of T2 is the
4244     //         same type as, or a base class of, the class of T1, and
4245     //         [cv2 > cv1].
4246     if (FRec == TRec || FDerivedFromT) {
4247       if (TTy.isAtLeastAsQualifiedAs(FTy)) {
4248         InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
4249         InitializationSequence InitSeq(Self, Entity, Kind, From);
4250         if (InitSeq) {
4251           HaveConversion = true;
4252           return false;
4253         }
4254 
4255         if (InitSeq.isAmbiguous())
4256           return InitSeq.Diagnose(Self, Entity, Kind, From);
4257       }
4258     }
4259 
4260     return false;
4261   }
4262 
4263   //     -- Otherwise: E1 can be converted to match E2 if E1 can be
4264   //        implicitly converted to the type that expression E2 would have
4265   //        if E2 were converted to an rvalue (or the type it has, if E2 is
4266   //        an rvalue).
4267   //
4268   // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
4269   // to the array-to-pointer or function-to-pointer conversions.
4270   if (!TTy->getAs<TagType>())
4271     TTy = TTy.getUnqualifiedType();
4272 
4273   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
4274   InitializationSequence InitSeq(Self, Entity, Kind, From);
4275   HaveConversion = !InitSeq.Failed();
4276   ToType = TTy;
4277   if (InitSeq.isAmbiguous())
4278     return InitSeq.Diagnose(Self, Entity, Kind, From);
4279 
4280   return false;
4281 }
4282 
4283 /// \brief Try to find a common type for two according to C++0x 5.16p5.
4284 ///
4285 /// This is part of the parameter validation for the ? operator. If either
4286 /// value operand is a class type, overload resolution is used to find a
4287 /// conversion to a common type.
FindConditionalOverload(Sema & Self,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)4288 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
4289                                     SourceLocation QuestionLoc) {
4290   Expr *Args[2] = { LHS.get(), RHS.get() };
4291   OverloadCandidateSet CandidateSet(QuestionLoc,
4292                                     OverloadCandidateSet::CSK_Operator);
4293   Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
4294                                     CandidateSet);
4295 
4296   OverloadCandidateSet::iterator Best;
4297   switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
4298     case OR_Success: {
4299       // We found a match. Perform the conversions on the arguments and move on.
4300       ExprResult LHSRes =
4301         Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
4302                                        Best->Conversions[0], Sema::AA_Converting);
4303       if (LHSRes.isInvalid())
4304         break;
4305       LHS = LHSRes;
4306 
4307       ExprResult RHSRes =
4308         Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
4309                                        Best->Conversions[1], Sema::AA_Converting);
4310       if (RHSRes.isInvalid())
4311         break;
4312       RHS = RHSRes;
4313       if (Best->Function)
4314         Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
4315       return false;
4316     }
4317 
4318     case OR_No_Viable_Function:
4319 
4320       // Emit a better diagnostic if one of the expressions is a null pointer
4321       // constant and the other is a pointer type. In this case, the user most
4322       // likely forgot to take the address of the other expression.
4323       if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4324         return true;
4325 
4326       Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4327         << LHS.get()->getType() << RHS.get()->getType()
4328         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4329       return true;
4330 
4331     case OR_Ambiguous:
4332       Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
4333         << LHS.get()->getType() << RHS.get()->getType()
4334         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4335       // FIXME: Print the possible common types by printing the return types of
4336       // the viable candidates.
4337       break;
4338 
4339     case OR_Deleted:
4340       llvm_unreachable("Conditional operator has only built-in overloads");
4341   }
4342   return true;
4343 }
4344 
4345 /// \brief Perform an "extended" implicit conversion as returned by
4346 /// TryClassUnification.
ConvertForConditional(Sema & Self,ExprResult & E,QualType T)4347 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
4348   InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4349   InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
4350                                                            SourceLocation());
4351   Expr *Arg = E.get();
4352   InitializationSequence InitSeq(Self, Entity, Kind, Arg);
4353   ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
4354   if (Result.isInvalid())
4355     return true;
4356 
4357   E = Result;
4358   return false;
4359 }
4360 
4361 /// \brief Check the operands of ?: under C++ semantics.
4362 ///
4363 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4364 /// extension. In this case, LHS == Cond. (But they're not aliases.)
CXXCheckConditionalOperands(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation QuestionLoc)4365 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4366                                            ExprResult &RHS, ExprValueKind &VK,
4367                                            ExprObjectKind &OK,
4368                                            SourceLocation QuestionLoc) {
4369   // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4370   // interface pointers.
4371 
4372   // C++11 [expr.cond]p1
4373   //   The first expression is contextually converted to bool.
4374   if (!Cond.get()->isTypeDependent()) {
4375     ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
4376     if (CondRes.isInvalid())
4377       return QualType();
4378     Cond = CondRes;
4379   }
4380 
4381   // Assume r-value.
4382   VK = VK_RValue;
4383   OK = OK_Ordinary;
4384 
4385   // Either of the arguments dependent?
4386   if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
4387     return Context.DependentTy;
4388 
4389   // C++11 [expr.cond]p2
4390   //   If either the second or the third operand has type (cv) void, ...
4391   QualType LTy = LHS.get()->getType();
4392   QualType RTy = RHS.get()->getType();
4393   bool LVoid = LTy->isVoidType();
4394   bool RVoid = RTy->isVoidType();
4395   if (LVoid || RVoid) {
4396     //   ... one of the following shall hold:
4397     //   -- The second or the third operand (but not both) is a (possibly
4398     //      parenthesized) throw-expression; the result is of the type
4399     //      and value category of the other.
4400     bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
4401     bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
4402     if (LThrow != RThrow) {
4403       Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
4404       VK = NonThrow->getValueKind();
4405       // DR (no number yet): the result is a bit-field if the
4406       // non-throw-expression operand is a bit-field.
4407       OK = NonThrow->getObjectKind();
4408       return NonThrow->getType();
4409     }
4410 
4411     //   -- Both the second and third operands have type void; the result is of
4412     //      type void and is a prvalue.
4413     if (LVoid && RVoid)
4414       return Context.VoidTy;
4415 
4416     // Neither holds, error.
4417     Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4418       << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
4419       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4420     return QualType();
4421   }
4422 
4423   // Neither is void.
4424 
4425   // C++11 [expr.cond]p3
4426   //   Otherwise, if the second and third operand have different types, and
4427   //   either has (cv) class type [...] an attempt is made to convert each of
4428   //   those operands to the type of the other.
4429   if (!Context.hasSameType(LTy, RTy) &&
4430       (LTy->isRecordType() || RTy->isRecordType())) {
4431     // These return true if a single direction is already ambiguous.
4432     QualType L2RType, R2LType;
4433     bool HaveL2R, HaveR2L;
4434     if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
4435       return QualType();
4436     if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
4437       return QualType();
4438 
4439     //   If both can be converted, [...] the program is ill-formed.
4440     if (HaveL2R && HaveR2L) {
4441       Diag(QuestionLoc, diag::err_conditional_ambiguous)
4442         << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4443       return QualType();
4444     }
4445 
4446     //   If exactly one conversion is possible, that conversion is applied to
4447     //   the chosen operand and the converted operands are used in place of the
4448     //   original operands for the remainder of this section.
4449     if (HaveL2R) {
4450       if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
4451         return QualType();
4452       LTy = LHS.get()->getType();
4453     } else if (HaveR2L) {
4454       if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
4455         return QualType();
4456       RTy = RHS.get()->getType();
4457     }
4458   }
4459 
4460   // C++11 [expr.cond]p3
4461   //   if both are glvalues of the same value category and the same type except
4462   //   for cv-qualification, an attempt is made to convert each of those
4463   //   operands to the type of the other.
4464   ExprValueKind LVK = LHS.get()->getValueKind();
4465   ExprValueKind RVK = RHS.get()->getValueKind();
4466   if (!Context.hasSameType(LTy, RTy) &&
4467       Context.hasSameUnqualifiedType(LTy, RTy) &&
4468       LVK == RVK && LVK != VK_RValue) {
4469     // Since the unqualified types are reference-related and we require the
4470     // result to be as if a reference bound directly, the only conversion
4471     // we can perform is to add cv-qualifiers.
4472     Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
4473     Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
4474     if (RCVR.isStrictSupersetOf(LCVR)) {
4475       LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
4476       LTy = LHS.get()->getType();
4477     }
4478     else if (LCVR.isStrictSupersetOf(RCVR)) {
4479       RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
4480       RTy = RHS.get()->getType();
4481     }
4482   }
4483 
4484   // C++11 [expr.cond]p4
4485   //   If the second and third operands are glvalues of the same value
4486   //   category and have the same type, the result is of that type and
4487   //   value category and it is a bit-field if the second or the third
4488   //   operand is a bit-field, or if both are bit-fields.
4489   // We only extend this to bitfields, not to the crazy other kinds of
4490   // l-values.
4491   bool Same = Context.hasSameType(LTy, RTy);
4492   if (Same && LVK == RVK && LVK != VK_RValue &&
4493       LHS.get()->isOrdinaryOrBitFieldObject() &&
4494       RHS.get()->isOrdinaryOrBitFieldObject()) {
4495     VK = LHS.get()->getValueKind();
4496     if (LHS.get()->getObjectKind() == OK_BitField ||
4497         RHS.get()->getObjectKind() == OK_BitField)
4498       OK = OK_BitField;
4499     return LTy;
4500   }
4501 
4502   // C++11 [expr.cond]p5
4503   //   Otherwise, the result is a prvalue. If the second and third operands
4504   //   do not have the same type, and either has (cv) class type, ...
4505   if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4506     //   ... overload resolution is used to determine the conversions (if any)
4507     //   to be applied to the operands. If the overload resolution fails, the
4508     //   program is ill-formed.
4509     if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4510       return QualType();
4511   }
4512 
4513   // C++11 [expr.cond]p6
4514   //   Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
4515   //   conversions are performed on the second and third operands.
4516   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
4517   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
4518   if (LHS.isInvalid() || RHS.isInvalid())
4519     return QualType();
4520   LTy = LHS.get()->getType();
4521   RTy = RHS.get()->getType();
4522 
4523   //   After those conversions, one of the following shall hold:
4524   //   -- The second and third operands have the same type; the result
4525   //      is of that type. If the operands have class type, the result
4526   //      is a prvalue temporary of the result type, which is
4527   //      copy-initialized from either the second operand or the third
4528   //      operand depending on the value of the first operand.
4529   if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4530     if (LTy->isRecordType()) {
4531       // The operands have class type. Make a temporary copy.
4532       if (RequireNonAbstractType(QuestionLoc, LTy,
4533                                  diag::err_allocation_of_abstract_type))
4534         return QualType();
4535       InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
4536 
4537       ExprResult LHSCopy = PerformCopyInitialization(Entity,
4538                                                      SourceLocation(),
4539                                                      LHS);
4540       if (LHSCopy.isInvalid())
4541         return QualType();
4542 
4543       ExprResult RHSCopy = PerformCopyInitialization(Entity,
4544                                                      SourceLocation(),
4545                                                      RHS);
4546       if (RHSCopy.isInvalid())
4547         return QualType();
4548 
4549       LHS = LHSCopy;
4550       RHS = RHSCopy;
4551     }
4552 
4553     return LTy;
4554   }
4555 
4556   // Extension: conditional operator involving vector types.
4557   if (LTy->isVectorType() || RTy->isVectorType())
4558     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4559 
4560   //   -- The second and third operands have arithmetic or enumeration type;
4561   //      the usual arithmetic conversions are performed to bring them to a
4562   //      common type, and the result is of that type.
4563   if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4564     UsualArithmeticConversions(LHS, RHS);
4565     if (LHS.isInvalid() || RHS.isInvalid())
4566       return QualType();
4567     return LHS.get()->getType();
4568   }
4569 
4570   //   -- The second and third operands have pointer type, or one has pointer
4571   //      type and the other is a null pointer constant, or both are null
4572   //      pointer constants, at least one of which is non-integral; pointer
4573   //      conversions and qualification conversions are performed to bring them
4574   //      to their composite pointer type. The result is of the composite
4575   //      pointer type.
4576   //   -- The second and third operands have pointer to member type, or one has
4577   //      pointer to member type and the other is a null pointer constant;
4578   //      pointer to member conversions and qualification conversions are
4579   //      performed to bring them to a common type, whose cv-qualification
4580   //      shall match the cv-qualification of either the second or the third
4581   //      operand. The result is of the common type.
4582   bool NonStandardCompositeType = false;
4583   QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
4584                                  isSFINAEContext() ? nullptr
4585                                                    : &NonStandardCompositeType);
4586   if (!Composite.isNull()) {
4587     if (NonStandardCompositeType)
4588       Diag(QuestionLoc,
4589            diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4590         << LTy << RTy << Composite
4591         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4592 
4593     return Composite;
4594   }
4595 
4596   // Similarly, attempt to find composite type of two objective-c pointers.
4597   Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4598   if (!Composite.isNull())
4599     return Composite;
4600 
4601   // Check if we are using a null with a non-pointer type.
4602   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4603     return QualType();
4604 
4605   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4606     << LHS.get()->getType() << RHS.get()->getType()
4607     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4608   return QualType();
4609 }
4610 
4611 /// \brief Find a merged pointer type and convert the two expressions to it.
4612 ///
4613 /// This finds the composite pointer type (or member pointer type) for @p E1
4614 /// and @p E2 according to C++11 5.9p2. It converts both expressions to this
4615 /// type and returns it.
4616 /// It does not emit diagnostics.
4617 ///
4618 /// \param Loc The location of the operator requiring these two expressions to
4619 /// be converted to the composite pointer type.
4620 ///
4621 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4622 /// a non-standard (but still sane) composite type to which both expressions
4623 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4624 /// will be set true.
FindCompositePointerType(SourceLocation Loc,Expr * & E1,Expr * & E2,bool * NonStandardCompositeType)4625 QualType Sema::FindCompositePointerType(SourceLocation Loc,
4626                                         Expr *&E1, Expr *&E2,
4627                                         bool *NonStandardCompositeType) {
4628   if (NonStandardCompositeType)
4629     *NonStandardCompositeType = false;
4630 
4631   assert(getLangOpts().CPlusPlus && "This function assumes C++");
4632   QualType T1 = E1->getType(), T2 = E2->getType();
4633 
4634   // C++11 5.9p2
4635   //   Pointer conversions and qualification conversions are performed on
4636   //   pointer operands to bring them to their composite pointer type. If
4637   //   one operand is a null pointer constant, the composite pointer type is
4638   //   std::nullptr_t if the other operand is also a null pointer constant or,
4639   //   if the other operand is a pointer, the type of the other operand.
4640   if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4641       !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
4642     if (T1->isNullPtrType() &&
4643         E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4644       E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
4645       return T1;
4646     }
4647     if (T2->isNullPtrType() &&
4648         E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4649       E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
4650       return T2;
4651     }
4652     return QualType();
4653   }
4654 
4655   if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4656     if (T2->isMemberPointerType())
4657       E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).get();
4658     else
4659       E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
4660     return T2;
4661   }
4662   if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4663     if (T1->isMemberPointerType())
4664       E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).get();
4665     else
4666       E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
4667     return T1;
4668   }
4669 
4670   // Now both have to be pointers or member pointers.
4671   if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4672       (!T2->isPointerType() && !T2->isMemberPointerType()))
4673     return QualType();
4674 
4675   //   Otherwise, of one of the operands has type "pointer to cv1 void," then
4676   //   the other has type "pointer to cv2 T" and the composite pointer type is
4677   //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4678   //   Otherwise, the composite pointer type is a pointer type similar to the
4679   //   type of one of the operands, with a cv-qualification signature that is
4680   //   the union of the cv-qualification signatures of the operand types.
4681   // In practice, the first part here is redundant; it's subsumed by the second.
4682   // What we do here is, we build the two possible composite types, and try the
4683   // conversions in both directions. If only one works, or if the two composite
4684   // types are the same, we have succeeded.
4685   // FIXME: extended qualifiers?
4686   typedef SmallVector<unsigned, 4> QualifierVector;
4687   QualifierVector QualifierUnion;
4688   typedef SmallVector<std::pair<const Type *, const Type *>, 4>
4689       ContainingClassVector;
4690   ContainingClassVector MemberOfClass;
4691   QualType Composite1 = Context.getCanonicalType(T1),
4692            Composite2 = Context.getCanonicalType(T2);
4693   unsigned NeedConstBefore = 0;
4694   do {
4695     const PointerType *Ptr1, *Ptr2;
4696     if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4697         (Ptr2 = Composite2->getAs<PointerType>())) {
4698       Composite1 = Ptr1->getPointeeType();
4699       Composite2 = Ptr2->getPointeeType();
4700 
4701       // If we're allowed to create a non-standard composite type, keep track
4702       // of where we need to fill in additional 'const' qualifiers.
4703       if (NonStandardCompositeType &&
4704           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4705         NeedConstBefore = QualifierUnion.size();
4706 
4707       QualifierUnion.push_back(
4708                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4709       MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
4710       continue;
4711     }
4712 
4713     const MemberPointerType *MemPtr1, *MemPtr2;
4714     if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4715         (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4716       Composite1 = MemPtr1->getPointeeType();
4717       Composite2 = MemPtr2->getPointeeType();
4718 
4719       // If we're allowed to create a non-standard composite type, keep track
4720       // of where we need to fill in additional 'const' qualifiers.
4721       if (NonStandardCompositeType &&
4722           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4723         NeedConstBefore = QualifierUnion.size();
4724 
4725       QualifierUnion.push_back(
4726                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4727       MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4728                                              MemPtr2->getClass()));
4729       continue;
4730     }
4731 
4732     // FIXME: block pointer types?
4733 
4734     // Cannot unwrap any more types.
4735     break;
4736   } while (true);
4737 
4738   if (NeedConstBefore && NonStandardCompositeType) {
4739     // Extension: Add 'const' to qualifiers that come before the first qualifier
4740     // mismatch, so that our (non-standard!) composite type meets the
4741     // requirements of C++ [conv.qual]p4 bullet 3.
4742     for (unsigned I = 0; I != NeedConstBefore; ++I) {
4743       if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4744         QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4745         *NonStandardCompositeType = true;
4746       }
4747     }
4748   }
4749 
4750   // Rewrap the composites as pointers or member pointers with the union CVRs.
4751   ContainingClassVector::reverse_iterator MOC
4752     = MemberOfClass.rbegin();
4753   for (QualifierVector::reverse_iterator
4754          I = QualifierUnion.rbegin(),
4755          E = QualifierUnion.rend();
4756        I != E; (void)++I, ++MOC) {
4757     Qualifiers Quals = Qualifiers::fromCVRMask(*I);
4758     if (MOC->first && MOC->second) {
4759       // Rebuild member pointer type
4760       Composite1 = Context.getMemberPointerType(
4761                                     Context.getQualifiedType(Composite1, Quals),
4762                                     MOC->first);
4763       Composite2 = Context.getMemberPointerType(
4764                                     Context.getQualifiedType(Composite2, Quals),
4765                                     MOC->second);
4766     } else {
4767       // Rebuild pointer type
4768       Composite1
4769         = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4770       Composite2
4771         = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
4772     }
4773   }
4774 
4775   // Try to convert to the first composite pointer type.
4776   InitializedEntity Entity1
4777     = InitializedEntity::InitializeTemporary(Composite1);
4778   InitializationKind Kind
4779     = InitializationKind::CreateCopy(Loc, SourceLocation());
4780   InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
4781   InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
4782 
4783   if (E1ToC1 && E2ToC1) {
4784     // Conversion to Composite1 is viable.
4785     if (!Context.hasSameType(Composite1, Composite2)) {
4786       // Composite2 is a different type from Composite1. Check whether
4787       // Composite2 is also viable.
4788       InitializedEntity Entity2
4789         = InitializedEntity::InitializeTemporary(Composite2);
4790       InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4791       InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
4792       if (E1ToC2 && E2ToC2) {
4793         // Both Composite1 and Composite2 are viable and are different;
4794         // this is an ambiguity.
4795         return QualType();
4796       }
4797     }
4798 
4799     // Convert E1 to Composite1
4800     ExprResult E1Result
4801       = E1ToC1.Perform(*this, Entity1, Kind, E1);
4802     if (E1Result.isInvalid())
4803       return QualType();
4804     E1 = E1Result.getAs<Expr>();
4805 
4806     // Convert E2 to Composite1
4807     ExprResult E2Result
4808       = E2ToC1.Perform(*this, Entity1, Kind, E2);
4809     if (E2Result.isInvalid())
4810       return QualType();
4811     E2 = E2Result.getAs<Expr>();
4812 
4813     return Composite1;
4814   }
4815 
4816   // Check whether Composite2 is viable.
4817   InitializedEntity Entity2
4818     = InitializedEntity::InitializeTemporary(Composite2);
4819   InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4820   InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
4821   if (!E1ToC2 || !E2ToC2)
4822     return QualType();
4823 
4824   // Convert E1 to Composite2
4825   ExprResult E1Result
4826     = E1ToC2.Perform(*this, Entity2, Kind, E1);
4827   if (E1Result.isInvalid())
4828     return QualType();
4829   E1 = E1Result.getAs<Expr>();
4830 
4831   // Convert E2 to Composite2
4832   ExprResult E2Result
4833     = E2ToC2.Perform(*this, Entity2, Kind, E2);
4834   if (E2Result.isInvalid())
4835     return QualType();
4836   E2 = E2Result.getAs<Expr>();
4837 
4838   return Composite2;
4839 }
4840 
MaybeBindToTemporary(Expr * E)4841 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
4842   if (!E)
4843     return ExprError();
4844 
4845   assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4846 
4847   // If the result is a glvalue, we shouldn't bind it.
4848   if (!E->isRValue())
4849     return E;
4850 
4851   // In ARC, calls that return a retainable type can return retained,
4852   // in which case we have to insert a consuming cast.
4853   if (getLangOpts().ObjCAutoRefCount &&
4854       E->getType()->isObjCRetainableType()) {
4855 
4856     bool ReturnsRetained;
4857 
4858     // For actual calls, we compute this by examining the type of the
4859     // called value.
4860     if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4861       Expr *Callee = Call->getCallee()->IgnoreParens();
4862       QualType T = Callee->getType();
4863 
4864       if (T == Context.BoundMemberTy) {
4865         // Handle pointer-to-members.
4866         if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4867           T = BinOp->getRHS()->getType();
4868         else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4869           T = Mem->getMemberDecl()->getType();
4870       }
4871 
4872       if (const PointerType *Ptr = T->getAs<PointerType>())
4873         T = Ptr->getPointeeType();
4874       else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4875         T = Ptr->getPointeeType();
4876       else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4877         T = MemPtr->getPointeeType();
4878 
4879       const FunctionType *FTy = T->getAs<FunctionType>();
4880       assert(FTy && "call to value not of function type?");
4881       ReturnsRetained = FTy->getExtInfo().getProducesResult();
4882 
4883     // ActOnStmtExpr arranges things so that StmtExprs of retainable
4884     // type always produce a +1 object.
4885     } else if (isa<StmtExpr>(E)) {
4886       ReturnsRetained = true;
4887 
4888     // We hit this case with the lambda conversion-to-block optimization;
4889     // we don't want any extra casts here.
4890     } else if (isa<CastExpr>(E) &&
4891                isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4892       return E;
4893 
4894     // For message sends and property references, we try to find an
4895     // actual method.  FIXME: we should infer retention by selector in
4896     // cases where we don't have an actual method.
4897     } else {
4898       ObjCMethodDecl *D = nullptr;
4899       if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4900         D = Send->getMethodDecl();
4901       } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4902         D = BoxedExpr->getBoxingMethod();
4903       } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4904         D = ArrayLit->getArrayWithObjectsMethod();
4905       } else if (ObjCDictionaryLiteral *DictLit
4906                                         = dyn_cast<ObjCDictionaryLiteral>(E)) {
4907         D = DictLit->getDictWithObjectsMethod();
4908       }
4909 
4910       ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
4911 
4912       // Don't do reclaims on performSelector calls; despite their
4913       // return type, the invoked method doesn't necessarily actually
4914       // return an object.
4915       if (!ReturnsRetained &&
4916           D && D->getMethodFamily() == OMF_performSelector)
4917         return E;
4918     }
4919 
4920     // Don't reclaim an object of Class type.
4921     if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4922       return E;
4923 
4924     ExprNeedsCleanups = true;
4925 
4926     CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4927                                    : CK_ARCReclaimReturnedObject);
4928     return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
4929                                     VK_RValue);
4930   }
4931 
4932   if (!getLangOpts().CPlusPlus)
4933     return E;
4934 
4935   // Search for the base element type (cf. ASTContext::getBaseElementType) with
4936   // a fast path for the common case that the type is directly a RecordType.
4937   const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4938   const RecordType *RT = nullptr;
4939   while (!RT) {
4940     switch (T->getTypeClass()) {
4941     case Type::Record:
4942       RT = cast<RecordType>(T);
4943       break;
4944     case Type::ConstantArray:
4945     case Type::IncompleteArray:
4946     case Type::VariableArray:
4947     case Type::DependentSizedArray:
4948       T = cast<ArrayType>(T)->getElementType().getTypePtr();
4949       break;
4950     default:
4951       return E;
4952     }
4953   }
4954 
4955   // That should be enough to guarantee that this type is complete, if we're
4956   // not processing a decltype expression.
4957   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4958   if (RD->isInvalidDecl() || RD->isDependentContext())
4959     return E;
4960 
4961   bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4962   CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
4963 
4964   if (Destructor) {
4965     MarkFunctionReferenced(E->getExprLoc(), Destructor);
4966     CheckDestructorAccess(E->getExprLoc(), Destructor,
4967                           PDiag(diag::err_access_dtor_temp)
4968                             << E->getType());
4969     if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
4970       return ExprError();
4971 
4972     // If destructor is trivial, we can avoid the extra copy.
4973     if (Destructor->isTrivial())
4974       return E;
4975 
4976     // We need a cleanup, but we don't need to remember the temporary.
4977     ExprNeedsCleanups = true;
4978   }
4979 
4980   CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4981   CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
4982 
4983   if (IsDecltype)
4984     ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
4985 
4986   return Bind;
4987 }
4988 
4989 ExprResult
MaybeCreateExprWithCleanups(ExprResult SubExpr)4990 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
4991   if (SubExpr.isInvalid())
4992     return ExprError();
4993 
4994   return MaybeCreateExprWithCleanups(SubExpr.get());
4995 }
4996 
MaybeCreateExprWithCleanups(Expr * SubExpr)4997 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4998   assert(SubExpr && "subexpression can't be null!");
4999 
5000   CleanupVarDeclMarking();
5001 
5002   unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
5003   assert(ExprCleanupObjects.size() >= FirstCleanup);
5004   assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
5005   if (!ExprNeedsCleanups)
5006     return SubExpr;
5007 
5008   ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
5009     = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
5010                          ExprCleanupObjects.size() - FirstCleanup);
5011 
5012   Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
5013   DiscardCleanupsInEvaluationContext();
5014 
5015   return E;
5016 }
5017 
MaybeCreateStmtWithCleanups(Stmt * SubStmt)5018 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
5019   assert(SubStmt && "sub-statement can't be null!");
5020 
5021   CleanupVarDeclMarking();
5022 
5023   if (!ExprNeedsCleanups)
5024     return SubStmt;
5025 
5026   // FIXME: In order to attach the temporaries, wrap the statement into
5027   // a StmtExpr; currently this is only used for asm statements.
5028   // This is hacky, either create a new CXXStmtWithTemporaries statement or
5029   // a new AsmStmtWithTemporaries.
5030   CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
5031                                                       SourceLocation(),
5032                                                       SourceLocation());
5033   Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
5034                                    SourceLocation());
5035   return MaybeCreateExprWithCleanups(E);
5036 }
5037 
5038 /// Process the expression contained within a decltype. For such expressions,
5039 /// certain semantic checks on temporaries are delayed until this point, and
5040 /// are omitted for the 'topmost' call in the decltype expression. If the
5041 /// topmost call bound a temporary, strip that temporary off the expression.
ActOnDecltypeExpression(Expr * E)5042 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
5043   assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
5044 
5045   // C++11 [expr.call]p11:
5046   //   If a function call is a prvalue of object type,
5047   // -- if the function call is either
5048   //   -- the operand of a decltype-specifier, or
5049   //   -- the right operand of a comma operator that is the operand of a
5050   //      decltype-specifier,
5051   //   a temporary object is not introduced for the prvalue.
5052 
5053   // Recursively rebuild ParenExprs and comma expressions to strip out the
5054   // outermost CXXBindTemporaryExpr, if any.
5055   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5056     ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
5057     if (SubExpr.isInvalid())
5058       return ExprError();
5059     if (SubExpr.get() == PE->getSubExpr())
5060       return E;
5061     return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
5062   }
5063   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5064     if (BO->getOpcode() == BO_Comma) {
5065       ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
5066       if (RHS.isInvalid())
5067         return ExprError();
5068       if (RHS.get() == BO->getRHS())
5069         return E;
5070       return new (Context) BinaryOperator(
5071           BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
5072           BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
5073     }
5074   }
5075 
5076   CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
5077   CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
5078                               : nullptr;
5079   if (TopCall)
5080     E = TopCall;
5081   else
5082     TopBind = nullptr;
5083 
5084   // Disable the special decltype handling now.
5085   ExprEvalContexts.back().IsDecltype = false;
5086 
5087   // In MS mode, don't perform any extra checking of call return types within a
5088   // decltype expression.
5089   if (getLangOpts().MSVCCompat)
5090     return E;
5091 
5092   // Perform the semantic checks we delayed until this point.
5093   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
5094        I != N; ++I) {
5095     CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
5096     if (Call == TopCall)
5097       continue;
5098 
5099     if (CheckCallReturnType(Call->getCallReturnType(),
5100                             Call->getLocStart(),
5101                             Call, Call->getDirectCallee()))
5102       return ExprError();
5103   }
5104 
5105   // Now all relevant types are complete, check the destructors are accessible
5106   // and non-deleted, and annotate them on the temporaries.
5107   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
5108        I != N; ++I) {
5109     CXXBindTemporaryExpr *Bind =
5110       ExprEvalContexts.back().DelayedDecltypeBinds[I];
5111     if (Bind == TopBind)
5112       continue;
5113 
5114     CXXTemporary *Temp = Bind->getTemporary();
5115 
5116     CXXRecordDecl *RD =
5117       Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5118     CXXDestructorDecl *Destructor = LookupDestructor(RD);
5119     Temp->setDestructor(Destructor);
5120 
5121     MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
5122     CheckDestructorAccess(Bind->getExprLoc(), Destructor,
5123                           PDiag(diag::err_access_dtor_temp)
5124                             << Bind->getType());
5125     if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
5126       return ExprError();
5127 
5128     // We need a cleanup, but we don't need to remember the temporary.
5129     ExprNeedsCleanups = true;
5130   }
5131 
5132   // Possibly strip off the top CXXBindTemporaryExpr.
5133   return E;
5134 }
5135 
5136 /// Note a set of 'operator->' functions that were used for a member access.
noteOperatorArrows(Sema & S,ArrayRef<FunctionDecl * > OperatorArrows)5137 static void noteOperatorArrows(Sema &S,
5138                                ArrayRef<FunctionDecl *> OperatorArrows) {
5139   unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
5140   // FIXME: Make this configurable?
5141   unsigned Limit = 9;
5142   if (OperatorArrows.size() > Limit) {
5143     // Produce Limit-1 normal notes and one 'skipping' note.
5144     SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
5145     SkipCount = OperatorArrows.size() - (Limit - 1);
5146   }
5147 
5148   for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
5149     if (I == SkipStart) {
5150       S.Diag(OperatorArrows[I]->getLocation(),
5151              diag::note_operator_arrows_suppressed)
5152           << SkipCount;
5153       I += SkipCount;
5154     } else {
5155       S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
5156           << OperatorArrows[I]->getCallResultType();
5157       ++I;
5158     }
5159   }
5160 }
5161 
5162 ExprResult
ActOnStartCXXMemberReference(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,ParsedType & ObjectType,bool & MayBePseudoDestructor)5163 Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
5164                                    tok::TokenKind OpKind, ParsedType &ObjectType,
5165                                    bool &MayBePseudoDestructor) {
5166   // Since this might be a postfix expression, get rid of ParenListExprs.
5167   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
5168   if (Result.isInvalid()) return ExprError();
5169   Base = Result.get();
5170 
5171   Result = CheckPlaceholderExpr(Base);
5172   if (Result.isInvalid()) return ExprError();
5173   Base = Result.get();
5174 
5175   QualType BaseType = Base->getType();
5176   MayBePseudoDestructor = false;
5177   if (BaseType->isDependentType()) {
5178     // If we have a pointer to a dependent type and are using the -> operator,
5179     // the object type is the type that the pointer points to. We might still
5180     // have enough information about that type to do something useful.
5181     if (OpKind == tok::arrow)
5182       if (const PointerType *Ptr = BaseType->getAs<PointerType>())
5183         BaseType = Ptr->getPointeeType();
5184 
5185     ObjectType = ParsedType::make(BaseType);
5186     MayBePseudoDestructor = true;
5187     return Base;
5188   }
5189 
5190   // C++ [over.match.oper]p8:
5191   //   [...] When operator->returns, the operator-> is applied  to the value
5192   //   returned, with the original second operand.
5193   if (OpKind == tok::arrow) {
5194     QualType StartingType = BaseType;
5195     bool NoArrowOperatorFound = false;
5196     bool FirstIteration = true;
5197     FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
5198     // The set of types we've considered so far.
5199     llvm::SmallPtrSet<CanQualType,8> CTypes;
5200     SmallVector<FunctionDecl*, 8> OperatorArrows;
5201     CTypes.insert(Context.getCanonicalType(BaseType));
5202 
5203     while (BaseType->isRecordType()) {
5204       if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
5205         Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
5206           << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
5207         noteOperatorArrows(*this, OperatorArrows);
5208         Diag(OpLoc, diag::note_operator_arrow_depth)
5209           << getLangOpts().ArrowDepth;
5210         return ExprError();
5211       }
5212 
5213       Result = BuildOverloadedArrowExpr(
5214           S, Base, OpLoc,
5215           // When in a template specialization and on the first loop iteration,
5216           // potentially give the default diagnostic (with the fixit in a
5217           // separate note) instead of having the error reported back to here
5218           // and giving a diagnostic with a fixit attached to the error itself.
5219           (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
5220               ? nullptr
5221               : &NoArrowOperatorFound);
5222       if (Result.isInvalid()) {
5223         if (NoArrowOperatorFound) {
5224           if (FirstIteration) {
5225             Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5226               << BaseType << 1 << Base->getSourceRange()
5227               << FixItHint::CreateReplacement(OpLoc, ".");
5228             OpKind = tok::period;
5229             break;
5230           }
5231           Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5232             << BaseType << Base->getSourceRange();
5233           CallExpr *CE = dyn_cast<CallExpr>(Base);
5234           if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
5235             Diag(CD->getLocStart(),
5236                  diag::note_member_reference_arrow_from_operator_arrow);
5237           }
5238         }
5239         return ExprError();
5240       }
5241       Base = Result.get();
5242       if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
5243         OperatorArrows.push_back(OpCall->getDirectCallee());
5244       BaseType = Base->getType();
5245       CanQualType CBaseType = Context.getCanonicalType(BaseType);
5246       if (!CTypes.insert(CBaseType)) {
5247         Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
5248         noteOperatorArrows(*this, OperatorArrows);
5249         return ExprError();
5250       }
5251       FirstIteration = false;
5252     }
5253 
5254     if (OpKind == tok::arrow &&
5255         (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
5256       BaseType = BaseType->getPointeeType();
5257   }
5258 
5259   // Objective-C properties allow "." access on Objective-C pointer types,
5260   // so adjust the base type to the object type itself.
5261   if (BaseType->isObjCObjectPointerType())
5262     BaseType = BaseType->getPointeeType();
5263 
5264   // C++ [basic.lookup.classref]p2:
5265   //   [...] If the type of the object expression is of pointer to scalar
5266   //   type, the unqualified-id is looked up in the context of the complete
5267   //   postfix-expression.
5268   //
5269   // This also indicates that we could be parsing a pseudo-destructor-name.
5270   // Note that Objective-C class and object types can be pseudo-destructor
5271   // expressions or normal member (ivar or property) access expressions.
5272   if (BaseType->isObjCObjectOrInterfaceType()) {
5273     MayBePseudoDestructor = true;
5274   } else if (!BaseType->isRecordType()) {
5275     ObjectType = ParsedType();
5276     MayBePseudoDestructor = true;
5277     return Base;
5278   }
5279 
5280   // The object type must be complete (or dependent), or
5281   // C++11 [expr.prim.general]p3:
5282   //   Unlike the object expression in other contexts, *this is not required to
5283   //   be of complete type for purposes of class member access (5.2.5) outside
5284   //   the member function body.
5285   if (!BaseType->isDependentType() &&
5286       !isThisOutsideMemberFunctionBody(BaseType) &&
5287       RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
5288     return ExprError();
5289 
5290   // C++ [basic.lookup.classref]p2:
5291   //   If the id-expression in a class member access (5.2.5) is an
5292   //   unqualified-id, and the type of the object expression is of a class
5293   //   type C (or of pointer to a class type C), the unqualified-id is looked
5294   //   up in the scope of class C. [...]
5295   ObjectType = ParsedType::make(BaseType);
5296   return Base;
5297 }
5298 
DiagnoseDtorReference(SourceLocation NameLoc,Expr * MemExpr)5299 ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
5300                                                    Expr *MemExpr) {
5301   SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
5302   Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
5303     << isa<CXXPseudoDestructorExpr>(MemExpr)
5304     << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
5305 
5306   return ActOnCallExpr(/*Scope*/ nullptr,
5307                        MemExpr,
5308                        /*LPLoc*/ ExpectedLParenLoc,
5309                        None,
5310                        /*RPLoc*/ ExpectedLParenLoc);
5311 }
5312 
CheckArrow(Sema & S,QualType & ObjectType,Expr * & Base,tok::TokenKind & OpKind,SourceLocation OpLoc)5313 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
5314                    tok::TokenKind& OpKind, SourceLocation OpLoc) {
5315   if (Base->hasPlaceholderType()) {
5316     ExprResult result = S.CheckPlaceholderExpr(Base);
5317     if (result.isInvalid()) return true;
5318     Base = result.get();
5319   }
5320   ObjectType = Base->getType();
5321 
5322   // C++ [expr.pseudo]p2:
5323   //   The left-hand side of the dot operator shall be of scalar type. The
5324   //   left-hand side of the arrow operator shall be of pointer to scalar type.
5325   //   This scalar type is the object type.
5326   // Note that this is rather different from the normal handling for the
5327   // arrow operator.
5328   if (OpKind == tok::arrow) {
5329     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
5330       ObjectType = Ptr->getPointeeType();
5331     } else if (!Base->isTypeDependent()) {
5332       // The user wrote "p->" when she probably meant "p."; fix it.
5333       S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5334         << ObjectType << true
5335         << FixItHint::CreateReplacement(OpLoc, ".");
5336       if (S.isSFINAEContext())
5337         return true;
5338 
5339       OpKind = tok::period;
5340     }
5341   }
5342 
5343   return false;
5344 }
5345 
BuildPseudoDestructorExpr(Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,const CXXScopeSpec & SS,TypeSourceInfo * ScopeTypeInfo,SourceLocation CCLoc,SourceLocation TildeLoc,PseudoDestructorTypeStorage Destructed,bool HasTrailingLParen)5346 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
5347                                            SourceLocation OpLoc,
5348                                            tok::TokenKind OpKind,
5349                                            const CXXScopeSpec &SS,
5350                                            TypeSourceInfo *ScopeTypeInfo,
5351                                            SourceLocation CCLoc,
5352                                            SourceLocation TildeLoc,
5353                                          PseudoDestructorTypeStorage Destructed,
5354                                            bool HasTrailingLParen) {
5355   TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
5356 
5357   QualType ObjectType;
5358   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5359     return ExprError();
5360 
5361   if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
5362       !ObjectType->isVectorType()) {
5363     if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
5364       Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
5365     else {
5366       Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
5367         << ObjectType << Base->getSourceRange();
5368       return ExprError();
5369     }
5370   }
5371 
5372   // C++ [expr.pseudo]p2:
5373   //   [...] The cv-unqualified versions of the object type and of the type
5374   //   designated by the pseudo-destructor-name shall be the same type.
5375   if (DestructedTypeInfo) {
5376     QualType DestructedType = DestructedTypeInfo->getType();
5377     SourceLocation DestructedTypeStart
5378       = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
5379     if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
5380       if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
5381         Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
5382           << ObjectType << DestructedType << Base->getSourceRange()
5383           << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5384 
5385         // Recover by setting the destructed type to the object type.
5386         DestructedType = ObjectType;
5387         DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5388                                                            DestructedTypeStart);
5389         Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5390       } else if (DestructedType.getObjCLifetime() !=
5391                                                 ObjectType.getObjCLifetime()) {
5392 
5393         if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
5394           // Okay: just pretend that the user provided the correctly-qualified
5395           // type.
5396         } else {
5397           Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
5398             << ObjectType << DestructedType << Base->getSourceRange()
5399             << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5400         }
5401 
5402         // Recover by setting the destructed type to the object type.
5403         DestructedType = ObjectType;
5404         DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5405                                                            DestructedTypeStart);
5406         Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5407       }
5408     }
5409   }
5410 
5411   // C++ [expr.pseudo]p2:
5412   //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
5413   //   form
5414   //
5415   //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
5416   //
5417   //   shall designate the same scalar type.
5418   if (ScopeTypeInfo) {
5419     QualType ScopeType = ScopeTypeInfo->getType();
5420     if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
5421         !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
5422 
5423       Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
5424            diag::err_pseudo_dtor_type_mismatch)
5425         << ObjectType << ScopeType << Base->getSourceRange()
5426         << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
5427 
5428       ScopeType = QualType();
5429       ScopeTypeInfo = nullptr;
5430     }
5431   }
5432 
5433   Expr *Result
5434     = new (Context) CXXPseudoDestructorExpr(Context, Base,
5435                                             OpKind == tok::arrow, OpLoc,
5436                                             SS.getWithLocInContext(Context),
5437                                             ScopeTypeInfo,
5438                                             CCLoc,
5439                                             TildeLoc,
5440                                             Destructed);
5441 
5442   if (HasTrailingLParen)
5443     return Result;
5444 
5445   return DiagnoseDtorReference(Destructed.getLocation(), Result);
5446 }
5447 
ActOnPseudoDestructorExpr(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,CXXScopeSpec & SS,UnqualifiedId & FirstTypeName,SourceLocation CCLoc,SourceLocation TildeLoc,UnqualifiedId & SecondTypeName,bool HasTrailingLParen)5448 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5449                                            SourceLocation OpLoc,
5450                                            tok::TokenKind OpKind,
5451                                            CXXScopeSpec &SS,
5452                                            UnqualifiedId &FirstTypeName,
5453                                            SourceLocation CCLoc,
5454                                            SourceLocation TildeLoc,
5455                                            UnqualifiedId &SecondTypeName,
5456                                            bool HasTrailingLParen) {
5457   assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5458           FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5459          "Invalid first type name in pseudo-destructor");
5460   assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5461           SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5462          "Invalid second type name in pseudo-destructor");
5463 
5464   QualType ObjectType;
5465   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5466     return ExprError();
5467 
5468   // Compute the object type that we should use for name lookup purposes. Only
5469   // record types and dependent types matter.
5470   ParsedType ObjectTypePtrForLookup;
5471   if (!SS.isSet()) {
5472     if (ObjectType->isRecordType())
5473       ObjectTypePtrForLookup = ParsedType::make(ObjectType);
5474     else if (ObjectType->isDependentType())
5475       ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
5476   }
5477 
5478   // Convert the name of the type being destructed (following the ~) into a
5479   // type (with source-location information).
5480   QualType DestructedType;
5481   TypeSourceInfo *DestructedTypeInfo = nullptr;
5482   PseudoDestructorTypeStorage Destructed;
5483   if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5484     ParsedType T = getTypeName(*SecondTypeName.Identifier,
5485                                SecondTypeName.StartLocation,
5486                                S, &SS, true, false, ObjectTypePtrForLookup);
5487     if (!T &&
5488         ((SS.isSet() && !computeDeclContext(SS, false)) ||
5489          (!SS.isSet() && ObjectType->isDependentType()))) {
5490       // The name of the type being destroyed is a dependent name, and we
5491       // couldn't find anything useful in scope. Just store the identifier and
5492       // it's location, and we'll perform (qualified) name lookup again at
5493       // template instantiation time.
5494       Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5495                                                SecondTypeName.StartLocation);
5496     } else if (!T) {
5497       Diag(SecondTypeName.StartLocation,
5498            diag::err_pseudo_dtor_destructor_non_type)
5499         << SecondTypeName.Identifier << ObjectType;
5500       if (isSFINAEContext())
5501         return ExprError();
5502 
5503       // Recover by assuming we had the right type all along.
5504       DestructedType = ObjectType;
5505     } else
5506       DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
5507   } else {
5508     // Resolve the template-id to a type.
5509     TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
5510     ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5511                                        TemplateId->NumArgs);
5512     TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5513                                        TemplateId->TemplateKWLoc,
5514                                        TemplateId->Template,
5515                                        TemplateId->TemplateNameLoc,
5516                                        TemplateId->LAngleLoc,
5517                                        TemplateArgsPtr,
5518                                        TemplateId->RAngleLoc);
5519     if (T.isInvalid() || !T.get()) {
5520       // Recover by assuming we had the right type all along.
5521       DestructedType = ObjectType;
5522     } else
5523       DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
5524   }
5525 
5526   // If we've performed some kind of recovery, (re-)build the type source
5527   // information.
5528   if (!DestructedType.isNull()) {
5529     if (!DestructedTypeInfo)
5530       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
5531                                                   SecondTypeName.StartLocation);
5532     Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5533   }
5534 
5535   // Convert the name of the scope type (the type prior to '::') into a type.
5536   TypeSourceInfo *ScopeTypeInfo = nullptr;
5537   QualType ScopeType;
5538   if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5539       FirstTypeName.Identifier) {
5540     if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5541       ParsedType T = getTypeName(*FirstTypeName.Identifier,
5542                                  FirstTypeName.StartLocation,
5543                                  S, &SS, true, false, ObjectTypePtrForLookup);
5544       if (!T) {
5545         Diag(FirstTypeName.StartLocation,
5546              diag::err_pseudo_dtor_destructor_non_type)
5547           << FirstTypeName.Identifier << ObjectType;
5548 
5549         if (isSFINAEContext())
5550           return ExprError();
5551 
5552         // Just drop this type. It's unnecessary anyway.
5553         ScopeType = QualType();
5554       } else
5555         ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
5556     } else {
5557       // Resolve the template-id to a type.
5558       TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
5559       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5560                                          TemplateId->NumArgs);
5561       TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5562                                          TemplateId->TemplateKWLoc,
5563                                          TemplateId->Template,
5564                                          TemplateId->TemplateNameLoc,
5565                                          TemplateId->LAngleLoc,
5566                                          TemplateArgsPtr,
5567                                          TemplateId->RAngleLoc);
5568       if (T.isInvalid() || !T.get()) {
5569         // Recover by dropping this type.
5570         ScopeType = QualType();
5571       } else
5572         ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
5573     }
5574   }
5575 
5576   if (!ScopeType.isNull() && !ScopeTypeInfo)
5577     ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5578                                                   FirstTypeName.StartLocation);
5579 
5580 
5581   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
5582                                    ScopeTypeInfo, CCLoc, TildeLoc,
5583                                    Destructed, HasTrailingLParen);
5584 }
5585 
ActOnPseudoDestructorExpr(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,SourceLocation TildeLoc,const DeclSpec & DS,bool HasTrailingLParen)5586 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5587                                            SourceLocation OpLoc,
5588                                            tok::TokenKind OpKind,
5589                                            SourceLocation TildeLoc,
5590                                            const DeclSpec& DS,
5591                                            bool HasTrailingLParen) {
5592   QualType ObjectType;
5593   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5594     return ExprError();
5595 
5596   QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5597 
5598   TypeLocBuilder TLB;
5599   DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5600   DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5601   TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5602   PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5603 
5604   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5605                                    nullptr, SourceLocation(), TildeLoc,
5606                                    Destructed, HasTrailingLParen);
5607 }
5608 
BuildCXXMemberCallExpr(Expr * E,NamedDecl * FoundDecl,CXXConversionDecl * Method,bool HadMultipleCandidates)5609 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
5610                                         CXXConversionDecl *Method,
5611                                         bool HadMultipleCandidates) {
5612   if (Method->getParent()->isLambda() &&
5613       Method->getConversionType()->isBlockPointerType()) {
5614     // This is a lambda coversion to block pointer; check if the argument
5615     // is a LambdaExpr.
5616     Expr *SubE = E;
5617     CastExpr *CE = dyn_cast<CastExpr>(SubE);
5618     if (CE && CE->getCastKind() == CK_NoOp)
5619       SubE = CE->getSubExpr();
5620     SubE = SubE->IgnoreParens();
5621     if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5622       SubE = BE->getSubExpr();
5623     if (isa<LambdaExpr>(SubE)) {
5624       // For the conversion to block pointer on a lambda expression, we
5625       // construct a special BlockLiteral instead; this doesn't really make
5626       // a difference in ARC, but outside of ARC the resulting block literal
5627       // follows the normal lifetime rules for block literals instead of being
5628       // autoreleased.
5629       DiagnosticErrorTrap Trap(Diags);
5630       ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5631                                                      E->getExprLoc(),
5632                                                      Method, E);
5633       if (Exp.isInvalid())
5634         Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5635       return Exp;
5636     }
5637   }
5638 
5639   ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
5640                                           FoundDecl, Method);
5641   if (Exp.isInvalid())
5642     return true;
5643 
5644   MemberExpr *ME =
5645       new (Context) MemberExpr(Exp.get(), /*IsArrow=*/false, Method,
5646                                SourceLocation(), Context.BoundMemberTy,
5647                                VK_RValue, OK_Ordinary);
5648   if (HadMultipleCandidates)
5649     ME->setHadMultipleCandidates(true);
5650   MarkMemberReferenced(ME);
5651 
5652   QualType ResultType = Method->getReturnType();
5653   ExprValueKind VK = Expr::getValueKindForType(ResultType);
5654   ResultType = ResultType.getNonLValueExprType(Context);
5655 
5656   CXXMemberCallExpr *CE =
5657     new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
5658                                     Exp.get()->getLocEnd());
5659   return CE;
5660 }
5661 
BuildCXXNoexceptExpr(SourceLocation KeyLoc,Expr * Operand,SourceLocation RParen)5662 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5663                                       SourceLocation RParen) {
5664   CanThrowResult CanThrow = canThrow(Operand);
5665   return new (Context)
5666       CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
5667 }
5668 
ActOnNoexceptExpr(SourceLocation KeyLoc,SourceLocation,Expr * Operand,SourceLocation RParen)5669 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5670                                    Expr *Operand, SourceLocation RParen) {
5671   return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
5672 }
5673 
IsSpecialDiscardedValue(Expr * E)5674 static bool IsSpecialDiscardedValue(Expr *E) {
5675   // In C++11, discarded-value expressions of a certain form are special,
5676   // according to [expr]p10:
5677   //   The lvalue-to-rvalue conversion (4.1) is applied only if the
5678   //   expression is an lvalue of volatile-qualified type and it has
5679   //   one of the following forms:
5680   E = E->IgnoreParens();
5681 
5682   //   - id-expression (5.1.1),
5683   if (isa<DeclRefExpr>(E))
5684     return true;
5685 
5686   //   - subscripting (5.2.1),
5687   if (isa<ArraySubscriptExpr>(E))
5688     return true;
5689 
5690   //   - class member access (5.2.5),
5691   if (isa<MemberExpr>(E))
5692     return true;
5693 
5694   //   - indirection (5.3.1),
5695   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
5696     if (UO->getOpcode() == UO_Deref)
5697       return true;
5698 
5699   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5700     //   - pointer-to-member operation (5.5),
5701     if (BO->isPtrMemOp())
5702       return true;
5703 
5704     //   - comma expression (5.18) where the right operand is one of the above.
5705     if (BO->getOpcode() == BO_Comma)
5706       return IsSpecialDiscardedValue(BO->getRHS());
5707   }
5708 
5709   //   - conditional expression (5.16) where both the second and the third
5710   //     operands are one of the above, or
5711   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
5712     return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
5713            IsSpecialDiscardedValue(CO->getFalseExpr());
5714   // The related edge case of "*x ?: *x".
5715   if (BinaryConditionalOperator *BCO =
5716           dyn_cast<BinaryConditionalOperator>(E)) {
5717     if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
5718       return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
5719              IsSpecialDiscardedValue(BCO->getFalseExpr());
5720   }
5721 
5722   // Objective-C++ extensions to the rule.
5723   if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
5724     return true;
5725 
5726   return false;
5727 }
5728 
5729 /// Perform the conversions required for an expression used in a
5730 /// context that ignores the result.
IgnoredValueConversions(Expr * E)5731 ExprResult Sema::IgnoredValueConversions(Expr *E) {
5732   if (E->hasPlaceholderType()) {
5733     ExprResult result = CheckPlaceholderExpr(E);
5734     if (result.isInvalid()) return E;
5735     E = result.get();
5736   }
5737 
5738   // C99 6.3.2.1:
5739   //   [Except in specific positions,] an lvalue that does not have
5740   //   array type is converted to the value stored in the
5741   //   designated object (and is no longer an lvalue).
5742   if (E->isRValue()) {
5743     // In C, function designators (i.e. expressions of function type)
5744     // are r-values, but we still want to do function-to-pointer decay
5745     // on them.  This is both technically correct and convenient for
5746     // some clients.
5747     if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
5748       return DefaultFunctionArrayConversion(E);
5749 
5750     return E;
5751   }
5752 
5753   if (getLangOpts().CPlusPlus)  {
5754     // The C++11 standard defines the notion of a discarded-value expression;
5755     // normally, we don't need to do anything to handle it, but if it is a
5756     // volatile lvalue with a special form, we perform an lvalue-to-rvalue
5757     // conversion.
5758     if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
5759         E->getType().isVolatileQualified() &&
5760         IsSpecialDiscardedValue(E)) {
5761       ExprResult Res = DefaultLvalueConversion(E);
5762       if (Res.isInvalid())
5763         return E;
5764       E = Res.get();
5765     }
5766     return E;
5767   }
5768 
5769   // GCC seems to also exclude expressions of incomplete enum type.
5770   if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5771     if (!T->getDecl()->isComplete()) {
5772       // FIXME: stupid workaround for a codegen bug!
5773       E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
5774       return E;
5775     }
5776   }
5777 
5778   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5779   if (Res.isInvalid())
5780     return E;
5781   E = Res.get();
5782 
5783   if (!E->getType()->isVoidType())
5784     RequireCompleteType(E->getExprLoc(), E->getType(),
5785                         diag::err_incomplete_type);
5786   return E;
5787 }
5788 
5789 // If we can unambiguously determine whether Var can never be used
5790 // in a constant expression, return true.
5791 //  - if the variable and its initializer are non-dependent, then
5792 //    we can unambiguously check if the variable is a constant expression.
5793 //  - if the initializer is not value dependent - we can determine whether
5794 //    it can be used to initialize a constant expression.  If Init can not
5795 //    be used to initialize a constant expression we conclude that Var can
5796 //    never be a constant expression.
5797 //  - FXIME: if the initializer is dependent, we can still do some analysis and
5798 //    identify certain cases unambiguously as non-const by using a Visitor:
5799 //      - such as those that involve odr-use of a ParmVarDecl, involve a new
5800 //        delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
VariableCanNeverBeAConstantExpression(VarDecl * Var,ASTContext & Context)5801 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
5802     ASTContext &Context) {
5803   if (isa<ParmVarDecl>(Var)) return true;
5804   const VarDecl *DefVD = nullptr;
5805 
5806   // If there is no initializer - this can not be a constant expression.
5807   if (!Var->getAnyInitializer(DefVD)) return true;
5808   assert(DefVD);
5809   if (DefVD->isWeak()) return false;
5810   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
5811 
5812   Expr *Init = cast<Expr>(Eval->Value);
5813 
5814   if (Var->getType()->isDependentType() || Init->isValueDependent()) {
5815     // FIXME: Teach the constant evaluator to deal with the non-dependent parts
5816     // of value-dependent expressions, and use it here to determine whether the
5817     // initializer is a potential constant expression.
5818     return false;
5819   }
5820 
5821   return !IsVariableAConstantExpression(Var, Context);
5822 }
5823 
5824 /// \brief Check if the current lambda has any potential captures
5825 /// that must be captured by any of its enclosing lambdas that are ready to
5826 /// capture. If there is a lambda that can capture a nested
5827 /// potential-capture, go ahead and do so.  Also, check to see if any
5828 /// variables are uncaptureable or do not involve an odr-use so do not
5829 /// need to be captured.
5830 
CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(Expr * const FE,LambdaScopeInfo * const CurrentLSI,Sema & S)5831 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
5832     Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
5833 
5834   assert(!S.isUnevaluatedContext());
5835   assert(S.CurContext->isDependentContext());
5836   assert(CurrentLSI->CallOperator == S.CurContext &&
5837       "The current call operator must be synchronized with Sema's CurContext");
5838 
5839   const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
5840 
5841   ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
5842       S.FunctionScopes.data(), S.FunctionScopes.size());
5843 
5844   // All the potentially captureable variables in the current nested
5845   // lambda (within a generic outer lambda), must be captured by an
5846   // outer lambda that is enclosed within a non-dependent context.
5847   const unsigned NumPotentialCaptures =
5848       CurrentLSI->getNumPotentialVariableCaptures();
5849   for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
5850     Expr *VarExpr = nullptr;
5851     VarDecl *Var = nullptr;
5852     CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
5853     // If the variable is clearly identified as non-odr-used and the full
5854     // expression is not instantiation dependent, only then do we not
5855     // need to check enclosing lambda's for speculative captures.
5856     // For e.g.:
5857     // Even though 'x' is not odr-used, it should be captured.
5858     // int test() {
5859     //   const int x = 10;
5860     //   auto L = [=](auto a) {
5861     //     (void) +x + a;
5862     //   };
5863     // }
5864     if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
5865         !IsFullExprInstantiationDependent)
5866       continue;
5867 
5868     // If we have a capture-capable lambda for the variable, go ahead and
5869     // capture the variable in that lambda (and all its enclosing lambdas).
5870     if (const Optional<unsigned> Index =
5871             getStackIndexOfNearestEnclosingCaptureCapableLambda(
5872                 FunctionScopesArrayRef, Var, S)) {
5873       const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
5874       MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
5875                          &FunctionScopeIndexOfCapturableLambda);
5876     }
5877     const bool IsVarNeverAConstantExpression =
5878         VariableCanNeverBeAConstantExpression(Var, S.Context);
5879     if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
5880       // This full expression is not instantiation dependent or the variable
5881       // can not be used in a constant expression - which means
5882       // this variable must be odr-used here, so diagnose a
5883       // capture violation early, if the variable is un-captureable.
5884       // This is purely for diagnosing errors early.  Otherwise, this
5885       // error would get diagnosed when the lambda becomes capture ready.
5886       QualType CaptureType, DeclRefType;
5887       SourceLocation ExprLoc = VarExpr->getExprLoc();
5888       if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
5889                           /*EllipsisLoc*/ SourceLocation(),
5890                           /*BuildAndDiagnose*/false, CaptureType,
5891                           DeclRefType, nullptr)) {
5892         // We will never be able to capture this variable, and we need
5893         // to be able to in any and all instantiations, so diagnose it.
5894         S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
5895                           /*EllipsisLoc*/ SourceLocation(),
5896                           /*BuildAndDiagnose*/true, CaptureType,
5897                           DeclRefType, nullptr);
5898       }
5899     }
5900   }
5901 
5902   // Check if 'this' needs to be captured.
5903   if (CurrentLSI->hasPotentialThisCapture()) {
5904     // If we have a capture-capable lambda for 'this', go ahead and capture
5905     // 'this' in that lambda (and all its enclosing lambdas).
5906     if (const Optional<unsigned> Index =
5907             getStackIndexOfNearestEnclosingCaptureCapableLambda(
5908                 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
5909       const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
5910       S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
5911                             /*Explicit*/ false, /*BuildAndDiagnose*/ true,
5912                             &FunctionScopeIndexOfCapturableLambda);
5913     }
5914   }
5915 
5916   // Reset all the potential captures at the end of each full-expression.
5917   CurrentLSI->clearPotentialCaptures();
5918 }
5919 
5920 
ActOnFinishFullExpr(Expr * FE,SourceLocation CC,bool DiscardedValue,bool IsConstexpr,bool IsLambdaInitCaptureInitializer)5921 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
5922                                      bool DiscardedValue,
5923                                      bool IsConstexpr,
5924                                      bool IsLambdaInitCaptureInitializer) {
5925   ExprResult FullExpr = FE;
5926 
5927   if (!FullExpr.get())
5928     return ExprError();
5929 
5930   // If we are an init-expression in a lambdas init-capture, we should not
5931   // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
5932   // containing full-expression is done).
5933   // template<class ... Ts> void test(Ts ... t) {
5934   //   test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
5935   //     return a;
5936   //   }() ...);
5937   // }
5938   // FIXME: This is a hack. It would be better if we pushed the lambda scope
5939   // when we parse the lambda introducer, and teach capturing (but not
5940   // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
5941   // corresponding class yet (that is, have LambdaScopeInfo either represent a
5942   // lambda where we've entered the introducer but not the body, or represent a
5943   // lambda where we've entered the body, depending on where the
5944   // parser/instantiation has got to).
5945   if (!IsLambdaInitCaptureInitializer &&
5946       DiagnoseUnexpandedParameterPack(FullExpr.get()))
5947     return ExprError();
5948 
5949   // Top-level expressions default to 'id' when we're in a debugger.
5950   if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
5951       FullExpr.get()->getType() == Context.UnknownAnyTy) {
5952     FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
5953     if (FullExpr.isInvalid())
5954       return ExprError();
5955   }
5956 
5957   if (DiscardedValue) {
5958     FullExpr = CheckPlaceholderExpr(FullExpr.get());
5959     if (FullExpr.isInvalid())
5960       return ExprError();
5961 
5962     FullExpr = IgnoredValueConversions(FullExpr.get());
5963     if (FullExpr.isInvalid())
5964       return ExprError();
5965   }
5966 
5967   CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
5968 
5969   // At the end of this full expression (which could be a deeply nested
5970   // lambda), if there is a potential capture within the nested lambda,
5971   // have the outer capture-able lambda try and capture it.
5972   // Consider the following code:
5973   // void f(int, int);
5974   // void f(const int&, double);
5975   // void foo() {
5976   //  const int x = 10, y = 20;
5977   //  auto L = [=](auto a) {
5978   //      auto M = [=](auto b) {
5979   //         f(x, b); <-- requires x to be captured by L and M
5980   //         f(y, a); <-- requires y to be captured by L, but not all Ms
5981   //      };
5982   //   };
5983   // }
5984 
5985   // FIXME: Also consider what happens for something like this that involves
5986   // the gnu-extension statement-expressions or even lambda-init-captures:
5987   //   void f() {
5988   //     const int n = 0;
5989   //     auto L =  [&](auto a) {
5990   //       +n + ({ 0; a; });
5991   //     };
5992   //   }
5993   //
5994   // Here, we see +n, and then the full-expression 0; ends, so we don't
5995   // capture n (and instead remove it from our list of potential captures),
5996   // and then the full-expression +n + ({ 0; }); ends, but it's too late
5997   // for us to see that we need to capture n after all.
5998 
5999   LambdaScopeInfo *const CurrentLSI = getCurLambda();
6000   // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
6001   // even if CurContext is not a lambda call operator. Refer to that Bug Report
6002   // for an example of the code that might cause this asynchrony.
6003   // By ensuring we are in the context of a lambda's call operator
6004   // we can fix the bug (we only need to check whether we need to capture
6005   // if we are within a lambda's body); but per the comments in that
6006   // PR, a proper fix would entail :
6007   //   "Alternative suggestion:
6008   //   - Add to Sema an integer holding the smallest (outermost) scope
6009   //     index that we are *lexically* within, and save/restore/set to
6010   //     FunctionScopes.size() in InstantiatingTemplate's
6011   //     constructor/destructor.
6012   //  - Teach the handful of places that iterate over FunctionScopes to
6013   //    stop at the outermost enclosing lexical scope."
6014   const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
6015   if (IsInLambdaDeclContext && CurrentLSI &&
6016       CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
6017     CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
6018                                                               *this);
6019   return MaybeCreateExprWithCleanups(FullExpr);
6020 }
6021 
ActOnFinishFullStmt(Stmt * FullStmt)6022 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
6023   if (!FullStmt) return StmtError();
6024 
6025   return MaybeCreateStmtWithCleanups(FullStmt);
6026 }
6027 
6028 Sema::IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope * S,CXXScopeSpec & SS,const DeclarationNameInfo & TargetNameInfo)6029 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
6030                                    CXXScopeSpec &SS,
6031                                    const DeclarationNameInfo &TargetNameInfo) {
6032   DeclarationName TargetName = TargetNameInfo.getName();
6033   if (!TargetName)
6034     return IER_DoesNotExist;
6035 
6036   // If the name itself is dependent, then the result is dependent.
6037   if (TargetName.isDependentName())
6038     return IER_Dependent;
6039 
6040   // Do the redeclaration lookup in the current scope.
6041   LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
6042                  Sema::NotForRedeclaration);
6043   LookupParsedName(R, S, &SS);
6044   R.suppressDiagnostics();
6045 
6046   switch (R.getResultKind()) {
6047   case LookupResult::Found:
6048   case LookupResult::FoundOverloaded:
6049   case LookupResult::FoundUnresolvedValue:
6050   case LookupResult::Ambiguous:
6051     return IER_Exists;
6052 
6053   case LookupResult::NotFound:
6054     return IER_DoesNotExist;
6055 
6056   case LookupResult::NotFoundInCurrentInstantiation:
6057     return IER_Dependent;
6058   }
6059 
6060   llvm_unreachable("Invalid LookupResult Kind!");
6061 }
6062 
6063 Sema::IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope * S,SourceLocation KeywordLoc,bool IsIfExists,CXXScopeSpec & SS,UnqualifiedId & Name)6064 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
6065                                    bool IsIfExists, CXXScopeSpec &SS,
6066                                    UnqualifiedId &Name) {
6067   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6068 
6069   // Check for unexpanded parameter packs.
6070   SmallVector<UnexpandedParameterPack, 4> Unexpanded;
6071   collectUnexpandedParameterPacks(SS, Unexpanded);
6072   collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
6073   if (!Unexpanded.empty()) {
6074     DiagnoseUnexpandedParameterPacks(KeywordLoc,
6075                                      IsIfExists? UPPC_IfExists
6076                                                : UPPC_IfNotExists,
6077                                      Unexpanded);
6078     return IER_Error;
6079   }
6080 
6081   return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
6082 }
6083