Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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