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