Bug Summary

File:tools/clang/lib/Sema/SemaExprCXX.cpp
Warning:line 448, column 7
Called C++ object pointer is null

Annotated Source Code

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