Bug Summary

File:tools/clang/lib/Sema/SemaExprCXX.cpp
Warning:line 706, column 7
Potential leak of memory pointed to by field 'DiagStorage'

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaExprCXX.cpp

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