Bug Summary

File:tools/clang/lib/Sema/SemaExprCXX.cpp
Warning:line 1150, column 45
The left operand of '==' is a garbage value

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~svn329677/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/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/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-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/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-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExprCXX.cpp

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExprCXX.cpp

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

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
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// This file defines the Sema class, which performs semantic analysis and
11// builds ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_SEMA_SEMA_H
16#define LLVM_CLANG_SEMA_SEMA_H
17
18#include "clang/AST/Attr.h"
19#include "clang/AST/Availability.h"
20#include "clang/AST/DeclarationName.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/ExternalASTSource.h"
25#include "clang/AST/LocInfoType.h"
26#include "clang/AST/MangleNumberingContext.h"
27#include "clang/AST/NSAPI.h"
28#include "clang/AST/PrettyPrinter.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/TypeLoc.h"
31#include "clang/AST/TypeOrdering.h"
32#include "clang/Basic/ExpressionTraits.h"
33#include "clang/Basic/Module.h"
34#include "clang/Basic/OpenMPKinds.h"
35#include "clang/Basic/PragmaKinds.h"
36#include "clang/Basic/Specifiers.h"
37#include "clang/Basic/TemplateKinds.h"
38#include "clang/Basic/TypeTraits.h"
39#include "clang/Sema/AnalysisBasedWarnings.h"
40#include "clang/Sema/CleanupInfo.h"
41#include "clang/Sema/DeclSpec.h"
42#include "clang/Sema/ExternalSemaSource.h"
43#include "clang/Sema/IdentifierResolver.h"
44#include "clang/Sema/ObjCMethodList.h"
45#include "clang/Sema/Ownership.h"
46#include "clang/Sema/Scope.h"
47#include "clang/Sema/TypoCorrection.h"
48#include "clang/Sema/Weak.h"
49#include "llvm/ADT/ArrayRef.h"
50#include "llvm/ADT/Optional.h"
51#include "llvm/ADT/SetVector.h"
52#include "llvm/ADT/SmallPtrSet.h"
53#include "llvm/ADT/SmallVector.h"
54#include "llvm/ADT/TinyPtrVector.h"
55#include <deque>
56#include <memory>
57#include <string>
58#include <vector>
59
60namespace llvm {
61 class APSInt;
62 template <typename ValueT> struct DenseMapInfo;
63 template <typename ValueT, typename ValueInfoT> class DenseSet;
64 class SmallBitVector;
65 struct InlineAsmIdentifierInfo;
66}
67
68namespace clang {
69 class ADLResult;
70 class ASTConsumer;
71 class ASTContext;
72 class ASTMutationListener;
73 class ASTReader;
74 class ASTWriter;
75 class ArrayType;
76 class AttributeList;
77 class BindingDecl;
78 class BlockDecl;
79 class CapturedDecl;
80 class CXXBasePath;
81 class CXXBasePaths;
82 class CXXBindTemporaryExpr;
83 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
84 class CXXConstructorDecl;
85 class CXXConversionDecl;
86 class CXXDeleteExpr;
87 class CXXDestructorDecl;
88 class CXXFieldCollector;
89 class CXXMemberCallExpr;
90 class CXXMethodDecl;
91 class CXXScopeSpec;
92 class CXXTemporary;
93 class CXXTryStmt;
94 class CallExpr;
95 class ClassTemplateDecl;
96 class ClassTemplatePartialSpecializationDecl;
97 class ClassTemplateSpecializationDecl;
98 class VarTemplatePartialSpecializationDecl;
99 class CodeCompleteConsumer;
100 class CodeCompletionAllocator;
101 class CodeCompletionTUInfo;
102 class CodeCompletionResult;
103 class CoroutineBodyStmt;
104 class Decl;
105 class DeclAccessPair;
106 class DeclContext;
107 class DeclRefExpr;
108 class DeclaratorDecl;
109 class DeducedTemplateArgument;
110 class DependentDiagnostic;
111 class DesignatedInitExpr;
112 class Designation;
113 class EnableIfAttr;
114 class EnumConstantDecl;
115 class Expr;
116 class ExtVectorType;
117 class FormatAttr;
118 class FriendDecl;
119 class FunctionDecl;
120 class FunctionProtoType;
121 class FunctionTemplateDecl;
122 class ImplicitConversionSequence;
123 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
124 class InitListExpr;
125 class InitializationKind;
126 class InitializationSequence;
127 class InitializedEntity;
128 class IntegerLiteral;
129 class LabelStmt;
130 class LambdaExpr;
131 class LangOptions;
132 class LocalInstantiationScope;
133 class LookupResult;
134 class MacroInfo;
135 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
136 class ModuleLoader;
137 class MultiLevelTemplateArgumentList;
138 class NamedDecl;
139 class ObjCCategoryDecl;
140 class ObjCCategoryImplDecl;
141 class ObjCCompatibleAliasDecl;
142 class ObjCContainerDecl;
143 class ObjCImplDecl;
144 class ObjCImplementationDecl;
145 class ObjCInterfaceDecl;
146 class ObjCIvarDecl;
147 template <class T> class ObjCList;
148 class ObjCMessageExpr;
149 class ObjCMethodDecl;
150 class ObjCPropertyDecl;
151 class ObjCProtocolDecl;
152 class OMPThreadPrivateDecl;
153 class OMPDeclareReductionDecl;
154 class OMPDeclareSimdDecl;
155 class OMPClause;
156 struct OverloadCandidate;
157 class OverloadCandidateSet;
158 class OverloadExpr;
159 class ParenListExpr;
160 class ParmVarDecl;
161 class Preprocessor;
162 class PseudoDestructorTypeStorage;
163 class PseudoObjectExpr;
164 class QualType;
165 class StandardConversionSequence;
166 class Stmt;
167 class StringLiteral;
168 class SwitchStmt;
169 class TemplateArgument;
170 class TemplateArgumentList;
171 class TemplateArgumentLoc;
172 class TemplateDecl;
173 class TemplateInstantiationCallback;
174 class TemplateParameterList;
175 class TemplatePartialOrderingContext;
176 class TemplateTemplateParmDecl;
177 class Token;
178 class TypeAliasDecl;
179 class TypedefDecl;
180 class TypedefNameDecl;
181 class TypeLoc;
182 class TypoCorrectionConsumer;
183 class UnqualifiedId;
184 class UnresolvedLookupExpr;
185 class UnresolvedMemberExpr;
186 class UnresolvedSetImpl;
187 class UnresolvedSetIterator;
188 class UsingDecl;
189 class UsingShadowDecl;
190 class ValueDecl;
191 class VarDecl;
192 class VarTemplateSpecializationDecl;
193 class VisibilityAttr;
194 class VisibleDeclConsumer;
195 class IndirectFieldDecl;
196 struct DeductionFailureInfo;
197 class TemplateSpecCandidateSet;
198
199namespace sema {
200 class AccessedEntity;
201 class BlockScopeInfo;
202 class Capture;
203 class CapturedRegionScopeInfo;
204 class CapturingScopeInfo;
205 class CompoundScopeInfo;
206 class DelayedDiagnostic;
207 class DelayedDiagnosticPool;
208 class FunctionScopeInfo;
209 class LambdaScopeInfo;
210 class PossiblyUnreachableDiag;
211 class SemaPPCallbacks;
212 class TemplateDeductionInfo;
213}
214
215namespace threadSafety {
216 class BeforeSet;
217 void threadSafetyCleanup(BeforeSet* Cache);
218}
219
220// FIXME: No way to easily map from TemplateTypeParmTypes to
221// TemplateTypeParmDecls, so we have this horrible PointerUnion.
222typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
223 SourceLocation> UnexpandedParameterPack;
224
225/// Describes whether we've seen any nullability information for the given
226/// file.
227struct FileNullability {
228 /// The first pointer declarator (of any pointer kind) in the file that does
229 /// not have a corresponding nullability annotation.
230 SourceLocation PointerLoc;
231
232 /// The end location for the first pointer declarator in the file. Used for
233 /// placing fix-its.
234 SourceLocation PointerEndLoc;
235
236 /// Which kind of pointer declarator we saw.
237 uint8_t PointerKind;
238
239 /// Whether we saw any type nullability annotations in the given file.
240 bool SawTypeNullability = false;
241};
242
243/// A mapping from file IDs to a record of whether we've seen nullability
244/// information in that file.
245class FileNullabilityMap {
246 /// A mapping from file IDs to the nullability information for each file ID.
247 llvm::DenseMap<FileID, FileNullability> Map;
248
249 /// A single-element cache based on the file ID.
250 struct {
251 FileID File;
252 FileNullability Nullability;
253 } Cache;
254
255public:
256 FileNullability &operator[](FileID file) {
257 // Check the single-element cache.
258 if (file == Cache.File)
259 return Cache.Nullability;
260
261 // It's not in the single-element cache; flush the cache if we have one.
262 if (!Cache.File.isInvalid()) {
263 Map[Cache.File] = Cache.Nullability;
264 }
265
266 // Pull this entry into the cache.
267 Cache.File = file;
268 Cache.Nullability = Map[file];
269 return Cache.Nullability;
270 }
271};
272
273/// Sema - This implements semantic analysis and AST building for C.
274class Sema {
275 Sema(const Sema &) = delete;
276 void operator=(const Sema &) = delete;
277
278 ///\brief Source of additional semantic information.
279 ExternalSemaSource *ExternalSource;
280
281 ///\brief Whether Sema has generated a multiplexer and has to delete it.
282 bool isMultiplexExternalSource;
283
284 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
285
286 bool isVisibleSlow(const NamedDecl *D);
287
288 /// Determine whether two declarations should be linked together, given that
289 /// the old declaration might not be visible and the new declaration might
290 /// not have external linkage.
291 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
292 const NamedDecl *New) {
293 if (isVisible(Old))
294 return true;
295 // See comment in below overload for why it's safe to compute the linkage
296 // of the new declaration here.
297 if (New->isExternallyDeclarable()) {
298 assert(Old->isExternallyDeclarable() &&(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 299, __extension__ __PRETTY_FUNCTION__))
299 "should not have found a non-externally-declarable previous decl")(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 299, __extension__ __PRETTY_FUNCTION__))
;
300 return true;
301 }
302 return false;
303 }
304 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
305
306public:
307 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
308 typedef OpaquePtr<TemplateName> TemplateTy;
309 typedef OpaquePtr<QualType> TypeTy;
310
311 OpenCLOptions OpenCLFeatures;
312 FPOptions FPFeatures;
313
314 const LangOptions &LangOpts;
315 Preprocessor &PP;
316 ASTContext &Context;
317 ASTConsumer &Consumer;
318 DiagnosticsEngine &Diags;
319 SourceManager &SourceMgr;
320
321 /// \brief Flag indicating whether or not to collect detailed statistics.
322 bool CollectStats;
323
324 /// \brief Code-completion consumer.
325 CodeCompleteConsumer *CodeCompleter;
326
327 /// CurContext - This is the current declaration context of parsing.
328 DeclContext *CurContext;
329
330 /// \brief Generally null except when we temporarily switch decl contexts,
331 /// like in \see ActOnObjCTemporaryExitContainerContext.
332 DeclContext *OriginalLexicalContext;
333
334 /// VAListTagName - The declaration name corresponding to __va_list_tag.
335 /// This is used as part of a hack to omit that class from ADL results.
336 DeclarationName VAListTagName;
337
338 bool MSStructPragmaOn; // True when \#pragma ms_struct on
339
340 /// \brief Controls member pointer representation format under the MS ABI.
341 LangOptions::PragmaMSPointersToMembersKind
342 MSPointerToMemberRepresentationMethod;
343
344 /// Stack of active SEH __finally scopes. Can be empty.
345 SmallVector<Scope*, 2> CurrentSEHFinally;
346
347 /// \brief Source location for newly created implicit MSInheritanceAttrs
348 SourceLocation ImplicitMSInheritanceAttrLoc;
349
350 /// \brief pragma clang section kind
351 enum PragmaClangSectionKind {
352 PCSK_Invalid = 0,
353 PCSK_BSS = 1,
354 PCSK_Data = 2,
355 PCSK_Rodata = 3,
356 PCSK_Text = 4
357 };
358
359 enum PragmaClangSectionAction {
360 PCSA_Set = 0,
361 PCSA_Clear = 1
362 };
363
364 struct PragmaClangSection {
365 std::string SectionName;
366 bool Valid = false;
367 SourceLocation PragmaLocation;
368
369 void Act(SourceLocation PragmaLocation,
370 PragmaClangSectionAction Action,
371 StringLiteral* Name);
372 };
373
374 PragmaClangSection PragmaClangBSSSection;
375 PragmaClangSection PragmaClangDataSection;
376 PragmaClangSection PragmaClangRodataSection;
377 PragmaClangSection PragmaClangTextSection;
378
379 enum PragmaMsStackAction {
380 PSK_Reset = 0x0, // #pragma ()
381 PSK_Set = 0x1, // #pragma (value)
382 PSK_Push = 0x2, // #pragma (push[, id])
383 PSK_Pop = 0x4, // #pragma (pop[, id])
384 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
385 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
386 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
387 };
388
389 template<typename ValueType>
390 struct PragmaStack {
391 struct Slot {
392 llvm::StringRef StackSlotLabel;
393 ValueType Value;
394 SourceLocation PragmaLocation;
395 SourceLocation PragmaPushLocation;
396 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
397 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
398 : StackSlotLabel(StackSlotLabel), Value(Value),
399 PragmaLocation(PragmaLocation),
400 PragmaPushLocation(PragmaPushLocation) {}
401 };
402 void Act(SourceLocation PragmaLocation,
403 PragmaMsStackAction Action,
404 llvm::StringRef StackSlotLabel,
405 ValueType Value);
406
407 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
408 // method body to restore the stacks on exit, so it works like this:
409 //
410 // struct S {
411 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
412 // void Method {}
413 // #pragma <name>(pop, InternalPragmaSlot)
414 // };
415 //
416 // It works even with #pragma vtordisp, although MSVC doesn't support
417 // #pragma vtordisp(push [, id], n)
418 // syntax.
419 //
420 // Push / pop a named sentinel slot.
421 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
422 assert((Action == PSK_Push || Action == PSK_Pop) &&(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 423, __extension__ __PRETTY_FUNCTION__))
423 "Can only push / pop #pragma stack sentinels!")(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 423, __extension__ __PRETTY_FUNCTION__))
;
424 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
425 }
426
427 // Constructors.
428 explicit PragmaStack(const ValueType &Default)
429 : DefaultValue(Default), CurrentValue(Default) {}
430
431 bool hasValue() const { return CurrentValue != DefaultValue; }
432
433 SmallVector<Slot, 2> Stack;
434 ValueType DefaultValue; // Value used for PSK_Reset action.
435 ValueType CurrentValue;
436 SourceLocation CurrentPragmaLocation;
437 };
438 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
439 // we shouldn't do so if they're in a module).
440
441 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
442 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
443 ///
444 /// 0: Suppress all vtordisps
445 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
446 /// structors
447 /// 2: Always insert vtordisps to support RTTI on partially constructed
448 /// objects
449 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
450 // #pragma pack.
451 // Sentinel to represent when the stack is set to mac68k alignment.
452 static const unsigned kMac68kAlignmentSentinel = ~0U;
453 PragmaStack<unsigned> PackStack;
454 // The current #pragma pack values and locations at each #include.
455 struct PackIncludeState {
456 unsigned CurrentValue;
457 SourceLocation CurrentPragmaLocation;
458 bool HasNonDefaultValue, ShouldWarnOnInclude;
459 };
460 SmallVector<PackIncludeState, 8> PackIncludeStack;
461 // Segment #pragmas.
462 PragmaStack<StringLiteral *> DataSegStack;
463 PragmaStack<StringLiteral *> BSSSegStack;
464 PragmaStack<StringLiteral *> ConstSegStack;
465 PragmaStack<StringLiteral *> CodeSegStack;
466
467 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
468 // Actions should be performed only if we enter / exit a C++ method body.
469 class PragmaStackSentinelRAII {
470 public:
471 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
472 ~PragmaStackSentinelRAII();
473
474 private:
475 Sema &S;
476 StringRef SlotLabel;
477 bool ShouldAct;
478 };
479
480 /// A mapping that describes the nullability we've seen in each header file.
481 FileNullabilityMap NullabilityMap;
482
483 /// Last section used with #pragma init_seg.
484 StringLiteral *CurInitSeg;
485 SourceLocation CurInitSegLoc;
486
487 /// VisContext - Manages the stack for \#pragma GCC visibility.
488 void *VisContext; // Really a "PragmaVisStack*"
489
490 /// \brief This represents the stack of attributes that were pushed by
491 /// \#pragma clang attribute.
492 struct PragmaAttributeEntry {
493 SourceLocation Loc;
494 AttributeList *Attribute;
495 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
496 bool IsUsed;
497 };
498 SmallVector<PragmaAttributeEntry, 2> PragmaAttributeStack;
499
500 /// \brief The declaration that is currently receiving an attribute from the
501 /// #pragma attribute stack.
502 const Decl *PragmaAttributeCurrentTargetDecl;
503
504 /// \brief This represents the last location of a "#pragma clang optimize off"
505 /// directive if such a directive has not been closed by an "on" yet. If
506 /// optimizations are currently "on", this is set to an invalid location.
507 SourceLocation OptimizeOffPragmaLocation;
508
509 /// \brief Flag indicating if Sema is building a recovery call expression.
510 ///
511 /// This flag is used to avoid building recovery call expressions
512 /// if Sema is already doing so, which would cause infinite recursions.
513 bool IsBuildingRecoveryCallExpr;
514
515 /// Used to control the generation of ExprWithCleanups.
516 CleanupInfo Cleanup;
517
518 /// ExprCleanupObjects - This is the stack of objects requiring
519 /// cleanup that are created by the current full expression. The
520 /// element type here is ExprWithCleanups::Object.
521 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
522
523 /// \brief Store a list of either DeclRefExprs or MemberExprs
524 /// that contain a reference to a variable (constant) that may or may not
525 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
526 /// and discarded value conversions have been applied to all subexpressions
527 /// of the enclosing full expression. This is cleared at the end of each
528 /// full expression.
529 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
530
531 std::unique_ptr<sema::FunctionScopeInfo> PreallocatedFunctionScope;
532
533 /// \brief Stack containing information about each of the nested
534 /// function, block, and method scopes that are currently active.
535 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
536
537 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
538 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
539 ExtVectorDeclsType;
540
541 /// ExtVectorDecls - This is a list all the extended vector types. This allows
542 /// us to associate a raw vector type with one of the ext_vector type names.
543 /// This is only necessary for issuing pretty diagnostics.
544 ExtVectorDeclsType ExtVectorDecls;
545
546 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
547 std::unique_ptr<CXXFieldCollector> FieldCollector;
548
549 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
550
551 /// \brief Set containing all declared private fields that are not used.
552 NamedDeclSetType UnusedPrivateFields;
553
554 /// \brief Set containing all typedefs that are likely unused.
555 llvm::SmallSetVector<const TypedefNameDecl *, 4>
556 UnusedLocalTypedefNameCandidates;
557
558 /// \brief Delete-expressions to be analyzed at the end of translation unit
559 ///
560 /// This list contains class members, and locations of delete-expressions
561 /// that could not be proven as to whether they mismatch with new-expression
562 /// used in initializer of the field.
563 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
564 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
565 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
566
567 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
568
569 /// PureVirtualClassDiagSet - a set of class declarations which we have
570 /// emitted a list of pure virtual functions. Used to prevent emitting the
571 /// same list more than once.
572 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
573
574 /// ParsingInitForAutoVars - a set of declarations with auto types for which
575 /// we are currently parsing the initializer.
576 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
577
578 /// \brief Look for a locally scoped extern "C" declaration by the given name.
579 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
580
581 typedef LazyVector<VarDecl *, ExternalSemaSource,
582 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
583 TentativeDefinitionsType;
584
585 /// \brief All the tentative definitions encountered in the TU.
586 TentativeDefinitionsType TentativeDefinitions;
587
588 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
589 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
590 UnusedFileScopedDeclsType;
591
592 /// \brief The set of file scoped decls seen so far that have not been used
593 /// and must warn if not used. Only contains the first declaration.
594 UnusedFileScopedDeclsType UnusedFileScopedDecls;
595
596 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
597 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
598 DelegatingCtorDeclsType;
599
600 /// \brief All the delegating constructors seen so far in the file, used for
601 /// cycle detection at the end of the TU.
602 DelegatingCtorDeclsType DelegatingCtorDecls;
603
604 /// \brief All the overriding functions seen during a class definition
605 /// that had their exception spec checks delayed, plus the overridden
606 /// function.
607 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
608 DelayedExceptionSpecChecks;
609
610 /// \brief All the members seen during a class definition which were both
611 /// explicitly defaulted and had explicitly-specified exception
612 /// specifications, along with the function type containing their
613 /// user-specified exception specification. Those exception specifications
614 /// were overridden with the default specifications, but we still need to
615 /// check whether they are compatible with the default specification, and
616 /// we can't do that until the nesting set of class definitions is complete.
617 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
618 DelayedDefaultedMemberExceptionSpecs;
619
620 typedef llvm::MapVector<const FunctionDecl *,
621 std::unique_ptr<LateParsedTemplate>>
622 LateParsedTemplateMapT;
623 LateParsedTemplateMapT LateParsedTemplateMap;
624
625 /// \brief Callback to the parser to parse templated functions when needed.
626 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
627 typedef void LateTemplateParserCleanupCB(void *P);
628 LateTemplateParserCB *LateTemplateParser;
629 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
630 void *OpaqueParser;
631
632 void SetLateTemplateParser(LateTemplateParserCB *LTP,
633 LateTemplateParserCleanupCB *LTPCleanup,
634 void *P) {
635 LateTemplateParser = LTP;
636 LateTemplateParserCleanup = LTPCleanup;
637 OpaqueParser = P;
638 }
639
640 class DelayedDiagnostics;
641
642 class DelayedDiagnosticsState {
643 sema::DelayedDiagnosticPool *SavedPool;
644 friend class Sema::DelayedDiagnostics;
645 };
646 typedef DelayedDiagnosticsState ParsingDeclState;
647 typedef DelayedDiagnosticsState ProcessingContextState;
648
649 /// A class which encapsulates the logic for delaying diagnostics
650 /// during parsing and other processing.
651 class DelayedDiagnostics {
652 /// \brief The current pool of diagnostics into which delayed
653 /// diagnostics should go.
654 sema::DelayedDiagnosticPool *CurPool;
655
656 public:
657 DelayedDiagnostics() : CurPool(nullptr) {}
658
659 /// Adds a delayed diagnostic.
660 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
661
662 /// Determines whether diagnostics should be delayed.
663 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
664
665 /// Returns the current delayed-diagnostics pool.
666 sema::DelayedDiagnosticPool *getCurrentPool() const {
667 return CurPool;
668 }
669
670 /// Enter a new scope. Access and deprecation diagnostics will be
671 /// collected in this pool.
672 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
673 DelayedDiagnosticsState state;
674 state.SavedPool = CurPool;
675 CurPool = &pool;
676 return state;
677 }
678
679 /// Leave a delayed-diagnostic state that was previously pushed.
680 /// Do not emit any of the diagnostics. This is performed as part
681 /// of the bookkeeping of popping a pool "properly".
682 void popWithoutEmitting(DelayedDiagnosticsState state) {
683 CurPool = state.SavedPool;
684 }
685
686 /// Enter a new scope where access and deprecation diagnostics are
687 /// not delayed.
688 DelayedDiagnosticsState pushUndelayed() {
689 DelayedDiagnosticsState state;
690 state.SavedPool = CurPool;
691 CurPool = nullptr;
692 return state;
693 }
694
695 /// Undo a previous pushUndelayed().
696 void popUndelayed(DelayedDiagnosticsState state) {
697 assert(CurPool == nullptr)(static_cast <bool> (CurPool == nullptr) ? void (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 697, __extension__ __PRETTY_FUNCTION__))
;
698 CurPool = state.SavedPool;
699 }
700 } DelayedDiagnostics;
701
702 /// A RAII object to temporarily push a declaration context.
703 class ContextRAII {
704 private:
705 Sema &S;
706 DeclContext *SavedContext;
707 ProcessingContextState SavedContextState;
708 QualType SavedCXXThisTypeOverride;
709
710 public:
711 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
712 : S(S), SavedContext(S.CurContext),
713 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
714 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
715 {
716 assert(ContextToPush && "pushing null context")(static_cast <bool> (ContextToPush && "pushing null context"
) ? void (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 716, __extension__ __PRETTY_FUNCTION__))
;
717 S.CurContext = ContextToPush;
718 if (NewThisContext)
719 S.CXXThisTypeOverride = QualType();
720 }
721
722 void pop() {
723 if (!SavedContext) return;
724 S.CurContext = SavedContext;
725 S.DelayedDiagnostics.popUndelayed(SavedContextState);
726 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
727 SavedContext = nullptr;
728 }
729
730 ~ContextRAII() {
731 pop();
732 }
733 };
734
735 /// \brief RAII object to handle the state changes required to synthesize
736 /// a function body.
737 class SynthesizedFunctionScope {
738 Sema &S;
739 Sema::ContextRAII SavedContext;
740 bool PushedCodeSynthesisContext = false;
741
742 public:
743 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
744 : S(S), SavedContext(S, DC) {
745 S.PushFunctionScope();
746 S.PushExpressionEvaluationContext(
747 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
748 if (auto *FD = dyn_cast<FunctionDecl>(DC))
749 FD->setWillHaveBody(true);
750 else
751 assert(isa<ObjCMethodDecl>(DC))(static_cast <bool> (isa<ObjCMethodDecl>(DC)) ? void
(0) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 751, __extension__ __PRETTY_FUNCTION__))
;
752 }
753
754 void addContextNote(SourceLocation UseLoc) {
755 assert(!PushedCodeSynthesisContext)(static_cast <bool> (!PushedCodeSynthesisContext) ? void
(0) : __assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 755, __extension__ __PRETTY_FUNCTION__))
;
756
757 Sema::CodeSynthesisContext Ctx;
758 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
759 Ctx.PointOfInstantiation = UseLoc;
760 Ctx.Entity = cast<Decl>(S.CurContext);
761 S.pushCodeSynthesisContext(Ctx);
762
763 PushedCodeSynthesisContext = true;
764 }
765
766 ~SynthesizedFunctionScope() {
767 if (PushedCodeSynthesisContext)
768 S.popCodeSynthesisContext();
769 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
770 FD->setWillHaveBody(false);
771 S.PopExpressionEvaluationContext();
772 S.PopFunctionScopeInfo();
773 }
774 };
775
776 /// WeakUndeclaredIdentifiers - Identifiers contained in
777 /// \#pragma weak before declared. rare. may alias another
778 /// identifier, declared or undeclared
779 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
780
781 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
782 /// \#pragma redefine_extname before declared. Used in Solaris system headers
783 /// to define functions that occur in multiple standards to call the version
784 /// in the currently selected standard.
785 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
786
787
788 /// \brief Load weak undeclared identifiers from the external source.
789 void LoadExternalWeakUndeclaredIdentifiers();
790
791 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
792 /// \#pragma weak during processing of other Decls.
793 /// I couldn't figure out a clean way to generate these in-line, so
794 /// we store them here and handle separately -- which is a hack.
795 /// It would be best to refactor this.
796 SmallVector<Decl*,2> WeakTopLevelDecl;
797
798 IdentifierResolver IdResolver;
799
800 /// Translation Unit Scope - useful to Objective-C actions that need
801 /// to lookup file scope declarations in the "ordinary" C decl namespace.
802 /// For example, user-defined classes, built-in "id" type, etc.
803 Scope *TUScope;
804
805 /// \brief The C++ "std" namespace, where the standard library resides.
806 LazyDeclPtr StdNamespace;
807
808 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
809 /// standard library.
810 LazyDeclPtr StdBadAlloc;
811
812 /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
813 /// standard library.
814 LazyDeclPtr StdAlignValT;
815
816 /// \brief The C++ "std::experimental" namespace, where the experimental parts
817 /// of the standard library resides.
818 NamespaceDecl *StdExperimentalNamespaceCache;
819
820 /// \brief The C++ "std::initializer_list" template, which is defined in
821 /// \<initializer_list>.
822 ClassTemplateDecl *StdInitializerList;
823
824 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
825 RecordDecl *CXXTypeInfoDecl;
826
827 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
828 RecordDecl *MSVCGuidDecl;
829
830 /// \brief Caches identifiers/selectors for NSFoundation APIs.
831 std::unique_ptr<NSAPI> NSAPIObj;
832
833 /// \brief The declaration of the Objective-C NSNumber class.
834 ObjCInterfaceDecl *NSNumberDecl;
835
836 /// \brief The declaration of the Objective-C NSValue class.
837 ObjCInterfaceDecl *NSValueDecl;
838
839 /// \brief Pointer to NSNumber type (NSNumber *).
840 QualType NSNumberPointer;
841
842 /// \brief Pointer to NSValue type (NSValue *).
843 QualType NSValuePointer;
844
845 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
846 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
847
848 /// \brief The declaration of the Objective-C NSString class.
849 ObjCInterfaceDecl *NSStringDecl;
850
851 /// \brief Pointer to NSString type (NSString *).
852 QualType NSStringPointer;
853
854 /// \brief The declaration of the stringWithUTF8String: method.
855 ObjCMethodDecl *StringWithUTF8StringMethod;
856
857 /// \brief The declaration of the valueWithBytes:objCType: method.
858 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
859
860 /// \brief The declaration of the Objective-C NSArray class.
861 ObjCInterfaceDecl *NSArrayDecl;
862
863 /// \brief The declaration of the arrayWithObjects:count: method.
864 ObjCMethodDecl *ArrayWithObjectsMethod;
865
866 /// \brief The declaration of the Objective-C NSDictionary class.
867 ObjCInterfaceDecl *NSDictionaryDecl;
868
869 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
870 ObjCMethodDecl *DictionaryWithObjectsMethod;
871
872 /// \brief id<NSCopying> type.
873 QualType QIDNSCopying;
874
875 /// \brief will hold 'respondsToSelector:'
876 Selector RespondsToSelectorSel;
877
878 /// A flag to remember whether the implicit forms of operator new and delete
879 /// have been declared.
880 bool GlobalNewDeleteDeclared;
881
882 /// A flag to indicate that we're in a context that permits abstract
883 /// references to fields. This is really a
884 bool AllowAbstractFieldReference;
885
886 /// \brief Describes how the expressions currently being parsed are
887 /// evaluated at run-time, if at all.
888 enum class ExpressionEvaluationContext {
889 /// \brief The current expression and its subexpressions occur within an
890 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
891 /// \c sizeof, where the type of the expression may be significant but
892 /// no code will be generated to evaluate the value of the expression at
893 /// run time.
894 Unevaluated,
895
896 /// \brief The current expression occurs within a braced-init-list within
897 /// an unevaluated operand. This is mostly like a regular unevaluated
898 /// context, except that we still instantiate constexpr functions that are
899 /// referenced here so that we can perform narrowing checks correctly.
900 UnevaluatedList,
901
902 /// \brief The current expression occurs within a discarded statement.
903 /// This behaves largely similarly to an unevaluated operand in preventing
904 /// definitions from being required, but not in other ways.
905 DiscardedStatement,
906
907 /// \brief The current expression occurs within an unevaluated
908 /// operand that unconditionally permits abstract references to
909 /// fields, such as a SIZE operator in MS-style inline assembly.
910 UnevaluatedAbstract,
911
912 /// \brief The current context is "potentially evaluated" in C++11 terms,
913 /// but the expression is evaluated at compile-time (like the values of
914 /// cases in a switch statement).
915 ConstantEvaluated,
916
917 /// \brief The current expression is potentially evaluated at run time,
918 /// which means that code may be generated to evaluate the value of the
919 /// expression at run time.
920 PotentiallyEvaluated,
921
922 /// \brief The current expression is potentially evaluated, but any
923 /// declarations referenced inside that expression are only used if
924 /// in fact the current expression is used.
925 ///
926 /// This value is used when parsing default function arguments, for which
927 /// we would like to provide diagnostics (e.g., passing non-POD arguments
928 /// through varargs) but do not want to mark declarations as "referenced"
929 /// until the default argument is used.
930 PotentiallyEvaluatedIfUsed
931 };
932
933 /// \brief Data structure used to record current or nested
934 /// expression evaluation contexts.
935 struct ExpressionEvaluationContextRecord {
936 /// \brief The expression evaluation context.
937 ExpressionEvaluationContext Context;
938
939 /// \brief Whether the enclosing context needed a cleanup.
940 CleanupInfo ParentCleanup;
941
942 /// \brief Whether we are in a decltype expression.
943 bool IsDecltype;
944
945 /// \brief The number of active cleanup objects when we entered
946 /// this expression evaluation context.
947 unsigned NumCleanupObjects;
948
949 /// \brief The number of typos encountered during this expression evaluation
950 /// context (i.e. the number of TypoExprs created).
951 unsigned NumTypos;
952
953 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
954
955 /// \brief The lambdas that are present within this context, if it
956 /// is indeed an unevaluated context.
957 SmallVector<LambdaExpr *, 2> Lambdas;
958
959 /// \brief The declaration that provides context for lambda expressions
960 /// and block literals if the normal declaration context does not
961 /// suffice, e.g., in a default function argument.
962 Decl *ManglingContextDecl;
963
964 /// \brief The context information used to mangle lambda expressions
965 /// and block literals within this context.
966 ///
967 /// This mangling information is allocated lazily, since most contexts
968 /// do not have lambda expressions or block literals.
969 std::unique_ptr<MangleNumberingContext> MangleNumbering;
970
971 /// \brief If we are processing a decltype type, a set of call expressions
972 /// for which we have deferred checking the completeness of the return type.
973 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
974
975 /// \brief If we are processing a decltype type, a set of temporary binding
976 /// expressions for which we have deferred checking the destructor.
977 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
978
979 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
980 unsigned NumCleanupObjects,
981 CleanupInfo ParentCleanup,
982 Decl *ManglingContextDecl,
983 bool IsDecltype)
984 : Context(Context), ParentCleanup(ParentCleanup),
985 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
986 NumTypos(0),
987 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
988
989 /// \brief Retrieve the mangling numbering context, used to consistently
990 /// number constructs like lambdas for mangling.
991 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
992
993 bool isUnevaluated() const {
994 return Context == ExpressionEvaluationContext::Unevaluated ||
995 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
996 Context == ExpressionEvaluationContext::UnevaluatedList;
997 }
998 bool isConstantEvaluated() const {
999 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1000 }
1001 };
1002
1003 /// A stack of expression evaluation contexts.
1004 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1005
1006 /// \brief Compute the mangling number context for a lambda expression or
1007 /// block literal.
1008 ///
1009 /// \param DC - The DeclContext containing the lambda expression or
1010 /// block literal.
1011 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
1012 /// associated with the context, if relevant.
1013 MangleNumberingContext *getCurrentMangleNumberContext(
1014 const DeclContext *DC,
1015 Decl *&ManglingContextDecl);
1016
1017
1018 /// SpecialMemberOverloadResult - The overloading result for a special member
1019 /// function.
1020 ///
1021 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1022 /// integer are used to determine whether overload resolution succeeded.
1023 class SpecialMemberOverloadResult {
1024 public:
1025 enum Kind {
1026 NoMemberOrDeleted,
1027 Ambiguous,
1028 Success
1029 };
1030
1031 private:
1032 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1033
1034 public:
1035 SpecialMemberOverloadResult() : Pair() {}
1036 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1037 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1038
1039 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1040 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1041
1042 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1043 void setKind(Kind K) { Pair.setInt(K); }
1044 };
1045
1046 class SpecialMemberOverloadResultEntry
1047 : public llvm::FastFoldingSetNode,
1048 public SpecialMemberOverloadResult {
1049 public:
1050 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1051 : FastFoldingSetNode(ID)
1052 {}
1053 };
1054
1055 /// \brief A cache of special member function overload resolution results
1056 /// for C++ records.
1057 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1058
1059 /// \brief A cache of the flags available in enumerations with the flag_bits
1060 /// attribute.
1061 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1062
1063 /// \brief The kind of translation unit we are processing.
1064 ///
1065 /// When we're processing a complete translation unit, Sema will perform
1066 /// end-of-translation-unit semantic tasks (such as creating
1067 /// initializers for tentative definitions in C) once parsing has
1068 /// completed. Modules and precompiled headers perform different kinds of
1069 /// checks.
1070 TranslationUnitKind TUKind;
1071
1072 llvm::BumpPtrAllocator BumpAlloc;
1073
1074 /// \brief The number of SFINAE diagnostics that have been trapped.
1075 unsigned NumSFINAEErrors;
1076
1077 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1078 UnparsedDefaultArgInstantiationsMap;
1079
1080 /// \brief A mapping from parameters with unparsed default arguments to the
1081 /// set of instantiations of each parameter.
1082 ///
1083 /// This mapping is a temporary data structure used when parsing
1084 /// nested class templates or nested classes of class templates,
1085 /// where we might end up instantiating an inner class before the
1086 /// default arguments of its methods have been parsed.
1087 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1088
1089 // Contains the locations of the beginning of unparsed default
1090 // argument locations.
1091 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1092
1093 /// UndefinedInternals - all the used, undefined objects which require a
1094 /// definition in this translation unit.
1095 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1096
1097 /// Determine if VD, which must be a variable or function, is an external
1098 /// symbol that nonetheless can't be referenced from outside this translation
1099 /// unit because its type has no linkage and it's not extern "C".
1100 bool isExternalWithNoLinkageType(ValueDecl *VD);
1101
1102 /// Obtain a sorted list of functions that are undefined but ODR-used.
1103 void getUndefinedButUsed(
1104 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1105
1106 /// Retrieves list of suspicious delete-expressions that will be checked at
1107 /// the end of translation unit.
1108 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1109 getMismatchingDeleteExpressions() const;
1110
1111 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1112 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1113
1114 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1115 /// We need to maintain a list, since selectors can have differing signatures
1116 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1117 /// of selectors are "overloaded").
1118 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1119 /// methods inside categories with a particular selector.
1120 GlobalMethodPool MethodPool;
1121
1122 /// Method selectors used in a \@selector expression. Used for implementation
1123 /// of -Wselector.
1124 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1125
1126 /// Kinds of C++ special members.
1127 enum CXXSpecialMember {
1128 CXXDefaultConstructor,
1129 CXXCopyConstructor,
1130 CXXMoveConstructor,
1131 CXXCopyAssignment,
1132 CXXMoveAssignment,
1133 CXXDestructor,
1134 CXXInvalid
1135 };
1136
1137 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1138 SpecialMemberDecl;
1139
1140 /// The C++ special members which we are currently in the process of
1141 /// declaring. If this process recursively triggers the declaration of the
1142 /// same special member, we should act as if it is not yet declared.
1143 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1144
1145 /// The function definitions which were renamed as part of typo-correction
1146 /// to match their respective declarations. We want to keep track of them
1147 /// to ensure that we don't emit a "redefinition" error if we encounter a
1148 /// correctly named definition after the renamed definition.
1149 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1150
1151 /// Stack of types that correspond to the parameter entities that are
1152 /// currently being copy-initialized. Can be empty.
1153 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1154
1155 void ReadMethodPool(Selector Sel);
1156 void updateOutOfDateSelector(Selector Sel);
1157
1158 /// Private Helper predicate to check for 'self'.
1159 bool isSelfExpr(Expr *RExpr);
1160 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1161
1162 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1163 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1164 /// should not be used elsewhere.
1165 void EmitCurrentDiagnostic(unsigned DiagID);
1166
1167 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1168 /// statements.
1169 class FPContractStateRAII {
1170 public:
1171 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1172 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1173
1174 private:
1175 Sema& S;
1176 FPOptions OldFPFeaturesState;
1177 };
1178
1179 void addImplicitTypedef(StringRef Name, QualType T);
1180
1181public:
1182 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1183 TranslationUnitKind TUKind = TU_Complete,
1184 CodeCompleteConsumer *CompletionConsumer = nullptr);
1185 ~Sema();
1186
1187 /// \brief Perform initialization that occurs after the parser has been
1188 /// initialized but before it parses anything.
1189 void Initialize();
1190
1191 const LangOptions &getLangOpts() const { return LangOpts; }
1192 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1193 FPOptions &getFPOptions() { return FPFeatures; }
1194
1195 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1196 SourceManager &getSourceManager() const { return SourceMgr; }
1197 Preprocessor &getPreprocessor() const { return PP; }
1198 ASTContext &getASTContext() const { return Context; }
1199 ASTConsumer &getASTConsumer() const { return Consumer; }
1200 ASTMutationListener *getASTMutationListener() const;
1201 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1202
1203 ///\brief Registers an external source. If an external source already exists,
1204 /// creates a multiplex external source and appends to it.
1205 ///
1206 ///\param[in] E - A non-null external sema source.
1207 ///
1208 void addExternalSource(ExternalSemaSource *E);
1209
1210 void PrintStats() const;
1211
1212 /// \brief Helper class that creates diagnostics with optional
1213 /// template instantiation stacks.
1214 ///
1215 /// This class provides a wrapper around the basic DiagnosticBuilder
1216 /// class that emits diagnostics. SemaDiagnosticBuilder is
1217 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1218 /// does) and, if the diagnostic comes from inside a template
1219 /// instantiation, printing the template instantiation stack as
1220 /// well.
1221 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1222 Sema &SemaRef;
1223 unsigned DiagID;
1224
1225 public:
1226 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1227 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1228
1229 // This is a cunning lie. DiagnosticBuilder actually performs move
1230 // construction in its copy constructor (but due to varied uses, it's not
1231 // possible to conveniently express this as actual move construction). So
1232 // the default copy ctor here is fine, because the base class disables the
1233 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1234 // in that case anwyay.
1235 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1236
1237 ~SemaDiagnosticBuilder() {
1238 // If we aren't active, there is nothing to do.
1239 if (!isActive()) return;
1240
1241 // Otherwise, we need to emit the diagnostic. First flush the underlying
1242 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1243 // won't emit the diagnostic in its own destructor.
1244 //
1245 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1246 // do its own needless checks to see if the diagnostic needs to be
1247 // emitted. However, because we take care to ensure that the builder
1248 // objects never escape, a sufficiently smart compiler will be able to
1249 // eliminate that code.
1250 FlushCounts();
1251 Clear();
1252
1253 // Dispatch to Sema to emit the diagnostic.
1254 SemaRef.EmitCurrentDiagnostic(DiagID);
1255 }
1256
1257 /// Teach operator<< to produce an object of the correct type.
1258 template<typename T>
1259 friend const SemaDiagnosticBuilder &operator<<(
1260 const SemaDiagnosticBuilder &Diag, const T &Value) {
1261 const DiagnosticBuilder &BaseDiag = Diag;
1262 BaseDiag << Value;
1263 return Diag;
1264 }
1265 };
1266
1267 /// \brief Emit a diagnostic.
1268 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1269 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1270 return SemaDiagnosticBuilder(DB, *this, DiagID);
1271 }
1272
1273 /// \brief Emit a partial diagnostic.
1274 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1275
1276 /// \brief Build a partial diagnostic.
1277 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1278
1279 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1280
1281 /// \brief Get a string to suggest for zero-initialization of a type.
1282 std::string
1283 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1284 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1285
1286 /// \brief Calls \c Lexer::getLocForEndOfToken()
1287 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1288
1289 /// \brief Retrieve the module loader associated with the preprocessor.
1290 ModuleLoader &getModuleLoader() const;
1291
1292 void emitAndClearUnusedLocalTypedefWarnings();
1293
1294 void ActOnStartOfTranslationUnit();
1295 void ActOnEndOfTranslationUnit();
1296
1297 void CheckDelegatingCtorCycles();
1298
1299 Scope *getScopeForContext(DeclContext *Ctx);
1300
1301 void PushFunctionScope();
1302 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1303 sema::LambdaScopeInfo *PushLambdaScope();
1304
1305 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1306 /// is during Parsing. Currently it is used to pass on the depth
1307 /// when parsing generic lambda 'auto' parameters.
1308 void RecordParsingTemplateParameterDepth(unsigned Depth);
1309
1310 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1311 RecordDecl *RD,
1312 CapturedRegionKind K);
1313 void
1314 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1315 const Decl *D = nullptr,
1316 const BlockExpr *blkExpr = nullptr);
1317
1318 sema::FunctionScopeInfo *getCurFunction() const {
1319 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1320 }
1321
1322 sema::FunctionScopeInfo *getEnclosingFunction() const;
1323
1324 void setFunctionHasBranchIntoScope();
1325 void setFunctionHasBranchProtectedScope();
1326 void setFunctionHasIndirectGoto();
1327
1328 void PushCompoundScope(bool IsStmtExpr);
1329 void PopCompoundScope();
1330
1331 sema::CompoundScopeInfo &getCurCompoundScope() const;
1332
1333 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1334
1335 /// \brief Retrieve the current block, if any.
1336 sema::BlockScopeInfo *getCurBlock();
1337
1338 /// Retrieve the current lambda scope info, if any.
1339 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1340 /// lambda scope info ignoring all inner capturing scopes that are not
1341 /// lambda scopes.
1342 sema::LambdaScopeInfo *
1343 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1344
1345 /// \brief Retrieve the current generic lambda info, if any.
1346 sema::LambdaScopeInfo *getCurGenericLambda();
1347
1348 /// \brief Retrieve the current captured region, if any.
1349 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1350
1351 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1352 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1353
1354 void ActOnComment(SourceRange Comment);
1355
1356 //===--------------------------------------------------------------------===//
1357 // Type Analysis / Processing: SemaType.cpp.
1358 //
1359
1360 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1361 const DeclSpec *DS = nullptr);
1362 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1363 const DeclSpec *DS = nullptr);
1364 QualType BuildPointerType(QualType T,
1365 SourceLocation Loc, DeclarationName Entity);
1366 QualType BuildReferenceType(QualType T, bool LValueRef,
1367 SourceLocation Loc, DeclarationName Entity);
1368 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1369 Expr *ArraySize, unsigned Quals,
1370 SourceRange Brackets, DeclarationName Entity);
1371 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1372 SourceLocation AttrLoc);
1373 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1374 SourceLocation AttrLoc);
1375
1376 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1377
1378 /// \brief Build a function type.
1379 ///
1380 /// This routine checks the function type according to C++ rules and
1381 /// under the assumption that the result type and parameter types have
1382 /// just been instantiated from a template. It therefore duplicates
1383 /// some of the behavior of GetTypeForDeclarator, but in a much
1384 /// simpler form that is only suitable for this narrow use case.
1385 ///
1386 /// \param T The return type of the function.
1387 ///
1388 /// \param ParamTypes The parameter types of the function. This array
1389 /// will be modified to account for adjustments to the types of the
1390 /// function parameters.
1391 ///
1392 /// \param Loc The location of the entity whose type involves this
1393 /// function type or, if there is no such entity, the location of the
1394 /// type that will have function type.
1395 ///
1396 /// \param Entity The name of the entity that involves the function
1397 /// type, if known.
1398 ///
1399 /// \param EPI Extra information about the function type. Usually this will
1400 /// be taken from an existing function with the same prototype.
1401 ///
1402 /// \returns A suitable function type, if there are no errors. The
1403 /// unqualified type will always be a FunctionProtoType.
1404 /// Otherwise, returns a NULL type.
1405 QualType BuildFunctionType(QualType T,
1406 MutableArrayRef<QualType> ParamTypes,
1407 SourceLocation Loc, DeclarationName Entity,
1408 const FunctionProtoType::ExtProtoInfo &EPI);
1409
1410 QualType BuildMemberPointerType(QualType T, QualType Class,
1411 SourceLocation Loc,
1412 DeclarationName Entity);
1413 QualType BuildBlockPointerType(QualType T,
1414 SourceLocation Loc, DeclarationName Entity);
1415 QualType BuildParenType(QualType T);
1416 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1417 QualType BuildReadPipeType(QualType T,
1418 SourceLocation Loc);
1419 QualType BuildWritePipeType(QualType T,
1420 SourceLocation Loc);
1421
1422 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1423 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1424 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1425 TypeSourceInfo *ReturnTypeInfo);
1426
1427 /// \brief Package the given type and TSI into a ParsedType.
1428 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1429 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1430 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1431 static QualType GetTypeFromParser(ParsedType Ty,
1432 TypeSourceInfo **TInfo = nullptr);
1433 CanThrowResult canThrow(const Expr *E);
1434 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1435 const FunctionProtoType *FPT);
1436 void UpdateExceptionSpec(FunctionDecl *FD,
1437 const FunctionProtoType::ExceptionSpecInfo &ESI);
1438 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1439 bool CheckDistantExceptionSpec(QualType T);
1440 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1441 bool CheckEquivalentExceptionSpec(
1442 const FunctionProtoType *Old, SourceLocation OldLoc,
1443 const FunctionProtoType *New, SourceLocation NewLoc);
1444 bool CheckEquivalentExceptionSpec(
1445 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1446 const FunctionProtoType *Old, SourceLocation OldLoc,
1447 const FunctionProtoType *New, SourceLocation NewLoc);
1448 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1449 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1450 const PartialDiagnostic &NestedDiagID,
1451 const PartialDiagnostic &NoteID,
1452 const FunctionProtoType *Superset,
1453 SourceLocation SuperLoc,
1454 const FunctionProtoType *Subset,
1455 SourceLocation SubLoc);
1456 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1457 const PartialDiagnostic &NoteID,
1458 const FunctionProtoType *Target,
1459 SourceLocation TargetLoc,
1460 const FunctionProtoType *Source,
1461 SourceLocation SourceLoc);
1462
1463 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1464
1465 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1466 /// in an Objective-C message declaration. Return the appropriate type.
1467 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1468
1469 /// \brief Abstract class used to diagnose incomplete types.
1470 struct TypeDiagnoser {
1471 TypeDiagnoser() {}
1472
1473 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1474 virtual ~TypeDiagnoser() {}
1475 };
1476
1477 static int getPrintable(int I) { return I; }
1478 static unsigned getPrintable(unsigned I) { return I; }
1479 static bool getPrintable(bool B) { return B; }
1480 static const char * getPrintable(const char *S) { return S; }
1481 static StringRef getPrintable(StringRef S) { return S; }
1482 static const std::string &getPrintable(const std::string &S) { return S; }
1483 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1484 return II;
1485 }
1486 static DeclarationName getPrintable(DeclarationName N) { return N; }
1487 static QualType getPrintable(QualType T) { return T; }
1488 static SourceRange getPrintable(SourceRange R) { return R; }
1489 static SourceRange getPrintable(SourceLocation L) { return L; }
1490 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1491 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1492
1493 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1494 unsigned DiagID;
1495 std::tuple<const Ts &...> Args;
1496
1497 template <std::size_t... Is>
1498 void emit(const SemaDiagnosticBuilder &DB,
1499 llvm::index_sequence<Is...>) const {
1500 // Apply all tuple elements to the builder in order.
1501 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1502 (void)Dummy;
1503 }
1504
1505 public:
1506 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1507 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1508 assert(DiagID != 0 && "no diagnostic for type diagnoser")(static_cast <bool> (DiagID != 0 && "no diagnostic for type diagnoser"
) ? void (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 1508, __extension__ __PRETTY_FUNCTION__))
;
1509 }
1510
1511 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1512 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1513 emit(DB, llvm::index_sequence_for<Ts...>());
1514 DB << T;
1515 }
1516 };
1517
1518private:
1519 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1520 TypeDiagnoser *Diagnoser);
1521
1522 struct ModuleScope {
1523 clang::Module *Module = nullptr;
1524 bool ModuleInterface = false;
1525 VisibleModuleSet OuterVisibleModules;
1526 };
1527 /// The modules we're currently parsing.
1528 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1529
1530 /// Get the module whose scope we are currently within.
1531 Module *getCurrentModule() const {
1532 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1533 }
1534
1535 VisibleModuleSet VisibleModules;
1536
1537public:
1538 /// \brief Get the module owning an entity.
1539 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1540
1541 /// \brief Make a merged definition of an existing hidden definition \p ND
1542 /// visible at the specified location.
1543 void makeMergedDefinitionVisible(NamedDecl *ND);
1544
1545 bool isModuleVisible(const Module *M) { return VisibleModules.isVisible(M); }
1546
1547 /// Determine whether a declaration is visible to name lookup.
1548 bool isVisible(const NamedDecl *D) {
1549 return !D->isHidden() || isVisibleSlow(D);
1550 }
1551
1552 /// Determine whether any declaration of an entity is visible.
1553 bool
1554 hasVisibleDeclaration(const NamedDecl *D,
1555 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1556 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1557 }
1558 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1559 llvm::SmallVectorImpl<Module *> *Modules);
1560
1561 bool hasVisibleMergedDefinition(NamedDecl *Def);
1562 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1563
1564 /// Determine if \p D and \p Suggested have a structurally compatible
1565 /// layout as described in C11 6.2.7/1.
1566 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1567
1568 /// Determine if \p D has a visible definition. If not, suggest a declaration
1569 /// that should be made visible to expose the definition.
1570 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1571 bool OnlyNeedComplete = false);
1572 bool hasVisibleDefinition(const NamedDecl *D) {
1573 NamedDecl *Hidden;
1574 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1575 }
1576
1577 /// Determine if the template parameter \p D has a visible default argument.
1578 bool
1579 hasVisibleDefaultArgument(const NamedDecl *D,
1580 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1581
1582 /// Determine if there is a visible declaration of \p D that is an explicit
1583 /// specialization declaration for a specialization of a template. (For a
1584 /// member specialization, use hasVisibleMemberSpecialization.)
1585 bool hasVisibleExplicitSpecialization(
1586 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1587
1588 /// Determine if there is a visible declaration of \p D that is a member
1589 /// specialization declaration (as opposed to an instantiated declaration).
1590 bool hasVisibleMemberSpecialization(
1591 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1592
1593 /// Determine if \p A and \p B are equivalent internal linkage declarations
1594 /// from different modules, and thus an ambiguity error can be downgraded to
1595 /// an extension warning.
1596 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1597 const NamedDecl *B);
1598 void diagnoseEquivalentInternalLinkageDeclarations(
1599 SourceLocation Loc, const NamedDecl *D,
1600 ArrayRef<const NamedDecl *> Equiv);
1601
1602 bool isCompleteType(SourceLocation Loc, QualType T) {
1603 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1604 }
1605 bool RequireCompleteType(SourceLocation Loc, QualType T,
1606 TypeDiagnoser &Diagnoser);
1607 bool RequireCompleteType(SourceLocation Loc, QualType T,
1608 unsigned DiagID);
1609
1610 template <typename... Ts>
1611 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1612 const Ts &...Args) {
1613 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1614 return RequireCompleteType(Loc, T, Diagnoser);
1615 }
1616
1617 void completeExprArrayBound(Expr *E);
1618 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1619 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1620
1621 template <typename... Ts>
1622 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1623 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1624 return RequireCompleteExprType(E, Diagnoser);
1625 }
1626
1627 bool RequireLiteralType(SourceLocation Loc, QualType T,
1628 TypeDiagnoser &Diagnoser);
1629 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1630
1631 template <typename... Ts>
1632 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1633 const Ts &...Args) {
1634 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1635 return RequireLiteralType(Loc, T, Diagnoser);
1636 }
1637
1638 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1639 const CXXScopeSpec &SS, QualType T);
1640
1641 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1642 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1643 /// context, such as when building a type for decltype(auto).
1644 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1645 bool AsUnevaluated = true);
1646 QualType BuildUnaryTransformType(QualType BaseType,
1647 UnaryTransformType::UTTKind UKind,
1648 SourceLocation Loc);
1649
1650 //===--------------------------------------------------------------------===//
1651 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1652 //
1653
1654 struct SkipBodyInfo {
1655 SkipBodyInfo()
1656 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1657 New(nullptr) {}
1658 bool ShouldSkip;
1659 bool CheckSameAsPrevious;
1660 NamedDecl *Previous;
1661 NamedDecl *New;
1662 };
1663
1664 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1665
1666 void DiagnoseUseOfUnimplementedSelectors();
1667
1668 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1669
1670 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1671 Scope *S, CXXScopeSpec *SS = nullptr,
1672 bool isClassName = false, bool HasTrailingDot = false,
1673 ParsedType ObjectType = nullptr,
1674 bool IsCtorOrDtorName = false,
1675 bool WantNontrivialTypeSourceInfo = false,
1676 bool IsClassTemplateDeductionContext = true,
1677 IdentifierInfo **CorrectedII = nullptr);
1678 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1679 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1680 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1681 SourceLocation IILoc,
1682 Scope *S,
1683 CXXScopeSpec *SS,
1684 ParsedType &SuggestedType,
1685 bool IsTemplateName = false);
1686
1687 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1688 /// type name has failed in a dependent context. In these situations, we
1689 /// automatically form a DependentTypeName that will retry lookup in a related
1690 /// scope during instantiation.
1691 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1692 SourceLocation NameLoc,
1693 bool IsTemplateTypeArg);
1694
1695 /// \brief Describes the result of the name lookup and resolution performed
1696 /// by \c ClassifyName().
1697 enum NameClassificationKind {
1698 NC_Unknown,
1699 NC_Error,
1700 NC_Keyword,
1701 NC_Type,
1702 NC_Expression,
1703 NC_NestedNameSpecifier,
1704 NC_TypeTemplate,
1705 NC_VarTemplate,
1706 NC_FunctionTemplate
1707 };
1708
1709 class NameClassification {
1710 NameClassificationKind Kind;
1711 ExprResult Expr;
1712 TemplateName Template;
1713 ParsedType Type;
1714
1715 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1716
1717 public:
1718 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1719
1720 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1721
1722 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1723
1724 static NameClassification Error() {
1725 return NameClassification(NC_Error);
1726 }
1727
1728 static NameClassification Unknown() {
1729 return NameClassification(NC_Unknown);
1730 }
1731
1732 static NameClassification NestedNameSpecifier() {
1733 return NameClassification(NC_NestedNameSpecifier);
1734 }
1735
1736 static NameClassification TypeTemplate(TemplateName Name) {
1737 NameClassification Result(NC_TypeTemplate);
1738 Result.Template = Name;
1739 return Result;
1740 }
1741
1742 static NameClassification VarTemplate(TemplateName Name) {
1743 NameClassification Result(NC_VarTemplate);
1744 Result.Template = Name;
1745 return Result;
1746 }
1747
1748 static NameClassification FunctionTemplate(TemplateName Name) {
1749 NameClassification Result(NC_FunctionTemplate);
1750 Result.Template = Name;
1751 return Result;
1752 }
1753
1754 NameClassificationKind getKind() const { return Kind; }
1755
1756 ParsedType getType() const {
1757 assert(Kind == NC_Type)(static_cast <bool> (Kind == NC_Type) ? void (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 1757, __extension__ __PRETTY_FUNCTION__))
;
1758 return Type;
1759 }
1760
1761 ExprResult getExpression() const {
1762 assert(Kind == NC_Expression)(static_cast <bool> (Kind == NC_Expression) ? void (0) :
__assert_fail ("Kind == NC_Expression", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 1762, __extension__ __PRETTY_FUNCTION__))
;
1763 return Expr;
1764 }
1765
1766 TemplateName getTemplateName() const {
1767 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 1768, __extension__ __PRETTY_FUNCTION__))
1768 Kind == NC_VarTemplate)(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 1768, __extension__ __PRETTY_FUNCTION__))
;
1769 return Template;
1770 }
1771
1772 TemplateNameKind getTemplateNameKind() const {
1773 switch (Kind) {
1774 case NC_TypeTemplate:
1775 return TNK_Type_template;
1776 case NC_FunctionTemplate:
1777 return TNK_Function_template;
1778 case NC_VarTemplate:
1779 return TNK_Var_template;
1780 default:
1781 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 1781)
;
1782 }
1783 }
1784 };
1785
1786 /// \brief Perform name lookup on the given name, classifying it based on
1787 /// the results of name lookup and the following token.
1788 ///
1789 /// This routine is used by the parser to resolve identifiers and help direct
1790 /// parsing. When the identifier cannot be found, this routine will attempt
1791 /// to correct the typo and classify based on the resulting name.
1792 ///
1793 /// \param S The scope in which we're performing name lookup.
1794 ///
1795 /// \param SS The nested-name-specifier that precedes the name.
1796 ///
1797 /// \param Name The identifier. If typo correction finds an alternative name,
1798 /// this pointer parameter will be updated accordingly.
1799 ///
1800 /// \param NameLoc The location of the identifier.
1801 ///
1802 /// \param NextToken The token following the identifier. Used to help
1803 /// disambiguate the name.
1804 ///
1805 /// \param IsAddressOfOperand True if this name is the operand of a unary
1806 /// address of ('&') expression, assuming it is classified as an
1807 /// expression.
1808 ///
1809 /// \param CCC The correction callback, if typo correction is desired.
1810 NameClassification
1811 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1812 SourceLocation NameLoc, const Token &NextToken,
1813 bool IsAddressOfOperand,
1814 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1815
1816 /// Describes the detailed kind of a template name. Used in diagnostics.
1817 enum class TemplateNameKindForDiagnostics {
1818 ClassTemplate,
1819 FunctionTemplate,
1820 VarTemplate,
1821 AliasTemplate,
1822 TemplateTemplateParam,
1823 DependentTemplate
1824 };
1825 TemplateNameKindForDiagnostics
1826 getTemplateNameKindForDiagnostics(TemplateName Name);
1827
1828 /// Determine whether it's plausible that E was intended to be a
1829 /// template-name.
1830 bool mightBeIntendedToBeTemplateName(ExprResult E) {
1831 if (!getLangOpts().CPlusPlus || E.isInvalid())
1832 return false;
1833 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
1834 return !DRE->hasExplicitTemplateArgs();
1835 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
1836 return !ME->hasExplicitTemplateArgs();
1837 // Any additional cases recognized here should also be handled by
1838 // diagnoseExprIntendedAsTemplateName.
1839 return false;
1840 }
1841 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
1842 SourceLocation Less,
1843 SourceLocation Greater);
1844
1845 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1846
1847 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1848 MultiTemplateParamsArg TemplateParameterLists);
1849 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1850 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1851 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1852 DeclarationName Name, SourceLocation Loc,
1853 bool IsTemplateId);
1854 void
1855 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1856 SourceLocation FallbackLoc,
1857 SourceLocation ConstQualLoc = SourceLocation(),
1858 SourceLocation VolatileQualLoc = SourceLocation(),
1859 SourceLocation RestrictQualLoc = SourceLocation(),
1860 SourceLocation AtomicQualLoc = SourceLocation(),
1861 SourceLocation UnalignedQualLoc = SourceLocation());
1862
1863 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1864 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1865 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1866 const LookupResult &R);
1867 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1868 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1869 const LookupResult &R);
1870 void CheckShadow(Scope *S, VarDecl *D);
1871
1872 /// Warn if 'E', which is an expression that is about to be modified, refers
1873 /// to a shadowing declaration.
1874 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1875
1876 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1877
1878private:
1879 /// Map of current shadowing declarations to shadowed declarations. Warn if
1880 /// it looks like the user is trying to modify the shadowing declaration.
1881 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1882
1883public:
1884 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1885 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1886 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1887 TypedefNameDecl *NewTD);
1888 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1889 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1890 TypeSourceInfo *TInfo,
1891 LookupResult &Previous);
1892 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1893 LookupResult &Previous, bool &Redeclaration);
1894 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1895 TypeSourceInfo *TInfo,
1896 LookupResult &Previous,
1897 MultiTemplateParamsArg TemplateParamLists,
1898 bool &AddToScope,
1899 ArrayRef<BindingDecl *> Bindings = None);
1900 NamedDecl *
1901 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1902 MultiTemplateParamsArg TemplateParamLists);
1903 // Returns true if the variable declaration is a redeclaration
1904 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1905 void CheckVariableDeclarationType(VarDecl *NewVD);
1906 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1907 Expr *Init);
1908 void CheckCompleteVariableDeclaration(VarDecl *VD);
1909 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1910 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1911
1912 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1913 TypeSourceInfo *TInfo,
1914 LookupResult &Previous,
1915 MultiTemplateParamsArg TemplateParamLists,
1916 bool &AddToScope);
1917 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1918
1919 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1920 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1921
1922 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1923 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1924 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1925 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1926 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1927 // Returns true if the function declaration is a redeclaration
1928 bool CheckFunctionDeclaration(Scope *S,
1929 FunctionDecl *NewFD, LookupResult &Previous,
1930 bool IsMemberSpecialization);
1931 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1932 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1933 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1934 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1935 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1936 SourceLocation Loc,
1937 QualType T);
1938 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1939 SourceLocation NameLoc, IdentifierInfo *Name,
1940 QualType T, TypeSourceInfo *TSInfo,
1941 StorageClass SC);
1942 void ActOnParamDefaultArgument(Decl *param,
1943 SourceLocation EqualLoc,
1944 Expr *defarg);
1945 void ActOnParamUnparsedDefaultArgument(Decl *param,
1946 SourceLocation EqualLoc,
1947 SourceLocation ArgLoc);
1948 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1949 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1950 SourceLocation EqualLoc);
1951
1952 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1953 void ActOnUninitializedDecl(Decl *dcl);
1954 void ActOnInitializerError(Decl *Dcl);
1955
1956 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1957 void ActOnCXXForRangeDecl(Decl *D);
1958 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1959 IdentifierInfo *Ident,
1960 ParsedAttributes &Attrs,
1961 SourceLocation AttrEnd);
1962 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1963 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1964 void FinalizeDeclaration(Decl *D);
1965 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1966 ArrayRef<Decl *> Group);
1967 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1968
1969 /// Should be called on all declarations that might have attached
1970 /// documentation comments.
1971 void ActOnDocumentableDecl(Decl *D);
1972 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1973
1974 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1975 SourceLocation LocAfterDecls);
1976 void CheckForFunctionRedefinition(
1977 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1978 SkipBodyInfo *SkipBody = nullptr);
1979 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1980 MultiTemplateParamsArg TemplateParamLists,
1981 SkipBodyInfo *SkipBody = nullptr);
1982 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1983 SkipBodyInfo *SkipBody = nullptr);
1984 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1985 bool isObjCMethodDecl(Decl *D) {
1986 return D && isa<ObjCMethodDecl>(D);
1987 }
1988
1989 /// \brief Determine whether we can delay parsing the body of a function or
1990 /// function template until it is used, assuming we don't care about emitting
1991 /// code for that function.
1992 ///
1993 /// This will be \c false if we may need the body of the function in the
1994 /// middle of parsing an expression (where it's impractical to switch to
1995 /// parsing a different function), for instance, if it's constexpr in C++11
1996 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1997 bool canDelayFunctionBody(const Declarator &D);
1998
1999 /// \brief Determine whether we can skip parsing the body of a function
2000 /// definition, assuming we don't care about analyzing its body or emitting
2001 /// code for that function.
2002 ///
2003 /// This will be \c false only if we may need the body of the function in
2004 /// order to parse the rest of the program (for instance, if it is
2005 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2006 bool canSkipFunctionBody(Decl *D);
2007
2008 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2009 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2010 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2011 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2012 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2013
2014 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2015 /// attribute for which parsing is delayed.
2016 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2017
2018 /// \brief Diagnose any unused parameters in the given sequence of
2019 /// ParmVarDecl pointers.
2020 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2021
2022 /// \brief Diagnose whether the size of parameters or return value of a
2023 /// function or obj-c method definition is pass-by-value and larger than a
2024 /// specified threshold.
2025 void
2026 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2027 QualType ReturnTy, NamedDecl *D);
2028
2029 void DiagnoseInvalidJumps(Stmt *Body);
2030 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2031 SourceLocation AsmLoc,
2032 SourceLocation RParenLoc);
2033
2034 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
2035 Decl *ActOnEmptyDeclaration(Scope *S,
2036 AttributeList *AttrList,
2037 SourceLocation SemiLoc);
2038
2039 enum class ModuleDeclKind {
2040 Interface, ///< 'export module X;'
2041 Implementation, ///< 'module X;'
2042 Partition, ///< 'module partition X;'
2043 };
2044
2045 /// The parser has processed a module-declaration that begins the definition
2046 /// of a module interface or implementation.
2047 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2048 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2049 ModuleIdPath Path);
2050
2051 /// \brief The parser has processed a module import declaration.
2052 ///
2053 /// \param AtLoc The location of the '@' symbol, if any.
2054 ///
2055 /// \param ImportLoc The location of the 'import' keyword.
2056 ///
2057 /// \param Path The module access path.
2058 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
2059 ModuleIdPath Path);
2060
2061 /// \brief The parser has processed a module import translated from a
2062 /// #include or similar preprocessing directive.
2063 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2064 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2065
2066 /// \brief The parsed has entered a submodule.
2067 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2068 /// \brief The parser has left a submodule.
2069 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2070
2071 /// \brief Create an implicit import of the given module at the given
2072 /// source location, for error recovery, if possible.
2073 ///
2074 /// This routine is typically used when an entity found by name lookup
2075 /// is actually hidden within a module that we know about but the user
2076 /// has forgotten to import.
2077 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2078 Module *Mod);
2079
2080 /// Kinds of missing import. Note, the values of these enumerators correspond
2081 /// to %select values in diagnostics.
2082 enum class MissingImportKind {
2083 Declaration,
2084 Definition,
2085 DefaultArgument,
2086 ExplicitSpecialization,
2087 PartialSpecialization
2088 };
2089
2090 /// \brief Diagnose that the specified declaration needs to be visible but
2091 /// isn't, and suggest a module import that would resolve the problem.
2092 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2093 MissingImportKind MIK, bool Recover = true);
2094 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2095 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2096 MissingImportKind MIK, bool Recover);
2097
2098 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2099 SourceLocation LBraceLoc);
2100 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2101 SourceLocation RBraceLoc);
2102
2103 /// \brief We've found a use of a templated declaration that would trigger an
2104 /// implicit instantiation. Check that any relevant explicit specializations
2105 /// and partial specializations are visible, and diagnose if not.
2106 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2107
2108 /// \brief We've found a use of a template specialization that would select a
2109 /// partial specialization. Check that the partial specialization is visible,
2110 /// and diagnose if not.
2111 void checkPartialSpecializationVisibility(SourceLocation Loc,
2112 NamedDecl *Spec);
2113
2114 /// \brief Retrieve a suitable printing policy.
2115 PrintingPolicy getPrintingPolicy() const {
2116 return getPrintingPolicy(Context, PP);
2117 }
2118
2119 /// \brief Retrieve a suitable printing policy.
2120 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2121 const Preprocessor &PP);
2122
2123 /// Scope actions.
2124 void ActOnPopScope(SourceLocation Loc, Scope *S);
2125 void ActOnTranslationUnitScope(Scope *S);
2126
2127 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2128 RecordDecl *&AnonRecord);
2129 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2130 MultiTemplateParamsArg TemplateParams,
2131 bool IsExplicitInstantiation,
2132 RecordDecl *&AnonRecord);
2133
2134 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2135 AccessSpecifier AS,
2136 RecordDecl *Record,
2137 const PrintingPolicy &Policy);
2138
2139 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2140 RecordDecl *Record);
2141
2142 /// Common ways to introduce type names without a tag for use in diagnostics.
2143 /// Keep in sync with err_tag_reference_non_tag.
2144 enum NonTagKind {
2145 NTK_NonStruct,
2146 NTK_NonClass,
2147 NTK_NonUnion,
2148 NTK_NonEnum,
2149 NTK_Typedef,
2150 NTK_TypeAlias,
2151 NTK_Template,
2152 NTK_TypeAliasTemplate,
2153 NTK_TemplateTemplateArgument,
2154 };
2155
2156 /// Given a non-tag type declaration, returns an enum useful for indicating
2157 /// what kind of non-tag type this is.
2158 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2159
2160 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2161 TagTypeKind NewTag, bool isDefinition,
2162 SourceLocation NewTagLoc,
2163 const IdentifierInfo *Name);
2164
2165 enum TagUseKind {
2166 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2167 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2168 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2169 TUK_Friend // Friend declaration: 'friend struct foo;'
2170 };
2171
2172 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2173 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2174 SourceLocation NameLoc, AttributeList *Attr,
2175 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2176 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2177 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2178 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2179 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2180 SkipBodyInfo *SkipBody = nullptr);
2181
2182 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2183 unsigned TagSpec, SourceLocation TagLoc,
2184 CXXScopeSpec &SS,
2185 IdentifierInfo *Name, SourceLocation NameLoc,
2186 AttributeList *Attr,
2187 MultiTemplateParamsArg TempParamLists);
2188
2189 TypeResult ActOnDependentTag(Scope *S,
2190 unsigned TagSpec,
2191 TagUseKind TUK,
2192 const CXXScopeSpec &SS,
2193 IdentifierInfo *Name,
2194 SourceLocation TagLoc,
2195 SourceLocation NameLoc);
2196
2197 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2198 IdentifierInfo *ClassName,
2199 SmallVectorImpl<Decl *> &Decls);
2200 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2201 Declarator &D, Expr *BitfieldWidth);
2202
2203 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2204 Declarator &D, Expr *BitfieldWidth,
2205 InClassInitStyle InitStyle,
2206 AccessSpecifier AS);
2207 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2208 SourceLocation DeclStart,
2209 Declarator &D, Expr *BitfieldWidth,
2210 InClassInitStyle InitStyle,
2211 AccessSpecifier AS,
2212 AttributeList *MSPropertyAttr);
2213
2214 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2215 TypeSourceInfo *TInfo,
2216 RecordDecl *Record, SourceLocation Loc,
2217 bool Mutable, Expr *BitfieldWidth,
2218 InClassInitStyle InitStyle,
2219 SourceLocation TSSL,
2220 AccessSpecifier AS, NamedDecl *PrevDecl,
2221 Declarator *D = nullptr);
2222
2223 bool CheckNontrivialField(FieldDecl *FD);
2224 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2225
2226 enum TrivialABIHandling {
2227 /// The triviality of a method unaffected by "trivial_abi".
2228 TAH_IgnoreTrivialABI,
2229
2230 /// The triviality of a method affected by "trivial_abi".
2231 TAH_ConsiderTrivialABI
2232 };
2233
2234 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2235 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2236 bool Diagnose = false);
2237 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2238 void ActOnLastBitfield(SourceLocation DeclStart,
2239 SmallVectorImpl<Decl *> &AllIvarDecls);
2240 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2241 Declarator &D, Expr *BitfieldWidth,
2242 tok::ObjCKeywordKind visibility);
2243
2244 // This is used for both record definitions and ObjC interface declarations.
2245 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2246 ArrayRef<Decl *> Fields,
2247 SourceLocation LBrac, SourceLocation RBrac,
2248 AttributeList *AttrList);
2249
2250 /// ActOnTagStartDefinition - Invoked when we have entered the
2251 /// scope of a tag's definition (e.g., for an enumeration, class,
2252 /// struct, or union).
2253 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2254
2255 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2256 /// Differently from C++, actually parse the body and reject / error out
2257 /// in case of a structural mismatch.
2258 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2259 SkipBodyInfo &SkipBody);
2260
2261 typedef void *SkippedDefinitionContext;
2262
2263 /// \brief Invoked when we enter a tag definition that we're skipping.
2264 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2265
2266 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2267
2268 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2269 /// C++ record definition's base-specifiers clause and are starting its
2270 /// member declarations.
2271 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2272 SourceLocation FinalLoc,
2273 bool IsFinalSpelledSealed,
2274 SourceLocation LBraceLoc);
2275
2276 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2277 /// the definition of a tag (enumeration, class, struct, or union).
2278 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2279 SourceRange BraceRange);
2280
2281 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2282
2283 void ActOnObjCContainerFinishDefinition();
2284
2285 /// \brief Invoked when we must temporarily exit the objective-c container
2286 /// scope for parsing/looking-up C constructs.
2287 ///
2288 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2289 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2290 void ActOnObjCReenterContainerContext(DeclContext *DC);
2291
2292 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2293 /// error parsing the definition of a tag.
2294 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2295
2296 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2297 EnumConstantDecl *LastEnumConst,
2298 SourceLocation IdLoc,
2299 IdentifierInfo *Id,
2300 Expr *val);
2301 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2302 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2303 QualType EnumUnderlyingTy, bool IsFixed,
2304 const EnumDecl *Prev);
2305
2306 /// Determine whether the body of an anonymous enumeration should be skipped.
2307 /// \param II The name of the first enumerator.
2308 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2309 SourceLocation IILoc);
2310
2311 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2312 SourceLocation IdLoc, IdentifierInfo *Id,
2313 AttributeList *Attrs, SourceLocation EqualLoc,
2314 Expr *Val);
2315 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2316 Decl *EnumDecl,
2317 ArrayRef<Decl *> Elements,
2318 Scope *S, AttributeList *Attr);
2319
2320 DeclContext *getContainingDC(DeclContext *DC);
2321
2322 /// Set the current declaration context until it gets popped.
2323 void PushDeclContext(Scope *S, DeclContext *DC);
2324 void PopDeclContext();
2325
2326 /// EnterDeclaratorContext - Used when we must lookup names in the context
2327 /// of a declarator's nested name specifier.
2328 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2329 void ExitDeclaratorContext(Scope *S);
2330
2331 /// Push the parameters of D, which must be a function, into scope.
2332 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2333 void ActOnExitFunctionContext();
2334
2335 DeclContext *getFunctionLevelDeclContext();
2336
2337 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2338 /// to the function decl for the function being parsed. If we're currently
2339 /// in a 'block', this returns the containing context.
2340 FunctionDecl *getCurFunctionDecl();
2341
2342 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2343 /// the method decl for the method being parsed. If we're currently
2344 /// in a 'block', this returns the containing context.
2345 ObjCMethodDecl *getCurMethodDecl();
2346
2347 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2348 /// or C function we're in, otherwise return null. If we're currently
2349 /// in a 'block', this returns the containing context.
2350 NamedDecl *getCurFunctionOrMethodDecl();
2351
2352 /// Add this decl to the scope shadowed decl chains.
2353 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2354
2355 /// \brief Make the given externally-produced declaration visible at the
2356 /// top level scope.
2357 ///
2358 /// \param D The externally-produced declaration to push.
2359 ///
2360 /// \param Name The name of the externally-produced declaration.
2361 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2362
2363 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2364 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2365 /// true if 'D' belongs to the given declaration context.
2366 ///
2367 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2368 /// enclosing namespace set of the context, rather than contained
2369 /// directly within it.
2370 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2371 bool AllowInlineNamespace = false);
2372
2373 /// Finds the scope corresponding to the given decl context, if it
2374 /// happens to be an enclosing scope. Otherwise return NULL.
2375 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2376
2377 /// Subroutines of ActOnDeclarator().
2378 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2379 TypeSourceInfo *TInfo);
2380 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2381
2382 /// \brief Describes the kind of merge to perform for availability
2383 /// attributes (including "deprecated", "unavailable", and "availability").
2384 enum AvailabilityMergeKind {
2385 /// \brief Don't merge availability attributes at all.
2386 AMK_None,
2387 /// \brief Merge availability attributes for a redeclaration, which requires
2388 /// an exact match.
2389 AMK_Redeclaration,
2390 /// \brief Merge availability attributes for an override, which requires
2391 /// an exact match or a weakening of constraints.
2392 AMK_Override,
2393 /// \brief Merge availability attributes for an implementation of
2394 /// a protocol requirement.
2395 AMK_ProtocolImplementation,
2396 };
2397
2398 /// Attribute merging methods. Return true if a new attribute was added.
2399 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2400 IdentifierInfo *Platform,
2401 bool Implicit,
2402 VersionTuple Introduced,
2403 VersionTuple Deprecated,
2404 VersionTuple Obsoleted,
2405 bool IsUnavailable,
2406 StringRef Message,
2407 bool IsStrict, StringRef Replacement,
2408 AvailabilityMergeKind AMK,
2409 unsigned AttrSpellingListIndex);
2410 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2411 TypeVisibilityAttr::VisibilityType Vis,
2412 unsigned AttrSpellingListIndex);
2413 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2414 VisibilityAttr::VisibilityType Vis,
2415 unsigned AttrSpellingListIndex);
2416 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2417 unsigned AttrSpellingListIndex, StringRef Uuid);
2418 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2419 unsigned AttrSpellingListIndex);
2420 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2421 unsigned AttrSpellingListIndex);
2422 MSInheritanceAttr *
2423 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2424 unsigned AttrSpellingListIndex,
2425 MSInheritanceAttr::Spelling SemanticSpelling);
2426 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2427 IdentifierInfo *Format, int FormatIdx,
2428 int FirstArg, unsigned AttrSpellingListIndex);
2429 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2430 unsigned AttrSpellingListIndex);
2431 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2432 IdentifierInfo *Ident,
2433 unsigned AttrSpellingListIndex);
2434 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2435 unsigned AttrSpellingListIndex);
2436 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2437 unsigned AttrSpellingListIndex);
2438 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2439 IdentifierInfo *Ident,
2440 unsigned AttrSpellingListIndex);
2441 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2442 unsigned AttrSpellingListIndex);
2443
2444 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2445 AvailabilityMergeKind AMK = AMK_Redeclaration);
2446 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2447 LookupResult &OldDecls);
2448 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2449 bool MergeTypeWithOld);
2450 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2451 Scope *S, bool MergeTypeWithOld);
2452 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2453 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2454 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2455 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2456 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2457 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2458 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2459
2460 // AssignmentAction - This is used by all the assignment diagnostic functions
2461 // to represent what is actually causing the operation
2462 enum AssignmentAction {
2463 AA_Assigning,
2464 AA_Passing,
2465 AA_Returning,
2466 AA_Converting,
2467 AA_Initializing,
2468 AA_Sending,
2469 AA_Casting,
2470 AA_Passing_CFAudited
2471 };
2472
2473 /// C++ Overloading.
2474 enum OverloadKind {
2475 /// This is a legitimate overload: the existing declarations are
2476 /// functions or function templates with different signatures.
2477 Ovl_Overload,
2478
2479 /// This is not an overload because the signature exactly matches
2480 /// an existing declaration.
2481 Ovl_Match,
2482
2483 /// This is not an overload because the lookup results contain a
2484 /// non-function.
2485 Ovl_NonFunction
2486 };
2487 OverloadKind CheckOverload(Scope *S,
2488 FunctionDecl *New,
2489 const LookupResult &OldDecls,
2490 NamedDecl *&OldDecl,
2491 bool IsForUsingDecl);
2492 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2493 bool ConsiderCudaAttrs = true);
2494
2495 /// \brief Checks availability of the function depending on the current
2496 /// function context.Inside an unavailable function,unavailability is ignored.
2497 ///
2498 /// \returns true if \p FD is unavailable and current context is inside
2499 /// an available function, false otherwise.
2500 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2501
2502 ImplicitConversionSequence
2503 TryImplicitConversion(Expr *From, QualType ToType,
2504 bool SuppressUserConversions,
2505 bool AllowExplicit,
2506 bool InOverloadResolution,
2507 bool CStyle,
2508 bool AllowObjCWritebackConversion);
2509
2510 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2511 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2512 bool IsComplexPromotion(QualType FromType, QualType ToType);
2513 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2514 bool InOverloadResolution,
2515 QualType& ConvertedType, bool &IncompatibleObjC);
2516 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2517 QualType& ConvertedType, bool &IncompatibleObjC);
2518 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2519 QualType &ConvertedType);
2520 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2521 QualType& ConvertedType);
2522 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2523 const FunctionProtoType *NewType,
2524 unsigned *ArgPos = nullptr);
2525 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2526 QualType FromType, QualType ToType);
2527
2528 void maybeExtendBlockObject(ExprResult &E);
2529 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2530 bool CheckPointerConversion(Expr *From, QualType ToType,
2531 CastKind &Kind,
2532 CXXCastPath& BasePath,
2533 bool IgnoreBaseAccess,
2534 bool Diagnose = true);
2535 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2536 bool InOverloadResolution,
2537 QualType &ConvertedType);
2538 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2539 CastKind &Kind,
2540 CXXCastPath &BasePath,
2541 bool IgnoreBaseAccess);
2542 bool IsQualificationConversion(QualType FromType, QualType ToType,
2543 bool CStyle, bool &ObjCLifetimeConversion);
2544 bool IsFunctionConversion(QualType FromType, QualType ToType,
2545 QualType &ResultTy);
2546 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2547 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2548
2549 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2550 const VarDecl *NRVOCandidate,
2551 QualType ResultType,
2552 Expr *Value,
2553 bool AllowNRVO = true);
2554
2555 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2556 ExprResult Init);
2557 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2558 SourceLocation EqualLoc,
2559 ExprResult Init,
2560 bool TopLevelOfInitList = false,
2561 bool AllowExplicit = false);
2562 ExprResult PerformObjectArgumentInitialization(Expr *From,
2563 NestedNameSpecifier *Qualifier,
2564 NamedDecl *FoundDecl,
2565 CXXMethodDecl *Method);
2566
2567 ExprResult PerformContextuallyConvertToBool(Expr *From);
2568 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2569
2570 /// Contexts in which a converted constant expression is required.
2571 enum CCEKind {
2572 CCEK_CaseValue, ///< Expression in a case label.
2573 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2574 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2575 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2576 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2577 };
2578 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2579 llvm::APSInt &Value, CCEKind CCE);
2580 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2581 APValue &Value, CCEKind CCE);
2582
2583 /// \brief Abstract base class used to perform a contextual implicit
2584 /// conversion from an expression to any type passing a filter.
2585 class ContextualImplicitConverter {
2586 public:
2587 bool Suppress;
2588 bool SuppressConversion;
2589
2590 ContextualImplicitConverter(bool Suppress = false,
2591 bool SuppressConversion = false)
2592 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2593
2594 /// \brief Determine whether the specified type is a valid destination type
2595 /// for this conversion.
2596 virtual bool match(QualType T) = 0;
2597
2598 /// \brief Emits a diagnostic complaining that the expression does not have
2599 /// integral or enumeration type.
2600 virtual SemaDiagnosticBuilder
2601 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2602
2603 /// \brief Emits a diagnostic when the expression has incomplete class type.
2604 virtual SemaDiagnosticBuilder
2605 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2606
2607 /// \brief Emits a diagnostic when the only matching conversion function
2608 /// is explicit.
2609 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2610 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2611
2612 /// \brief Emits a note for the explicit conversion function.
2613 virtual SemaDiagnosticBuilder
2614 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2615
2616 /// \brief Emits a diagnostic when there are multiple possible conversion
2617 /// functions.
2618 virtual SemaDiagnosticBuilder
2619 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2620
2621 /// \brief Emits a note for one of the candidate conversions.
2622 virtual SemaDiagnosticBuilder
2623 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2624
2625 /// \brief Emits a diagnostic when we picked a conversion function
2626 /// (for cases when we are not allowed to pick a conversion function).
2627 virtual SemaDiagnosticBuilder diagnoseConversion(
2628 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2629
2630 virtual ~ContextualImplicitConverter() {}
2631 };
2632
2633 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2634 bool AllowScopedEnumerations;
2635
2636 public:
2637 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2638 bool Suppress, bool SuppressConversion)
2639 : ContextualImplicitConverter(Suppress, SuppressConversion),
2640 AllowScopedEnumerations(AllowScopedEnumerations) {}
2641
2642 /// Match an integral or (possibly scoped) enumeration type.
2643 bool match(QualType T) override;
2644
2645 SemaDiagnosticBuilder
2646 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2647 return diagnoseNotInt(S, Loc, T);
2648 }
2649
2650 /// \brief Emits a diagnostic complaining that the expression does not have
2651 /// integral or enumeration type.
2652 virtual SemaDiagnosticBuilder
2653 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2654 };
2655
2656 /// Perform a contextual implicit conversion.
2657 ExprResult PerformContextualImplicitConversion(
2658 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2659
2660
2661 enum ObjCSubscriptKind {
2662 OS_Array,
2663 OS_Dictionary,
2664 OS_Error
2665 };
2666 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2667
2668 // Note that LK_String is intentionally after the other literals, as
2669 // this is used for diagnostics logic.
2670 enum ObjCLiteralKind {
2671 LK_Array,
2672 LK_Dictionary,
2673 LK_Numeric,
2674 LK_Boxed,
2675 LK_String,
2676 LK_Block,
2677 LK_None
2678 };
2679 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2680
2681 ExprResult PerformObjectMemberConversion(Expr *From,
2682 NestedNameSpecifier *Qualifier,
2683 NamedDecl *FoundDecl,
2684 NamedDecl *Member);
2685
2686 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2687 // TODO: make this is a typesafe union.
2688 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2689 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2690
2691 void AddOverloadCandidate(FunctionDecl *Function,
2692 DeclAccessPair FoundDecl,
2693 ArrayRef<Expr *> Args,
2694 OverloadCandidateSet &CandidateSet,
2695 bool SuppressUserConversions = false,
2696 bool PartialOverloading = false,
2697 bool AllowExplicit = false,
2698 ConversionSequenceList EarlyConversions = None);
2699 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2700 ArrayRef<Expr *> Args,
2701 OverloadCandidateSet &CandidateSet,
2702 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2703 bool SuppressUserConversions = false,
2704 bool PartialOverloading = false,
2705 bool FirstArgumentIsBase = false);
2706 void AddMethodCandidate(DeclAccessPair FoundDecl,
2707 QualType ObjectType,
2708 Expr::Classification ObjectClassification,
2709 ArrayRef<Expr *> Args,
2710 OverloadCandidateSet& CandidateSet,
2711 bool SuppressUserConversion = false);
2712 void AddMethodCandidate(CXXMethodDecl *Method,
2713 DeclAccessPair FoundDecl,
2714 CXXRecordDecl *ActingContext, QualType ObjectType,
2715 Expr::Classification ObjectClassification,
2716 ArrayRef<Expr *> Args,
2717 OverloadCandidateSet& CandidateSet,
2718 bool SuppressUserConversions = false,
2719 bool PartialOverloading = false,
2720 ConversionSequenceList EarlyConversions = None);
2721 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2722 DeclAccessPair FoundDecl,
2723 CXXRecordDecl *ActingContext,
2724 TemplateArgumentListInfo *ExplicitTemplateArgs,
2725 QualType ObjectType,
2726 Expr::Classification ObjectClassification,
2727 ArrayRef<Expr *> Args,
2728 OverloadCandidateSet& CandidateSet,
2729 bool SuppressUserConversions = false,
2730 bool PartialOverloading = false);
2731 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2732 DeclAccessPair FoundDecl,
2733 TemplateArgumentListInfo *ExplicitTemplateArgs,
2734 ArrayRef<Expr *> Args,
2735 OverloadCandidateSet& CandidateSet,
2736 bool SuppressUserConversions = false,
2737 bool PartialOverloading = false);
2738 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2739 ArrayRef<QualType> ParamTypes,
2740 ArrayRef<Expr *> Args,
2741 OverloadCandidateSet &CandidateSet,
2742 ConversionSequenceList &Conversions,
2743 bool SuppressUserConversions,
2744 CXXRecordDecl *ActingContext = nullptr,
2745 QualType ObjectType = QualType(),
2746 Expr::Classification
2747 ObjectClassification = {});
2748 void AddConversionCandidate(CXXConversionDecl *Conversion,
2749 DeclAccessPair FoundDecl,
2750 CXXRecordDecl *ActingContext,
2751 Expr *From, QualType ToType,
2752 OverloadCandidateSet& CandidateSet,
2753 bool AllowObjCConversionOnExplicit,
2754 bool AllowResultConversion = true);
2755 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2756 DeclAccessPair FoundDecl,
2757 CXXRecordDecl *ActingContext,
2758 Expr *From, QualType ToType,
2759 OverloadCandidateSet &CandidateSet,
2760 bool AllowObjCConversionOnExplicit,
2761 bool AllowResultConversion = true);
2762 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2763 DeclAccessPair FoundDecl,
2764 CXXRecordDecl *ActingContext,
2765 const FunctionProtoType *Proto,
2766 Expr *Object, ArrayRef<Expr *> Args,
2767 OverloadCandidateSet& CandidateSet);
2768 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2769 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2770 OverloadCandidateSet& CandidateSet,
2771 SourceRange OpRange = SourceRange());
2772 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
2773 OverloadCandidateSet& CandidateSet,
2774 bool IsAssignmentOperator = false,
2775 unsigned NumContextualBoolArguments = 0);
2776 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2777 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2778 OverloadCandidateSet& CandidateSet);
2779 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2780 SourceLocation Loc,
2781 ArrayRef<Expr *> Args,
2782 TemplateArgumentListInfo *ExplicitTemplateArgs,
2783 OverloadCandidateSet& CandidateSet,
2784 bool PartialOverloading = false);
2785
2786 // Emit as a 'note' the specific overload candidate
2787 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2788 QualType DestType = QualType(),
2789 bool TakingAddress = false);
2790
2791 // Emit as a series of 'note's all template and non-templates identified by
2792 // the expression Expr
2793 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2794 bool TakingAddress = false);
2795
2796 /// Check the enable_if expressions on the given function. Returns the first
2797 /// failing attribute, or NULL if they were all successful.
2798 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2799 bool MissingImplicitThis = false);
2800
2801 /// Find the failed Boolean condition within a given Boolean
2802 /// constant expression, and describe it with a string.
2803 ///
2804 /// \param AllowTopLevelCond Whether to allow the result to be the
2805 /// complete top-level condition.
2806 std::pair<Expr *, std::string>
2807 findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond);
2808
2809 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2810 /// non-ArgDependent DiagnoseIfAttrs.
2811 ///
2812 /// Argument-dependent diagnose_if attributes should be checked each time a
2813 /// function is used as a direct callee of a function call.
2814 ///
2815 /// Returns true if any errors were emitted.
2816 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2817 const Expr *ThisArg,
2818 ArrayRef<const Expr *> Args,
2819 SourceLocation Loc);
2820
2821 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2822 /// ArgDependent DiagnoseIfAttrs.
2823 ///
2824 /// Argument-independent diagnose_if attributes should be checked on every use
2825 /// of a function.
2826 ///
2827 /// Returns true if any errors were emitted.
2828 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
2829 SourceLocation Loc);
2830
2831 /// Returns whether the given function's address can be taken or not,
2832 /// optionally emitting a diagnostic if the address can't be taken.
2833 ///
2834 /// Returns false if taking the address of the function is illegal.
2835 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2836 bool Complain = false,
2837 SourceLocation Loc = SourceLocation());
2838
2839 // [PossiblyAFunctionType] --> [Return]
2840 // NonFunctionType --> NonFunctionType
2841 // R (A) --> R(A)
2842 // R (*)(A) --> R (A)
2843 // R (&)(A) --> R (A)
2844 // R (S::*)(A) --> R (A)
2845 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2846
2847 FunctionDecl *
2848 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2849 QualType TargetType,
2850 bool Complain,
2851 DeclAccessPair &Found,
2852 bool *pHadMultipleCandidates = nullptr);
2853
2854 FunctionDecl *
2855 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2856 DeclAccessPair &FoundResult);
2857
2858 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
2859 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
2860
2861 FunctionDecl *
2862 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2863 bool Complain = false,
2864 DeclAccessPair *Found = nullptr);
2865
2866 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2867 ExprResult &SrcExpr,
2868 bool DoFunctionPointerConverion = false,
2869 bool Complain = false,
2870 SourceRange OpRangeForComplaining = SourceRange(),
2871 QualType DestTypeForComplaining = QualType(),
2872 unsigned DiagIDForComplaining = 0);
2873
2874
2875 Expr *FixOverloadedFunctionReference(Expr *E,
2876 DeclAccessPair FoundDecl,
2877 FunctionDecl *Fn);
2878 ExprResult FixOverloadedFunctionReference(ExprResult,
2879 DeclAccessPair FoundDecl,
2880 FunctionDecl *Fn);
2881
2882 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2883 ArrayRef<Expr *> Args,
2884 OverloadCandidateSet &CandidateSet,
2885 bool PartialOverloading = false);
2886
2887 // An enum used to represent the different possible results of building a
2888 // range-based for loop.
2889 enum ForRangeStatus {
2890 FRS_Success,
2891 FRS_NoViableFunction,
2892 FRS_DiagnosticIssued
2893 };
2894
2895 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2896 SourceLocation RangeLoc,
2897 const DeclarationNameInfo &NameInfo,
2898 LookupResult &MemberLookup,
2899 OverloadCandidateSet *CandidateSet,
2900 Expr *Range, ExprResult *CallExpr);
2901
2902 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2903 UnresolvedLookupExpr *ULE,
2904 SourceLocation LParenLoc,
2905 MultiExprArg Args,
2906 SourceLocation RParenLoc,
2907 Expr *ExecConfig,
2908 bool AllowTypoCorrection=true,
2909 bool CalleesAddressIsTaken=false);
2910
2911 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2912 MultiExprArg Args, SourceLocation RParenLoc,
2913 OverloadCandidateSet *CandidateSet,
2914 ExprResult *Result);
2915
2916 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2917 UnaryOperatorKind Opc,
2918 const UnresolvedSetImpl &Fns,
2919 Expr *input, bool RequiresADL = true);
2920
2921 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2922 BinaryOperatorKind Opc,
2923 const UnresolvedSetImpl &Fns,
2924 Expr *LHS, Expr *RHS,
2925 bool RequiresADL = true);
2926
2927 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2928 SourceLocation RLoc,
2929 Expr *Base,Expr *Idx);
2930
2931 ExprResult
2932 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2933 SourceLocation LParenLoc,
2934 MultiExprArg Args,
2935 SourceLocation RParenLoc);
2936 ExprResult
2937 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2938 MultiExprArg Args,
2939 SourceLocation RParenLoc);
2940
2941 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2942 SourceLocation OpLoc,
2943 bool *NoArrowOperatorFound = nullptr);
2944
2945 /// CheckCallReturnType - Checks that a call expression's return type is
2946 /// complete. Returns true on failure. The location passed in is the location
2947 /// that best represents the call.
2948 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2949 CallExpr *CE, FunctionDecl *FD);
2950
2951 /// Helpers for dealing with blocks and functions.
2952 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2953 bool CheckParameterNames);
2954 void CheckCXXDefaultArguments(FunctionDecl *FD);
2955 void CheckExtraCXXDefaultArguments(Declarator &D);
2956 Scope *getNonFieldDeclScope(Scope *S);
2957
2958 /// \name Name lookup
2959 ///
2960 /// These routines provide name lookup that is used during semantic
2961 /// analysis to resolve the various kinds of names (identifiers,
2962 /// overloaded operator names, constructor names, etc.) into zero or
2963 /// more declarations within a particular scope. The major entry
2964 /// points are LookupName, which performs unqualified name lookup,
2965 /// and LookupQualifiedName, which performs qualified name lookup.
2966 ///
2967 /// All name lookup is performed based on some specific criteria,
2968 /// which specify what names will be visible to name lookup and how
2969 /// far name lookup should work. These criteria are important both
2970 /// for capturing language semantics (certain lookups will ignore
2971 /// certain names, for example) and for performance, since name
2972 /// lookup is often a bottleneck in the compilation of C++. Name
2973 /// lookup criteria is specified via the LookupCriteria enumeration.
2974 ///
2975 /// The results of name lookup can vary based on the kind of name
2976 /// lookup performed, the current language, and the translation
2977 /// unit. In C, for example, name lookup will either return nothing
2978 /// (no entity found) or a single declaration. In C++, name lookup
2979 /// can additionally refer to a set of overloaded functions or
2980 /// result in an ambiguity. All of the possible results of name
2981 /// lookup are captured by the LookupResult class, which provides
2982 /// the ability to distinguish among them.
2983 //@{
2984
2985 /// @brief Describes the kind of name lookup to perform.
2986 enum LookupNameKind {
2987 /// Ordinary name lookup, which finds ordinary names (functions,
2988 /// variables, typedefs, etc.) in C and most kinds of names
2989 /// (functions, variables, members, types, etc.) in C++.
2990 LookupOrdinaryName = 0,
2991 /// Tag name lookup, which finds the names of enums, classes,
2992 /// structs, and unions.
2993 LookupTagName,
2994 /// Label name lookup.
2995 LookupLabel,
2996 /// Member name lookup, which finds the names of
2997 /// class/struct/union members.
2998 LookupMemberName,
2999 /// Look up of an operator name (e.g., operator+) for use with
3000 /// operator overloading. This lookup is similar to ordinary name
3001 /// lookup, but will ignore any declarations that are class members.
3002 LookupOperatorName,
3003 /// Look up of a name that precedes the '::' scope resolution
3004 /// operator in C++. This lookup completely ignores operator, object,
3005 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3006 LookupNestedNameSpecifierName,
3007 /// Look up a namespace name within a C++ using directive or
3008 /// namespace alias definition, ignoring non-namespace names (C++
3009 /// [basic.lookup.udir]p1).
3010 LookupNamespaceName,
3011 /// Look up all declarations in a scope with the given name,
3012 /// including resolved using declarations. This is appropriate
3013 /// for checking redeclarations for a using declaration.
3014 LookupUsingDeclName,
3015 /// Look up an ordinary name that is going to be redeclared as a
3016 /// name with linkage. This lookup ignores any declarations that
3017 /// are outside of the current scope unless they have linkage. See
3018 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3019 LookupRedeclarationWithLinkage,
3020 /// Look up a friend of a local class. This lookup does not look
3021 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3022 LookupLocalFriendName,
3023 /// Look up the name of an Objective-C protocol.
3024 LookupObjCProtocolName,
3025 /// Look up implicit 'self' parameter of an objective-c method.
3026 LookupObjCImplicitSelfParam,
3027 /// \brief Look up the name of an OpenMP user-defined reduction operation.
3028 LookupOMPReductionName,
3029 /// \brief Look up any declaration with any name.
3030 LookupAnyName
3031 };
3032
3033 /// \brief Specifies whether (or how) name lookup is being performed for a
3034 /// redeclaration (vs. a reference).
3035 enum RedeclarationKind {
3036 /// \brief The lookup is a reference to this name that is not for the
3037 /// purpose of redeclaring the name.
3038 NotForRedeclaration = 0,
3039 /// \brief The lookup results will be used for redeclaration of a name,
3040 /// if an entity by that name already exists and is visible.
3041 ForVisibleRedeclaration,
3042 /// \brief The lookup results will be used for redeclaration of a name
3043 /// with external linkage; non-visible lookup results with external linkage
3044 /// may also be found.
3045 ForExternalRedeclaration
3046 };
3047
3048 RedeclarationKind forRedeclarationInCurContext() {
3049 // A declaration with an owning module for linkage can never link against
3050 // anything that is not visible. We don't need to check linkage here; if
3051 // the context has internal linkage, redeclaration lookup won't find things
3052 // from other TUs, and we can't safely compute linkage yet in general.
3053 if (cast<Decl>(CurContext)
3054 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3055 return ForVisibleRedeclaration;
3056 return ForExternalRedeclaration;
3057 }
3058
3059 /// \brief The possible outcomes of name lookup for a literal operator.
3060 enum LiteralOperatorLookupResult {
3061 /// \brief The lookup resulted in an error.
3062 LOLR_Error,
3063 /// \brief The lookup found no match but no diagnostic was issued.
3064 LOLR_ErrorNoDiagnostic,
3065 /// \brief The lookup found a single 'cooked' literal operator, which
3066 /// expects a normal literal to be built and passed to it.
3067 LOLR_Cooked,
3068 /// \brief The lookup found a single 'raw' literal operator, which expects
3069 /// a string literal containing the spelling of the literal token.
3070 LOLR_Raw,
3071 /// \brief The lookup found an overload set of literal operator templates,
3072 /// which expect the characters of the spelling of the literal token to be
3073 /// passed as a non-type template argument pack.
3074 LOLR_Template,
3075 /// \brief The lookup found an overload set of literal operator templates,
3076 /// which expect the character type and characters of the spelling of the
3077 /// string literal token to be passed as template arguments.
3078 LOLR_StringTemplate
3079 };
3080
3081 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3082 CXXSpecialMember SM,
3083 bool ConstArg,
3084 bool VolatileArg,
3085 bool RValueThis,
3086 bool ConstThis,
3087 bool VolatileThis);
3088
3089 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3090 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3091 TypoRecoveryCallback;
3092
3093private:
3094 bool CppLookupName(LookupResult &R, Scope *S);
3095
3096 struct TypoExprState {
3097 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3098 TypoDiagnosticGenerator DiagHandler;
3099 TypoRecoveryCallback RecoveryHandler;
3100 TypoExprState();
3101 TypoExprState(TypoExprState &&other) noexcept;
3102 TypoExprState &operator=(TypoExprState &&other) noexcept;
3103 };
3104
3105 /// \brief The set of unhandled TypoExprs and their associated state.
3106 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3107
3108 /// \brief Creates a new TypoExpr AST node.
3109 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3110 TypoDiagnosticGenerator TDG,
3111 TypoRecoveryCallback TRC);
3112
3113 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
3114 //
3115 // The boolean value will be true to indicate that the namespace was loaded
3116 // from an AST/PCH file, or false otherwise.
3117 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3118
3119 /// \brief Whether we have already loaded known namespaces from an extenal
3120 /// source.
3121 bool LoadedExternalKnownNamespaces;
3122
3123 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
3124 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3125 /// should be skipped entirely.
3126 std::unique_ptr<TypoCorrectionConsumer>
3127 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3128 Sema::LookupNameKind LookupKind, Scope *S,
3129 CXXScopeSpec *SS,
3130 std::unique_ptr<CorrectionCandidateCallback> CCC,
3131 DeclContext *MemberContext, bool EnteringContext,
3132 const ObjCObjectPointerType *OPT,
3133 bool ErrorRecovery);
3134
3135public:
3136 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3137
3138 /// \brief Clears the state of the given TypoExpr.
3139 void clearDelayedTypo(TypoExpr *TE);
3140
3141 /// \brief Look up a name, looking for a single declaration. Return
3142 /// null if the results were absent, ambiguous, or overloaded.
3143 ///
3144 /// It is preferable to use the elaborated form and explicitly handle
3145 /// ambiguity and overloaded.
3146 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3147 SourceLocation Loc,
3148 LookupNameKind NameKind,
3149 RedeclarationKind Redecl
3150 = NotForRedeclaration);
3151 bool LookupName(LookupResult &R, Scope *S,
3152 bool AllowBuiltinCreation = false);
3153 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3154 bool InUnqualifiedLookup = false);
3155 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3156 CXXScopeSpec &SS);
3157 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3158 bool AllowBuiltinCreation = false,
3159 bool EnteringContext = false);
3160 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3161 RedeclarationKind Redecl
3162 = NotForRedeclaration);
3163 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3164
3165 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3166 QualType T1, QualType T2,
3167 UnresolvedSetImpl &Functions);
3168
3169 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3170 SourceLocation GnuLabelLoc = SourceLocation());
3171
3172 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3173 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3174 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3175 unsigned Quals);
3176 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3177 bool RValueThis, unsigned ThisQuals);
3178 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3179 unsigned Quals);
3180 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3181 bool RValueThis, unsigned ThisQuals);
3182 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3183
3184 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3185 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3186 ArrayRef<QualType> ArgTys,
3187 bool AllowRaw,
3188 bool AllowTemplate,
3189 bool AllowStringTemplate,
3190 bool DiagnoseMissing);
3191 bool isKnownName(StringRef name);
3192
3193 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3194 ArrayRef<Expr *> Args, ADLResult &Functions);
3195
3196 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3197 VisibleDeclConsumer &Consumer,
3198 bool IncludeGlobalScope = true,
3199 bool LoadExternal = true);
3200 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3201 VisibleDeclConsumer &Consumer,
3202 bool IncludeGlobalScope = true,
3203 bool IncludeDependentBases = false,
3204 bool LoadExternal = true);
3205
3206 enum CorrectTypoKind {
3207 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3208 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3209 };
3210
3211 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3212 Sema::LookupNameKind LookupKind,
3213 Scope *S, CXXScopeSpec *SS,
3214 std::unique_ptr<CorrectionCandidateCallback> CCC,
3215 CorrectTypoKind Mode,
3216 DeclContext *MemberContext = nullptr,
3217 bool EnteringContext = false,
3218 const ObjCObjectPointerType *OPT = nullptr,
3219 bool RecordFailure = true);
3220
3221 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3222 Sema::LookupNameKind LookupKind, Scope *S,
3223 CXXScopeSpec *SS,
3224 std::unique_ptr<CorrectionCandidateCallback> CCC,
3225 TypoDiagnosticGenerator TDG,
3226 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3227 DeclContext *MemberContext = nullptr,
3228 bool EnteringContext = false,
3229 const ObjCObjectPointerType *OPT = nullptr);
3230
3231 /// \brief Process any TypoExprs in the given Expr and its children,
3232 /// generating diagnostics as appropriate and returning a new Expr if there
3233 /// were typos that were all successfully corrected and ExprError if one or
3234 /// more typos could not be corrected.
3235 ///
3236 /// \param E The Expr to check for TypoExprs.
3237 ///
3238 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3239 /// initializer.
3240 ///
3241 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3242 /// it is an acceptable/usable result from a single combination of typo
3243 /// corrections. As long as the filter returns ExprError, different
3244 /// combinations of corrections will be tried until all are exhausted.
3245 ExprResult
3246 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3247 llvm::function_ref<ExprResult(Expr *)> Filter =
3248 [](Expr *E) -> ExprResult { return E; });
3249
3250 ExprResult
3251 CorrectDelayedTyposInExpr(Expr *E,
3252 llvm::function_ref<ExprResult(Expr *)> Filter) {
3253 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3254 }
3255
3256 ExprResult
3257 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3258 llvm::function_ref<ExprResult(Expr *)> Filter =
3259 [](Expr *E) -> ExprResult { return E; }) {
3260 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3261 }
3262
3263 ExprResult
3264 CorrectDelayedTyposInExpr(ExprResult ER,
3265 llvm::function_ref<ExprResult(Expr *)> Filter) {
3266 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3267 }
3268
3269 void diagnoseTypo(const TypoCorrection &Correction,
3270 const PartialDiagnostic &TypoDiag,
3271 bool ErrorRecovery = true);
3272
3273 void diagnoseTypo(const TypoCorrection &Correction,
3274 const PartialDiagnostic &TypoDiag,
3275 const PartialDiagnostic &PrevNote,
3276 bool ErrorRecovery = true);
3277
3278 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3279
3280 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3281 ArrayRef<Expr *> Args,
3282 AssociatedNamespaceSet &AssociatedNamespaces,
3283 AssociatedClassSet &AssociatedClasses);
3284
3285 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3286 bool ConsiderLinkage, bool AllowInlineNamespace);
3287
3288 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3289
3290 void DiagnoseAmbiguousLookup(LookupResult &Result);
3291 //@}
3292
3293 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3294 SourceLocation IdLoc,
3295 bool TypoCorrection = false);
3296 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3297 Scope *S, bool ForRedeclaration,
3298 SourceLocation Loc);
3299 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3300 Scope *S);
3301 void AddKnownFunctionAttributes(FunctionDecl *FD);
3302
3303 // More parsing and symbol table subroutines.
3304
3305 void ProcessPragmaWeak(Scope *S, Decl *D);
3306 // Decl attributes - this routine is the top level dispatcher.
3307 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3308 // Helper for delayed processing of attributes.
3309 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3310 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3311 bool IncludeCXX11Attributes = true);
3312 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3313 const AttributeList *AttrList);
3314
3315 void checkUnusedDeclAttributes(Declarator &D);
3316
3317 /// Determine if type T is a valid subject for a nonnull and similar
3318 /// attributes. By default, we look through references (the behavior used by
3319 /// nonnull), but if the second parameter is true, then we treat a reference
3320 /// type as valid.
3321 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3322
3323 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3324 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3325 const FunctionDecl *FD = nullptr);
3326 bool CheckAttrTarget(const AttributeList &CurrAttr);
3327 bool CheckAttrNoArgs(const AttributeList &CurrAttr);
3328 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3329 unsigned ArgNum, StringRef &Str,
3330 SourceLocation *ArgLocation = nullptr);
3331 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3332 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3333 bool checkMSInheritanceAttrOnDefinition(
3334 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3335 MSInheritanceAttr::Spelling SemanticSpelling);
3336
3337 void CheckAlignasUnderalignment(Decl *D);
3338
3339 /// Adjust the calling convention of a method to be the ABI default if it
3340 /// wasn't specified explicitly. This handles method types formed from
3341 /// function type typedefs and typename template arguments.
3342 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3343 SourceLocation Loc);
3344
3345 // Check if there is an explicit attribute, but only look through parens.
3346 // The intent is to look for an attribute on the current declarator, but not
3347 // one that came from a typedef.
3348 bool hasExplicitCallingConv(QualType &T);
3349
3350 /// Get the outermost AttributedType node that sets a calling convention.
3351 /// Valid types should not have multiple attributes with different CCs.
3352 const AttributedType *getCallingConvAttributedType(QualType T) const;
3353
3354 /// Check whether a nullability type specifier can be added to the given
3355 /// type.
3356 ///
3357 /// \param type The type to which the nullability specifier will be
3358 /// added. On success, this type will be updated appropriately.
3359 ///
3360 /// \param nullability The nullability specifier to add.
3361 ///
3362 /// \param nullabilityLoc The location of the nullability specifier.
3363 ///
3364 /// \param isContextSensitive Whether this nullability specifier was
3365 /// written as a context-sensitive keyword (in an Objective-C
3366 /// method) or an Objective-C property attribute, rather than as an
3367 /// underscored type specifier.
3368 ///
3369 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3370 /// array type (e.g., because it will decay to a pointer).
3371 ///
3372 /// \returns true if nullability cannot be applied, false otherwise.
3373 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3374 SourceLocation nullabilityLoc,
3375 bool isContextSensitive,
3376 bool allowArrayTypes);
3377
3378 /// \brief Stmt attributes - this routine is the top level dispatcher.
3379 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3380 SourceRange Range);
3381
3382 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3383 ObjCMethodDecl *MethodDecl,
3384 bool IsProtocolMethodDecl);
3385
3386 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3387 ObjCMethodDecl *Overridden,
3388 bool IsProtocolMethodDecl);
3389
3390 /// WarnExactTypedMethods - This routine issues a warning if method
3391 /// implementation declaration matches exactly that of its declaration.
3392 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3393 ObjCMethodDecl *MethodDecl,
3394 bool IsProtocolMethodDecl);
3395
3396 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3397
3398 /// CheckImplementationIvars - This routine checks if the instance variables
3399 /// listed in the implelementation match those listed in the interface.
3400 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3401 ObjCIvarDecl **Fields, unsigned nIvars,
3402 SourceLocation Loc);
3403
3404 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3405 /// remains unimplemented in the class or category \@implementation.
3406 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3407 ObjCContainerDecl* IDecl,
3408 bool IncompleteImpl = false);
3409
3410 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3411 /// which must be implemented by this implementation.
3412 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3413 ObjCContainerDecl *CDecl,
3414 bool SynthesizeProperties);
3415
3416 /// Diagnose any null-resettable synthesized setters.
3417 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3418
3419 /// DefaultSynthesizeProperties - This routine default synthesizes all
3420 /// properties which must be synthesized in the class's \@implementation.
3421 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3422 ObjCInterfaceDecl *IDecl,
3423 SourceLocation AtEnd);
3424 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3425
3426 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3427 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3428 /// declared in class 'IFace'.
3429 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3430 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3431
3432 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3433 /// backs the property is not used in the property's accessor.
3434 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3435 const ObjCImplementationDecl *ImplD);
3436
3437 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3438 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3439 /// It also returns ivar's property on success.
3440 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3441 const ObjCPropertyDecl *&PDecl) const;
3442
3443 /// Called by ActOnProperty to handle \@property declarations in
3444 /// class extensions.
3445 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3446 SourceLocation AtLoc,
3447 SourceLocation LParenLoc,
3448 FieldDeclarator &FD,
3449 Selector GetterSel,
3450 SourceLocation GetterNameLoc,
3451 Selector SetterSel,
3452 SourceLocation SetterNameLoc,
3453 const bool isReadWrite,
3454 unsigned &Attributes,
3455 const unsigned AttributesAsWritten,
3456 QualType T,
3457 TypeSourceInfo *TSI,
3458 tok::ObjCKeywordKind MethodImplKind);
3459
3460 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3461 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3462 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3463 ObjCContainerDecl *CDecl,
3464 SourceLocation AtLoc,
3465 SourceLocation LParenLoc,
3466 FieldDeclarator &FD,
3467 Selector GetterSel,
3468 SourceLocation GetterNameLoc,
3469 Selector SetterSel,
3470 SourceLocation SetterNameLoc,
3471 const bool isReadWrite,
3472 const unsigned Attributes,
3473 const unsigned AttributesAsWritten,
3474 QualType T,
3475 TypeSourceInfo *TSI,
3476 tok::ObjCKeywordKind MethodImplKind,
3477 DeclContext *lexicalDC = nullptr);
3478
3479 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3480 /// warning) when atomic property has one but not the other user-declared
3481 /// setter or getter.
3482 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3483 ObjCInterfaceDecl* IDecl);
3484
3485 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3486
3487 void DiagnoseMissingDesignatedInitOverrides(
3488 const ObjCImplementationDecl *ImplD,
3489 const ObjCInterfaceDecl *IFD);
3490
3491 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3492
3493 enum MethodMatchStrategy {
3494 MMS_loose,
3495 MMS_strict
3496 };
3497
3498 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3499 /// true, or false, accordingly.
3500 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3501 const ObjCMethodDecl *PrevMethod,
3502 MethodMatchStrategy strategy = MMS_strict);
3503
3504 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3505 /// or protocol against those declared in their implementations.
3506 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3507 const SelectorSet &ClsMap,
3508 SelectorSet &InsMapSeen,
3509 SelectorSet &ClsMapSeen,
3510 ObjCImplDecl* IMPDecl,
3511 ObjCContainerDecl* IDecl,
3512 bool &IncompleteImpl,
3513 bool ImmediateClass,
3514 bool WarnCategoryMethodImpl=false);
3515
3516 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3517 /// category matches with those implemented in its primary class and
3518 /// warns each time an exact match is found.
3519 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3520
3521 /// \brief Add the given method to the list of globally-known methods.
3522 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3523
3524private:
3525 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3526 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3527 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3528
3529 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3530 /// optionally warns if there are multiple signatures.
3531 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3532 bool receiverIdOrClass,
3533 bool instance);
3534
3535public:
3536 /// \brief - Returns instance or factory methods in global method pool for
3537 /// given selector. It checks the desired kind first, if none is found, and
3538 /// parameter checkTheOther is set, it then checks the other kind. If no such
3539 /// method or only one method is found, function returns false; otherwise, it
3540 /// returns true.
3541 bool
3542 CollectMultipleMethodsInGlobalPool(Selector Sel,
3543 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3544 bool InstanceFirst, bool CheckTheOther,
3545 const ObjCObjectType *TypeBound = nullptr);
3546
3547 bool
3548 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3549 SourceRange R, bool receiverIdOrClass,
3550 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3551
3552 void
3553 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3554 Selector Sel, SourceRange R,
3555 bool receiverIdOrClass);
3556
3557private:
3558 /// \brief - Returns a selector which best matches given argument list or
3559 /// nullptr if none could be found
3560 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3561 bool IsInstance,
3562 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3563
3564
3565 /// \brief Record the typo correction failure and return an empty correction.
3566 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3567 bool RecordFailure = true) {
3568 if (RecordFailure)
3569 TypoCorrectionFailures[Typo].insert(TypoLoc);
3570 return TypoCorrection();
3571 }
3572
3573public:
3574 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3575 /// unit are added to a global pool. This allows us to efficiently associate
3576 /// a selector with a method declaraation for purposes of typechecking
3577 /// messages sent to "id" (where the class of the object is unknown).
3578 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3579 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3580 }
3581
3582 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3583 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3584 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3585 }
3586
3587 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3588 /// pool.
3589 void AddAnyMethodToGlobalPool(Decl *D);
3590
3591 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3592 /// there are multiple signatures.
3593 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3594 bool receiverIdOrClass=false) {
3595 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3596 /*instance*/true);
3597 }
3598
3599 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3600 /// there are multiple signatures.
3601 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3602 bool receiverIdOrClass=false) {
3603 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3604 /*instance*/false);
3605 }
3606
3607 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3608 QualType ObjectType=QualType());
3609 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3610 /// implementation.
3611 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3612
3613 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3614 /// initialization.
3615 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3616 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3617
3618 //===--------------------------------------------------------------------===//
3619 // Statement Parsing Callbacks: SemaStmt.cpp.
3620public:
3621 class FullExprArg {
3622 public:
3623 FullExprArg() : E(nullptr) { }
3624 FullExprArg(Sema &actions) : E(nullptr) { }
3625
3626 ExprResult release() {
3627 return E;
3628 }
3629
3630 Expr *get() const { return E; }
3631
3632 Expr *operator->() {
3633 return E;
3634 }
3635
3636 private:
3637 // FIXME: No need to make the entire Sema class a friend when it's just
3638 // Sema::MakeFullExpr that needs access to the constructor below.
3639 friend class Sema;
3640
3641 explicit FullExprArg(Expr *expr) : E(expr) {}
3642
3643 Expr *E;
3644 };
3645
3646 FullExprArg MakeFullExpr(Expr *Arg) {
3647 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3648 }
3649 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3650 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3651 }
3652 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3653 ExprResult FE =
3654 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3655 /*DiscardedValue*/ true);
3656 return FullExprArg(FE.get());
3657 }
3658
3659 StmtResult ActOnExprStmt(ExprResult Arg);
3660 StmtResult ActOnExprStmtError();
3661
3662 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3663 bool HasLeadingEmptyMacro = false);
3664
3665 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
3666 void ActOnFinishOfCompoundStmt();
3667 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3668 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3669
3670 /// \brief A RAII object to enter scope of a compound statement.
3671 class CompoundScopeRAII {
3672 public:
3673 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
3674 S.ActOnStartOfCompoundStmt(IsStmtExpr);
3675 }
3676
3677 ~CompoundScopeRAII() {
3678 S.ActOnFinishOfCompoundStmt();
3679 }
3680
3681 private:
3682 Sema &S;
3683 };
3684
3685 /// An RAII helper that pops function a function scope on exit.
3686 struct FunctionScopeRAII {
3687 Sema &S;
3688 bool Active;
3689 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3690 ~FunctionScopeRAII() {
3691 if (Active)
3692 S.PopFunctionScopeInfo();
3693 }
3694 void disable() { Active = false; }
3695 };
3696
3697 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3698 SourceLocation StartLoc,
3699 SourceLocation EndLoc);
3700 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3701 StmtResult ActOnForEachLValueExpr(Expr *E);
3702 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3703 SourceLocation DotDotDotLoc, Expr *RHSVal,
3704 SourceLocation ColonLoc);
3705 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3706
3707 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3708 SourceLocation ColonLoc,
3709 Stmt *SubStmt, Scope *CurScope);
3710 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3711 SourceLocation ColonLoc, Stmt *SubStmt);
3712
3713 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3714 ArrayRef<const Attr*> Attrs,
3715 Stmt *SubStmt);
3716
3717 class ConditionResult;
3718 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3719 Stmt *InitStmt,
3720 ConditionResult Cond, Stmt *ThenVal,
3721 SourceLocation ElseLoc, Stmt *ElseVal);
3722 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3723 Stmt *InitStmt,
3724 ConditionResult Cond, Stmt *ThenVal,
3725 SourceLocation ElseLoc, Stmt *ElseVal);
3726 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3727 Stmt *InitStmt,
3728 ConditionResult Cond);
3729 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3730 Stmt *Switch, Stmt *Body);
3731 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3732 Stmt *Body);
3733 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3734 SourceLocation WhileLoc, SourceLocation CondLParen,
3735 Expr *Cond, SourceLocation CondRParen);
3736
3737 StmtResult ActOnForStmt(SourceLocation ForLoc,
3738 SourceLocation LParenLoc,
3739 Stmt *First,
3740 ConditionResult Second,
3741 FullExprArg Third,
3742 SourceLocation RParenLoc,
3743 Stmt *Body);
3744 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3745 Expr *collection);
3746 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3747 Stmt *First, Expr *collection,
3748 SourceLocation RParenLoc);
3749 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3750
3751 enum BuildForRangeKind {
3752 /// Initial building of a for-range statement.
3753 BFRK_Build,
3754 /// Instantiation or recovery rebuild of a for-range statement. Don't
3755 /// attempt any typo-correction.
3756 BFRK_Rebuild,
3757 /// Determining whether a for-range statement could be built. Avoid any
3758 /// unnecessary or irreversible actions.
3759 BFRK_Check
3760 };
3761
3762 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3763 SourceLocation CoawaitLoc,
3764 Stmt *LoopVar,
3765 SourceLocation ColonLoc, Expr *Collection,
3766 SourceLocation RParenLoc,
3767 BuildForRangeKind Kind);
3768 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3769 SourceLocation CoawaitLoc,
3770 SourceLocation ColonLoc,
3771 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3772 Expr *Cond, Expr *Inc,
3773 Stmt *LoopVarDecl,
3774 SourceLocation RParenLoc,
3775 BuildForRangeKind Kind);
3776 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3777
3778 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3779 SourceLocation LabelLoc,
3780 LabelDecl *TheDecl);
3781 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3782 SourceLocation StarLoc,
3783 Expr *DestExp);
3784 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3785 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3786
3787 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3788 CapturedRegionKind Kind, unsigned NumParams);
3789 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3790 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3791 CapturedRegionKind Kind,
3792 ArrayRef<CapturedParamNameType> Params);
3793 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3794 void ActOnCapturedRegionError();
3795 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3796 SourceLocation Loc,
3797 unsigned NumParams);
3798
3799 enum CopyElisionSemanticsKind {
3800 CES_Strict = 0,
3801 CES_AllowParameters = 1,
3802 CES_AllowDifferentTypes = 2,
3803 CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
3804 };
3805
3806 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3807 CopyElisionSemanticsKind CESK);
3808 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3809 CopyElisionSemanticsKind CESK);
3810
3811 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3812 Scope *CurScope);
3813 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3814 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3815
3816 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3817 bool IsVolatile, unsigned NumOutputs,
3818 unsigned NumInputs, IdentifierInfo **Names,
3819 MultiExprArg Constraints, MultiExprArg Exprs,
3820 Expr *AsmString, MultiExprArg Clobbers,
3821 SourceLocation RParenLoc);
3822
3823 void FillInlineAsmIdentifierInfo(Expr *Res,
3824 llvm::InlineAsmIdentifierInfo &Info);
3825 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3826 SourceLocation TemplateKWLoc,
3827 UnqualifiedId &Id,
3828 bool IsUnevaluatedContext);
3829 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3830 unsigned &Offset, SourceLocation AsmLoc);
3831 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3832 SourceLocation AsmLoc);
3833 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3834 ArrayRef<Token> AsmToks,
3835 StringRef AsmString,
3836 unsigned NumOutputs, unsigned NumInputs,
3837 ArrayRef<StringRef> Constraints,
3838 ArrayRef<StringRef> Clobbers,
3839 ArrayRef<Expr*> Exprs,
3840 SourceLocation EndLoc);
3841 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3842 SourceLocation Location,
3843 bool AlwaysCreate);
3844
3845 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3846 SourceLocation StartLoc,
3847 SourceLocation IdLoc, IdentifierInfo *Id,
3848 bool Invalid = false);
3849
3850 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3851
3852 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3853 Decl *Parm, Stmt *Body);
3854
3855 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3856
3857 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3858 MultiStmtArg Catch, Stmt *Finally);
3859
3860 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3861 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3862 Scope *CurScope);
3863 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3864 Expr *operand);
3865 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3866 Expr *SynchExpr,
3867 Stmt *SynchBody);
3868
3869 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3870
3871 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3872 SourceLocation StartLoc,
3873 SourceLocation IdLoc,
3874 IdentifierInfo *Id);
3875
3876 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3877
3878 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3879 Decl *ExDecl, Stmt *HandlerBlock);
3880 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3881 ArrayRef<Stmt *> Handlers);
3882
3883 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3884 SourceLocation TryLoc, Stmt *TryBlock,
3885 Stmt *Handler);
3886 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3887 Expr *FilterExpr,
3888 Stmt *Block);
3889 void ActOnStartSEHFinallyBlock();
3890 void ActOnAbortSEHFinallyBlock();
3891 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3892 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3893
3894 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3895
3896 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3897
3898 /// \brief If it's a file scoped decl that must warn if not used, keep track
3899 /// of it.
3900 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3901
3902 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3903 /// whose result is unused, warn.
3904 void DiagnoseUnusedExprResult(const Stmt *S);
3905 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3906 void DiagnoseUnusedDecl(const NamedDecl *ND);
3907
3908 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3909 /// statement as a \p Body, and it is located on the same line.
3910 ///
3911 /// This helps prevent bugs due to typos, such as:
3912 /// if (condition);
3913 /// do_stuff();
3914 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3915 const Stmt *Body,
3916 unsigned DiagID);
3917
3918 /// Warn if a for/while loop statement \p S, which is followed by
3919 /// \p PossibleBody, has a suspicious null statement as a body.
3920 void DiagnoseEmptyLoopBody(const Stmt *S,
3921 const Stmt *PossibleBody);
3922
3923 /// Warn if a value is moved to itself.
3924 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3925 SourceLocation OpLoc);
3926
3927 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3928 /// _Nonnull one.
3929 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3930 SourceLocation Loc);
3931
3932 /// Warn when implicitly casting 0 to nullptr.
3933 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
3934
3935 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3936 return DelayedDiagnostics.push(pool);
3937 }
3938 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3939
3940 typedef ProcessingContextState ParsingClassState;
3941 ParsingClassState PushParsingClass() {
3942 return DelayedDiagnostics.pushUndelayed();
3943 }
3944 void PopParsingClass(ParsingClassState state) {
3945 DelayedDiagnostics.popUndelayed(state);
3946 }
3947
3948 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3949
3950 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
3951 const ObjCInterfaceDecl *UnknownObjCClass,
3952 bool ObjCPropertyAccess,
3953 bool AvoidPartialAvailabilityChecks = false);
3954
3955 bool makeUnavailableInSystemHeader(SourceLocation loc,
3956 UnavailableAttr::ImplicitReason reason);
3957
3958 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3959 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3960
3961 //===--------------------------------------------------------------------===//
3962 // Expression Parsing Callbacks: SemaExpr.cpp.
3963
3964 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3965 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
3966 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
3967 bool ObjCPropertyAccess = false,
3968 bool AvoidPartialAvailabilityChecks = false);
3969 void NoteDeletedFunction(FunctionDecl *FD);
3970 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3971 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3972 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3973 ObjCMethodDecl *Getter,
3974 SourceLocation Loc);
3975 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3976 ArrayRef<Expr *> Args);
3977
3978 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3979 Decl *LambdaContextDecl = nullptr,
3980 bool IsDecltype = false);
3981 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3982 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3983 ReuseLambdaContextDecl_t,
3984 bool IsDecltype = false);
3985 void PopExpressionEvaluationContext();
3986
3987 void DiscardCleanupsInEvaluationContext();
3988
3989 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3990 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3991
3992 ExprResult ActOnConstantExpression(ExprResult Res);
3993
3994 // Functions for marking a declaration referenced. These functions also
3995 // contain the relevant logic for marking if a reference to a function or
3996 // variable is an odr-use (in the C++11 sense). There are separate variants
3997 // for expressions referring to a decl; these exist because odr-use marking
3998 // needs to be delayed for some constant variables when we build one of the
3999 // named expressions.
4000 //
4001 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4002 // should usually be true. This only needs to be set to false if the lack of
4003 // odr-use cannot be determined from the current context (for instance,
4004 // because the name denotes a virtual function and was written without an
4005 // explicit nested-name-specifier).
4006 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4007 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4008 bool MightBeOdrUse = true);
4009 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4010 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4011 void MarkMemberReferenced(MemberExpr *E);
4012
4013 void UpdateMarkingForLValueToRValue(Expr *E);
4014 void CleanupVarDeclMarking();
4015
4016 enum TryCaptureKind {
4017 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4018 };
4019
4020 /// \brief Try to capture the given variable.
4021 ///
4022 /// \param Var The variable to capture.
4023 ///
4024 /// \param Loc The location at which the capture occurs.
4025 ///
4026 /// \param Kind The kind of capture, which may be implicit (for either a
4027 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4028 ///
4029 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4030 /// an explicit lambda capture.
4031 ///
4032 /// \param BuildAndDiagnose Whether we are actually supposed to add the
4033 /// captures or diagnose errors. If false, this routine merely check whether
4034 /// the capture can occur without performing the capture itself or complaining
4035 /// if the variable cannot be captured.
4036 ///
4037 /// \param CaptureType Will be set to the type of the field used to capture
4038 /// this variable in the innermost block or lambda. Only valid when the
4039 /// variable can be captured.
4040 ///
4041 /// \param DeclRefType Will be set to the type of a reference to the capture
4042 /// from within the current scope. Only valid when the variable can be
4043 /// captured.
4044 ///
4045 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4046 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4047 /// This is useful when enclosing lambdas must speculatively capture
4048 /// variables that may or may not be used in certain specializations of
4049 /// a nested generic lambda.
4050 ///
4051 /// \returns true if an error occurred (i.e., the variable cannot be
4052 /// captured) and false if the capture succeeded.
4053 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4054 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4055 QualType &CaptureType,
4056 QualType &DeclRefType,
4057 const unsigned *const FunctionScopeIndexToStopAt);
4058
4059 /// \brief Try to capture the given variable.
4060 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4061 TryCaptureKind Kind = TryCapture_Implicit,
4062 SourceLocation EllipsisLoc = SourceLocation());
4063
4064 /// \brief Checks if the variable must be captured.
4065 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4066
4067 /// \brief Given a variable, determine the type that a reference to that
4068 /// variable will have in the given scope.
4069 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4070
4071 /// Mark all of the declarations referenced within a particular AST node as
4072 /// referenced. Used when template instantiation instantiates a non-dependent
4073 /// type -- entities referenced by the type are now referenced.
4074 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4075 void MarkDeclarationsReferencedInExpr(Expr *E,
4076 bool SkipLocalVariables = false);
4077
4078 /// \brief Try to recover by turning the given expression into a
4079 /// call. Returns true if recovery was attempted or an error was
4080 /// emitted; this may also leave the ExprResult invalid.
4081 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4082 bool ForceComplain = false,
4083 bool (*IsPlausibleResult)(QualType) = nullptr);
4084
4085 /// \brief Figure out if an expression could be turned into a call.
4086 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4087 UnresolvedSetImpl &NonTemplateOverloads);
4088
4089 /// \brief Conditionally issue a diagnostic based on the current
4090 /// evaluation context.
4091 ///
4092 /// \param Statement If Statement is non-null, delay reporting the
4093 /// diagnostic until the function body is parsed, and then do a basic
4094 /// reachability analysis to determine if the statement is reachable.
4095 /// If it is unreachable, the diagnostic will not be emitted.
4096 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4097 const PartialDiagnostic &PD);
4098
4099 // Primary Expressions.
4100 SourceRange getExprRange(Expr *E) const;
4101
4102 ExprResult ActOnIdExpression(
4103 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4104 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4105 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
4106 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4107
4108 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4109 TemplateArgumentListInfo &Buffer,
4110 DeclarationNameInfo &NameInfo,
4111 const TemplateArgumentListInfo *&TemplateArgs);
4112
4113 bool
4114 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4115 std::unique_ptr<CorrectionCandidateCallback> CCC,
4116 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4117 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4118
4119 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4120 IdentifierInfo *II,
4121 bool AllowBuiltinCreation=false);
4122
4123 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4124 SourceLocation TemplateKWLoc,
4125 const DeclarationNameInfo &NameInfo,
4126 bool isAddressOfOperand,
4127 const TemplateArgumentListInfo *TemplateArgs);
4128
4129 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
4130 ExprValueKind VK,
4131 SourceLocation Loc,
4132 const CXXScopeSpec *SS = nullptr);
4133 ExprResult
4134 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4135 const DeclarationNameInfo &NameInfo,
4136 const CXXScopeSpec *SS = nullptr,
4137 NamedDecl *FoundD = nullptr,
4138 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4139 ExprResult
4140 BuildAnonymousStructUnionMemberReference(
4141 const CXXScopeSpec &SS,
4142 SourceLocation nameLoc,
4143 IndirectFieldDecl *indirectField,
4144 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4145 Expr *baseObjectExpr = nullptr,
4146 SourceLocation opLoc = SourceLocation());
4147
4148 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4149 SourceLocation TemplateKWLoc,
4150 LookupResult &R,
4151 const TemplateArgumentListInfo *TemplateArgs,
4152 const Scope *S);
4153 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4154 SourceLocation TemplateKWLoc,
4155 LookupResult &R,
4156 const TemplateArgumentListInfo *TemplateArgs,
4157 bool IsDefiniteInstance,
4158 const Scope *S);
4159 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4160 const LookupResult &R,
4161 bool HasTrailingLParen);
4162
4163 ExprResult
4164 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4165 const DeclarationNameInfo &NameInfo,
4166 bool IsAddressOfOperand, const Scope *S,
4167 TypeSourceInfo **RecoveryTSI = nullptr);
4168
4169 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4170 SourceLocation TemplateKWLoc,
4171 const DeclarationNameInfo &NameInfo,
4172 const TemplateArgumentListInfo *TemplateArgs);
4173
4174 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4175 LookupResult &R,
4176 bool NeedsADL,
4177 bool AcceptInvalidDecl = false);
4178 ExprResult BuildDeclarationNameExpr(
4179 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4180 NamedDecl *FoundD = nullptr,
4181 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4182 bool AcceptInvalidDecl = false);
4183
4184 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4185 DeclarationNameInfo &SuffixInfo,
4186 ArrayRef<Expr *> Args,
4187 SourceLocation LitEndLoc,
4188 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4189
4190 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4191 PredefinedExpr::IdentType IT);
4192 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4193 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4194
4195 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4196
4197 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4198 ExprResult ActOnCharacterConstant(const Token &Tok,
4199 Scope *UDLScope = nullptr);
4200 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4201 ExprResult ActOnParenListExpr(SourceLocation L,
4202 SourceLocation R,
4203 MultiExprArg Val);
4204
4205 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4206 /// fragments (e.g. "foo" "bar" L"baz").
4207 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4208 Scope *UDLScope = nullptr);
4209
4210 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4211 SourceLocation DefaultLoc,
4212 SourceLocation RParenLoc,
4213 Expr *ControllingExpr,
4214 ArrayRef<ParsedType> ArgTypes,
4215 ArrayRef<Expr *> ArgExprs);
4216 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4217 SourceLocation DefaultLoc,
4218 SourceLocation RParenLoc,
4219 Expr *ControllingExpr,
4220 ArrayRef<TypeSourceInfo *> Types,
4221 ArrayRef<Expr *> Exprs);
4222
4223 // Binary/Unary Operators. 'Tok' is the token for the operator.
4224 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4225 Expr *InputExpr);
4226 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4227 UnaryOperatorKind Opc, Expr *Input);
4228 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4229 tok::TokenKind Op, Expr *Input);
4230
4231 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4232
4233 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4234 SourceLocation OpLoc,
4235 UnaryExprOrTypeTrait ExprKind,
4236 SourceRange R);
4237 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4238 UnaryExprOrTypeTrait ExprKind);
4239 ExprResult
4240 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4241 UnaryExprOrTypeTrait ExprKind,
4242 bool IsType, void *TyOrEx,
4243 SourceRange ArgRange);
4244
4245 ExprResult CheckPlaceholderExpr(Expr *E);
4246 bool CheckVecStepExpr(Expr *E);
4247
4248 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4249 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4250 SourceRange ExprRange,
4251 UnaryExprOrTypeTrait ExprKind);
4252 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4253 SourceLocation OpLoc,
4254 IdentifierInfo &Name,
4255 SourceLocation NameLoc,
4256 SourceLocation RParenLoc);
4257 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4258 tok::TokenKind Kind, Expr *Input);
4259
4260 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4261 Expr *Idx, SourceLocation RLoc);
4262 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4263 Expr *Idx, SourceLocation RLoc);
4264 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4265 Expr *LowerBound, SourceLocation ColonLoc,
4266 Expr *Length, SourceLocation RBLoc);
4267
4268 // This struct is for use by ActOnMemberAccess to allow
4269 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4270 // changing the access operator from a '.' to a '->' (to see if that is the
4271 // change needed to fix an error about an unknown member, e.g. when the class
4272 // defines a custom operator->).
4273 struct ActOnMemberAccessExtraArgs {
4274 Scope *S;
4275 UnqualifiedId &Id;
4276 Decl *ObjCImpDecl;
4277 };
4278
4279 ExprResult BuildMemberReferenceExpr(
4280 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4281 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4282 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4283 const TemplateArgumentListInfo *TemplateArgs,
4284 const Scope *S,
4285 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4286
4287 ExprResult
4288 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4289 bool IsArrow, const CXXScopeSpec &SS,
4290 SourceLocation TemplateKWLoc,
4291 NamedDecl *FirstQualifierInScope, LookupResult &R,
4292 const TemplateArgumentListInfo *TemplateArgs,
4293 const Scope *S,
4294 bool SuppressQualifierCheck = false,
4295 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4296
4297 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4298 SourceLocation OpLoc,
4299 const CXXScopeSpec &SS, FieldDecl *Field,
4300 DeclAccessPair FoundDecl,
4301 const DeclarationNameInfo &MemberNameInfo);
4302
4303 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4304
4305 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4306 const CXXScopeSpec &SS,
4307 const LookupResult &R);
4308
4309 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4310 bool IsArrow, SourceLocation OpLoc,
4311 const CXXScopeSpec &SS,
4312 SourceLocation TemplateKWLoc,
4313 NamedDecl *FirstQualifierInScope,
4314 const DeclarationNameInfo &NameInfo,
4315 const TemplateArgumentListInfo *TemplateArgs);
4316
4317 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4318 SourceLocation OpLoc,
4319 tok::TokenKind OpKind,
4320 CXXScopeSpec &SS,
4321 SourceLocation TemplateKWLoc,
4322 UnqualifiedId &Member,
4323 Decl *ObjCImpDecl);
4324
4325 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4326 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4327 FunctionDecl *FDecl,
4328 const FunctionProtoType *Proto,
4329 ArrayRef<Expr *> Args,
4330 SourceLocation RParenLoc,
4331 bool ExecConfig = false);
4332 void CheckStaticArrayArgument(SourceLocation CallLoc,
4333 ParmVarDecl *Param,
4334 const Expr *ArgExpr);
4335
4336 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4337 /// This provides the location of the left/right parens and a list of comma
4338 /// locations.
4339 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4340 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4341 Expr *ExecConfig = nullptr,
4342 bool IsExecConfig = false);
4343 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4344 SourceLocation LParenLoc,
4345 ArrayRef<Expr *> Arg,
4346 SourceLocation RParenLoc,
4347 Expr *Config = nullptr,
4348 bool IsExecConfig = false);
4349
4350 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4351 MultiExprArg ExecConfig,
4352 SourceLocation GGGLoc);
4353
4354 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4355 Declarator &D, ParsedType &Ty,
4356 SourceLocation RParenLoc, Expr *CastExpr);
4357 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4358 TypeSourceInfo *Ty,
4359 SourceLocation RParenLoc,
4360 Expr *Op);
4361 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4362
4363 /// \brief Build an altivec or OpenCL literal.
4364 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4365 SourceLocation RParenLoc, Expr *E,
4366 TypeSourceInfo *TInfo);
4367
4368 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4369
4370 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4371 ParsedType Ty,
4372 SourceLocation RParenLoc,
4373 Expr *InitExpr);
4374
4375 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4376 TypeSourceInfo *TInfo,
4377 SourceLocation RParenLoc,
4378 Expr *LiteralExpr);
4379
4380 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4381 MultiExprArg InitArgList,
4382 SourceLocation RBraceLoc);
4383
4384 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4385 SourceLocation Loc,
4386 bool GNUSyntax,
4387 ExprResult Init);
4388
4389private:
4390 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4391
4392public:
4393 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4394 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4395 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4396 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4397 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4398 Expr *LHSExpr, Expr *RHSExpr);
4399
4400 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4401
4402 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4403 /// in the case of a the GNU conditional expr extension.
4404 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4405 SourceLocation ColonLoc,
4406 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4407
4408 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4409 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4410 LabelDecl *TheDecl);
4411
4412 void ActOnStartStmtExpr();
4413 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4414 SourceLocation RPLoc); // "({..})"
4415 void ActOnStmtExprError();
4416
4417 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4418 struct OffsetOfComponent {
4419 SourceLocation LocStart, LocEnd;
4420 bool isBrackets; // true if [expr], false if .ident
4421 union {
4422 IdentifierInfo *IdentInfo;
4423 Expr *E;
4424 } U;
4425 };
4426
4427 /// __builtin_offsetof(type, a.b[123][456].c)
4428 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4429 TypeSourceInfo *TInfo,
4430 ArrayRef<OffsetOfComponent> Components,
4431 SourceLocation RParenLoc);
4432 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4433 SourceLocation BuiltinLoc,
4434 SourceLocation TypeLoc,
4435 ParsedType ParsedArgTy,
4436 ArrayRef<OffsetOfComponent> Components,
4437 SourceLocation RParenLoc);
4438
4439 // __builtin_choose_expr(constExpr, expr1, expr2)
4440 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4441 Expr *CondExpr, Expr *LHSExpr,
4442 Expr *RHSExpr, SourceLocation RPLoc);
4443
4444 // __builtin_va_arg(expr, type)
4445 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4446 SourceLocation RPLoc);
4447 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4448 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4449
4450 // __null
4451 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4452
4453 bool CheckCaseExpression(Expr *E);
4454
4455 /// \brief Describes the result of an "if-exists" condition check.
4456 enum IfExistsResult {
4457 /// \brief The symbol exists.
4458 IER_Exists,
4459
4460 /// \brief The symbol does not exist.
4461 IER_DoesNotExist,
4462
4463 /// \brief The name is a dependent name, so the results will differ
4464 /// from one instantiation to the next.
4465 IER_Dependent,
4466
4467 /// \brief An error occurred.
4468 IER_Error
4469 };
4470
4471 IfExistsResult
4472 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4473 const DeclarationNameInfo &TargetNameInfo);
4474
4475 IfExistsResult
4476 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4477 bool IsIfExists, CXXScopeSpec &SS,
4478 UnqualifiedId &Name);
4479
4480 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4481 bool IsIfExists,
4482 NestedNameSpecifierLoc QualifierLoc,
4483 DeclarationNameInfo NameInfo,
4484 Stmt *Nested);
4485 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4486 bool IsIfExists,
4487 CXXScopeSpec &SS, UnqualifiedId &Name,
4488 Stmt *Nested);
4489
4490 //===------------------------- "Block" Extension ------------------------===//
4491
4492 /// ActOnBlockStart - This callback is invoked when a block literal is
4493 /// started.
4494 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4495
4496 /// ActOnBlockArguments - This callback allows processing of block arguments.
4497 /// If there are no arguments, this is still invoked.
4498 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4499 Scope *CurScope);
4500
4501 /// ActOnBlockError - If there is an error parsing a block, this callback
4502 /// is invoked to pop the information about the block from the action impl.
4503 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4504
4505 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4506 /// literal was successfully completed. ^(int x){...}
4507 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4508 Scope *CurScope);
4509
4510 //===---------------------------- Clang Extensions ----------------------===//
4511
4512 /// __builtin_convertvector(...)
4513 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4514 SourceLocation BuiltinLoc,
4515 SourceLocation RParenLoc);
4516
4517 //===---------------------------- OpenCL Features -----------------------===//
4518
4519 /// __builtin_astype(...)
4520 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4521 SourceLocation BuiltinLoc,
4522 SourceLocation RParenLoc);
4523
4524 //===---------------------------- C++ Features --------------------------===//
4525
4526 // Act on C++ namespaces
4527 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4528 SourceLocation NamespaceLoc,
4529 SourceLocation IdentLoc,
4530 IdentifierInfo *Ident,
4531 SourceLocation LBrace,
4532 AttributeList *AttrList,
4533 UsingDirectiveDecl * &UsingDecl);
4534 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4535
4536 NamespaceDecl *getStdNamespace() const;
4537 NamespaceDecl *getOrCreateStdNamespace();
4538
4539 NamespaceDecl *lookupStdExperimentalNamespace();
4540
4541 CXXRecordDecl *getStdBadAlloc() const;
4542 EnumDecl *getStdAlignValT() const;
4543
4544 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4545 /// it is and Element is not NULL, assigns the element type to Element.
4546 bool isStdInitializerList(QualType Ty, QualType *Element);
4547
4548 /// \brief Looks for the std::initializer_list template and instantiates it
4549 /// with Element, or emits an error if it's not found.
4550 ///
4551 /// \returns The instantiated template, or null on error.
4552 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4553
4554 /// \brief Determine whether Ctor is an initializer-list constructor, as
4555 /// defined in [dcl.init.list]p2.
4556 bool isInitListConstructor(const FunctionDecl *Ctor);
4557
4558 Decl *ActOnUsingDirective(Scope *CurScope,
4559 SourceLocation UsingLoc,
4560 SourceLocation NamespcLoc,
4561 CXXScopeSpec &SS,
4562 SourceLocation IdentLoc,
4563 IdentifierInfo *NamespcName,
4564 AttributeList *AttrList);
4565
4566 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4567
4568 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4569 SourceLocation NamespaceLoc,
4570 SourceLocation AliasLoc,
4571 IdentifierInfo *Alias,
4572 CXXScopeSpec &SS,
4573 SourceLocation IdentLoc,
4574 IdentifierInfo *Ident);
4575
4576 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4577 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4578 const LookupResult &PreviousDecls,
4579 UsingShadowDecl *&PrevShadow);
4580 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4581 NamedDecl *Target,
4582 UsingShadowDecl *PrevDecl);
4583
4584 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4585 bool HasTypenameKeyword,
4586 const CXXScopeSpec &SS,
4587 SourceLocation NameLoc,
4588 const LookupResult &Previous);
4589 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4590 bool HasTypename,
4591 const CXXScopeSpec &SS,
4592 const DeclarationNameInfo &NameInfo,
4593 SourceLocation NameLoc);
4594
4595 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4596 SourceLocation UsingLoc,
4597 bool HasTypenameKeyword,
4598 SourceLocation TypenameLoc,
4599 CXXScopeSpec &SS,
4600 DeclarationNameInfo NameInfo,
4601 SourceLocation EllipsisLoc,
4602 AttributeList *AttrList,
4603 bool IsInstantiation);
4604 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4605 ArrayRef<NamedDecl *> Expansions);
4606
4607 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4608
4609 /// Given a derived-class using shadow declaration for a constructor and the
4610 /// correspnding base class constructor, find or create the implicit
4611 /// synthesized derived class constructor to use for this initialization.
4612 CXXConstructorDecl *
4613 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4614 ConstructorUsingShadowDecl *DerivedShadow);
4615
4616 Decl *ActOnUsingDeclaration(Scope *CurScope,
4617 AccessSpecifier AS,
4618 SourceLocation UsingLoc,
4619 SourceLocation TypenameLoc,
4620 CXXScopeSpec &SS,
4621 UnqualifiedId &Name,
4622 SourceLocation EllipsisLoc,
4623 AttributeList *AttrList);
4624 Decl *ActOnAliasDeclaration(Scope *CurScope,
4625 AccessSpecifier AS,
4626 MultiTemplateParamsArg TemplateParams,
4627 SourceLocation UsingLoc,
4628 UnqualifiedId &Name,
4629 AttributeList *AttrList,
4630 TypeResult Type,
4631 Decl *DeclFromDeclSpec);
4632
4633 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4634 /// including handling of its default argument expressions.
4635 ///
4636 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4637 ExprResult
4638 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4639 NamedDecl *FoundDecl,
4640 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4641 bool HadMultipleCandidates, bool IsListInitialization,
4642 bool IsStdInitListInitialization,
4643 bool RequiresZeroInit, unsigned ConstructKind,
4644 SourceRange ParenRange);
4645
4646 /// Build a CXXConstructExpr whose constructor has already been resolved if
4647 /// it denotes an inherited constructor.
4648 ExprResult
4649 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4650 CXXConstructorDecl *Constructor, bool Elidable,
4651 MultiExprArg Exprs,
4652 bool HadMultipleCandidates, bool IsListInitialization,
4653 bool IsStdInitListInitialization,
4654 bool RequiresZeroInit, unsigned ConstructKind,
4655 SourceRange ParenRange);
4656
4657 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4658 // the constructor can be elidable?
4659 ExprResult
4660 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4661 NamedDecl *FoundDecl,
4662 CXXConstructorDecl *Constructor, bool Elidable,
4663 MultiExprArg Exprs, bool HadMultipleCandidates,
4664 bool IsListInitialization,
4665 bool IsStdInitListInitialization, bool RequiresZeroInit,
4666 unsigned ConstructKind, SourceRange ParenRange);
4667
4668 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4669
4670
4671 /// Instantiate or parse a C++ default argument expression as necessary.
4672 /// Return true on error.
4673 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4674 ParmVarDecl *Param);
4675
4676 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4677 /// the default expr if needed.
4678 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4679 FunctionDecl *FD,
4680 ParmVarDecl *Param);
4681
4682 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4683 /// constructed variable.
4684 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4685
4686 /// \brief Helper class that collects exception specifications for
4687 /// implicitly-declared special member functions.
4688 class ImplicitExceptionSpecification {
4689 // Pointer to allow copying
4690 Sema *Self;
4691 // We order exception specifications thus:
4692 // noexcept is the most restrictive, but is only used in C++11.
4693 // throw() comes next.
4694 // Then a throw(collected exceptions)
4695 // Finally no specification, which is expressed as noexcept(false).
4696 // throw(...) is used instead if any called function uses it.
4697 ExceptionSpecificationType ComputedEST;
4698 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4699 SmallVector<QualType, 4> Exceptions;
4700
4701 void ClearExceptions() {
4702 ExceptionsSeen.clear();
4703 Exceptions.clear();
4704 }
4705
4706 public:
4707 explicit ImplicitExceptionSpecification(Sema &Self)
4708 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4709 if (!Self.getLangOpts().CPlusPlus11)
4710 ComputedEST = EST_DynamicNone;
4711 }
4712
4713 /// \brief Get the computed exception specification type.
4714 ExceptionSpecificationType getExceptionSpecType() const {
4715 assert(ComputedEST != EST_ComputedNoexcept &&(static_cast <bool> (ComputedEST != EST_ComputedNoexcept
&& "noexcept(expr) should not be a possible result")
? void (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 4716, __extension__ __PRETTY_FUNCTION__))
4716 "noexcept(expr) should not be a possible result")(static_cast <bool> (ComputedEST != EST_ComputedNoexcept
&& "noexcept(expr) should not be a possible result")
? void (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 4716, __extension__ __PRETTY_FUNCTION__))
;
4717 return ComputedEST;
4718 }
4719
4720 /// \brief The number of exceptions in the exception specification.
4721 unsigned size() const { return Exceptions.size(); }
4722
4723 /// \brief The set of exceptions in the exception specification.
4724 const QualType *data() const { return Exceptions.data(); }
4725
4726 /// \brief Integrate another called method into the collected data.
4727 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4728
4729 /// \brief Integrate an invoked expression into the collected data.
4730 void CalledExpr(Expr *E);
4731
4732 /// \brief Overwrite an EPI's exception specification with this
4733 /// computed exception specification.
4734 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4735 FunctionProtoType::ExceptionSpecInfo ESI;
4736 ESI.Type = getExceptionSpecType();
4737 if (ESI.Type == EST_Dynamic) {
4738 ESI.Exceptions = Exceptions;
4739 } else if (ESI.Type == EST_None) {
4740 /// C++11 [except.spec]p14:
4741 /// The exception-specification is noexcept(false) if the set of
4742 /// potential exceptions of the special member function contains "any"
4743 ESI.Type = EST_ComputedNoexcept;
4744 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4745 tok::kw_false).get();
4746 }
4747 return ESI;
4748 }
4749 };
4750
4751 /// \brief Determine what sort of exception specification a defaulted
4752 /// copy constructor of a class will have.
4753 ImplicitExceptionSpecification
4754 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4755 CXXMethodDecl *MD);
4756
4757 /// \brief Determine what sort of exception specification a defaulted
4758 /// default constructor of a class will have, and whether the parameter
4759 /// will be const.
4760 ImplicitExceptionSpecification
4761 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4762
4763 /// \brief Determine what sort of exception specification a defautled
4764 /// copy assignment operator of a class will have, and whether the
4765 /// parameter will be const.
4766 ImplicitExceptionSpecification
4767 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4768
4769 /// \brief Determine what sort of exception specification a defaulted move
4770 /// constructor of a class will have.
4771 ImplicitExceptionSpecification
4772 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4773
4774 /// \brief Determine what sort of exception specification a defaulted move
4775 /// assignment operator of a class will have.
4776 ImplicitExceptionSpecification
4777 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4778
4779 /// \brief Determine what sort of exception specification a defaulted
4780 /// destructor of a class will have.
4781 ImplicitExceptionSpecification
4782 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4783
4784 /// \brief Determine what sort of exception specification an inheriting
4785 /// constructor of a class will have.
4786 ImplicitExceptionSpecification
4787 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4788 CXXConstructorDecl *CD);
4789
4790 /// \brief Evaluate the implicit exception specification for a defaulted
4791 /// special member function.
4792 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4793
4794 /// \brief Check the given exception-specification and update the
4795 /// exception specification information with the results.
4796 void checkExceptionSpecification(bool IsTopLevel,
4797 ExceptionSpecificationType EST,
4798 ArrayRef<ParsedType> DynamicExceptions,
4799 ArrayRef<SourceRange> DynamicExceptionRanges,
4800 Expr *NoexceptExpr,
4801 SmallVectorImpl<QualType> &Exceptions,
4802 FunctionProtoType::ExceptionSpecInfo &ESI);
4803
4804 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4805 /// parse an exception specification to work around a libstdc++ bug.
4806 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4807
4808 /// \brief Add an exception-specification to the given member function
4809 /// (or member function template). The exception-specification was parsed
4810 /// after the method itself was declared.
4811 void actOnDelayedExceptionSpecification(Decl *Method,
4812 ExceptionSpecificationType EST,
4813 SourceRange SpecificationRange,
4814 ArrayRef<ParsedType> DynamicExceptions,
4815 ArrayRef<SourceRange> DynamicExceptionRanges,
4816 Expr *NoexceptExpr);
4817
4818 class InheritedConstructorInfo;
4819
4820 /// \brief Determine if a special member function should have a deleted
4821 /// definition when it is defaulted.
4822 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4823 InheritedConstructorInfo *ICI = nullptr,
4824 bool Diagnose = false);
4825
4826 /// \brief Declare the implicit default constructor for the given class.
4827 ///
4828 /// \param ClassDecl The class declaration into which the implicit
4829 /// default constructor will be added.
4830 ///
4831 /// \returns The implicitly-declared default constructor.
4832 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4833 CXXRecordDecl *ClassDecl);
4834
4835 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4836 /// defining this constructor as the default constructor.
4837 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4838 CXXConstructorDecl *Constructor);
4839
4840 /// \brief Declare the implicit destructor for the given class.
4841 ///
4842 /// \param ClassDecl The class declaration into which the implicit
4843 /// destructor will be added.
4844 ///
4845 /// \returns The implicitly-declared destructor.
4846 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4847
4848 /// DefineImplicitDestructor - Checks for feasibility of
4849 /// defining this destructor as the default destructor.
4850 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4851 CXXDestructorDecl *Destructor);
4852
4853 /// \brief Build an exception spec for destructors that don't have one.
4854 ///
4855 /// C++11 says that user-defined destructors with no exception spec get one
4856 /// that looks as if the destructor was implicitly declared.
4857 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4858 CXXDestructorDecl *Destructor);
4859
4860 /// \brief Define the specified inheriting constructor.
4861 void DefineInheritingConstructor(SourceLocation UseLoc,
4862 CXXConstructorDecl *Constructor);
4863
4864 /// \brief Declare the implicit copy constructor for the given class.
4865 ///
4866 /// \param ClassDecl The class declaration into which the implicit
4867 /// copy constructor will be added.
4868 ///
4869 /// \returns The implicitly-declared copy constructor.
4870 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4871
4872 /// DefineImplicitCopyConstructor - Checks for feasibility of
4873 /// defining this constructor as the copy constructor.
4874 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4875 CXXConstructorDecl *Constructor);
4876
4877 /// \brief Declare the implicit move constructor for the given class.
4878 ///
4879 /// \param ClassDecl The Class declaration into which the implicit
4880 /// move constructor will be added.
4881 ///
4882 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4883 /// declared.
4884 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4885
4886 /// DefineImplicitMoveConstructor - Checks for feasibility of
4887 /// defining this constructor as the move constructor.
4888 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4889 CXXConstructorDecl *Constructor);
4890
4891 /// \brief Declare the implicit copy assignment operator for the given class.
4892 ///
4893 /// \param ClassDecl The class declaration into which the implicit
4894 /// copy assignment operator will be added.
4895 ///
4896 /// \returns The implicitly-declared copy assignment operator.
4897 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4898
4899 /// \brief Defines an implicitly-declared copy assignment operator.
4900 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4901 CXXMethodDecl *MethodDecl);
4902
4903 /// \brief Declare the implicit move assignment operator for the given class.
4904 ///
4905 /// \param ClassDecl The Class declaration into which the implicit
4906 /// move assignment operator will be added.
4907 ///
4908 /// \returns The implicitly-declared move assignment operator, or NULL if it
4909 /// wasn't declared.
4910 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4911
4912 /// \brief Defines an implicitly-declared move assignment operator.
4913 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4914 CXXMethodDecl *MethodDecl);
4915
4916 /// \brief Force the declaration of any implicitly-declared members of this
4917 /// class.
4918 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4919
4920 /// \brief Check a completed declaration of an implicit special member.
4921 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4922
4923 /// \brief Determine whether the given function is an implicitly-deleted
4924 /// special member function.
4925 bool isImplicitlyDeleted(FunctionDecl *FD);
4926
4927 /// \brief Check whether 'this' shows up in the type of a static member
4928 /// function after the (naturally empty) cv-qualifier-seq would be.
4929 ///
4930 /// \returns true if an error occurred.
4931 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4932
4933 /// \brief Whether this' shows up in the exception specification of a static
4934 /// member function.
4935 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4936
4937 /// \brief Check whether 'this' shows up in the attributes of the given
4938 /// static member function.
4939 ///
4940 /// \returns true if an error occurred.
4941 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4942
4943 /// MaybeBindToTemporary - If the passed in expression has a record type with
4944 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4945 /// it simply returns the passed in expression.
4946 ExprResult MaybeBindToTemporary(Expr *E);
4947
4948 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4949 MultiExprArg ArgsPtr,
4950 SourceLocation Loc,
4951 SmallVectorImpl<Expr*> &ConvertedArgs,
4952 bool AllowExplicit = false,
4953 bool IsListInitialization = false);
4954
4955 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4956 SourceLocation NameLoc,
4957 IdentifierInfo &Name);
4958
4959 ParsedType getDestructorName(SourceLocation TildeLoc,
4960 IdentifierInfo &II, SourceLocation NameLoc,
4961 Scope *S, CXXScopeSpec &SS,
4962 ParsedType ObjectType,
4963 bool EnteringContext);
4964
4965 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4966 ParsedType ObjectType);
4967
4968 // Checks that reinterpret casts don't have undefined behavior.
4969 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4970 bool IsDereference, SourceRange Range);
4971
4972 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4973 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4974 tok::TokenKind Kind,
4975 SourceLocation LAngleBracketLoc,
4976 Declarator &D,
4977 SourceLocation RAngleBracketLoc,
4978 SourceLocation LParenLoc,
4979 Expr *E,
4980 SourceLocation RParenLoc);
4981
4982 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4983 tok::TokenKind Kind,
4984 TypeSourceInfo *Ty,
4985 Expr *E,
4986 SourceRange AngleBrackets,
4987 SourceRange Parens);
4988
4989 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4990 SourceLocation TypeidLoc,
4991 TypeSourceInfo *Operand,
4992 SourceLocation RParenLoc);
4993 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4994 SourceLocation TypeidLoc,
4995 Expr *Operand,
4996 SourceLocation RParenLoc);
4997
4998 /// ActOnCXXTypeid - Parse typeid( something ).
4999 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5000 SourceLocation LParenLoc, bool isType,
5001 void *TyOrExpr,
5002 SourceLocation RParenLoc);
5003
5004 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5005 SourceLocation TypeidLoc,
5006 TypeSourceInfo *Operand,
5007 SourceLocation RParenLoc);
5008 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5009 SourceLocation TypeidLoc,
5010 Expr *Operand,
5011 SourceLocation RParenLoc);
5012
5013 /// ActOnCXXUuidof - Parse __uuidof( something ).
5014 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5015 SourceLocation LParenLoc, bool isType,
5016 void *TyOrExpr,
5017 SourceLocation RParenLoc);
5018
5019 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
5020 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5021 tok::TokenKind Operator,
5022 SourceLocation EllipsisLoc, Expr *RHS,
5023 SourceLocation RParenLoc);
5024 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5025 BinaryOperatorKind Operator,
5026 SourceLocation EllipsisLoc, Expr *RHS,
5027 SourceLocation RParenLoc);
5028 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
5029 BinaryOperatorKind Operator);
5030
5031 //// ActOnCXXThis - Parse 'this' pointer.
5032 ExprResult ActOnCXXThis(SourceLocation loc);
5033
5034 /// \brief Try to retrieve the type of the 'this' pointer.
5035 ///
5036 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
5037 QualType getCurrentThisType();
5038
5039 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
5040 /// current context not being a non-static member function. In such cases,
5041 /// this provides the type used for 'this'.
5042 QualType CXXThisTypeOverride;
5043
5044 /// \brief RAII object used to temporarily allow the C++ 'this' expression
5045 /// to be used, with the given qualifiers on the current class type.
5046 class CXXThisScopeRAII {
5047 Sema &S;
5048 QualType OldCXXThisTypeOverride;
5049 bool Enabled;
5050
5051 public:
5052 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
5053 /// using the given declaration (which is either a class template or a
5054 /// class) along with the given qualifiers.
5055 /// along with the qualifiers placed on '*this'.
5056 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
5057 bool Enabled = true);
5058
5059 ~CXXThisScopeRAII();
5060 };
5061
5062 /// \brief Make sure the value of 'this' is actually available in the current
5063 /// context, if it is a potentially evaluated context.
5064 ///
5065 /// \param Loc The location at which the capture of 'this' occurs.
5066 ///
5067 /// \param Explicit Whether 'this' is explicitly captured in a lambda
5068 /// capture list.
5069 ///
5070 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5071 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5072 /// This is useful when enclosing lambdas must speculatively capture
5073 /// 'this' that may or may not be used in certain specializations of
5074 /// a nested generic lambda (depending on whether the name resolves to
5075 /// a non-static member function or a static function).
5076 /// \return returns 'true' if failed, 'false' if success.
5077 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5078 bool BuildAndDiagnose = true,
5079 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5080 bool ByCopy = false);
5081
5082 /// \brief Determine whether the given type is the type of *this that is used
5083 /// outside of the body of a member function for a type that is currently
5084 /// being defined.
5085 bool isThisOutsideMemberFunctionBody(QualType BaseType);
5086
5087 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5088 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5089
5090
5091 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5092 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5093
5094 ExprResult
5095 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5096 SourceLocation AtLoc, SourceLocation RParen);
5097
5098 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5099 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5100
5101 //// ActOnCXXThrow - Parse throw expressions.
5102 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5103 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5104 bool IsThrownVarInScope);
5105 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5106
5107 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5108 /// Can be interpreted either as function-style casting ("int(x)")
5109 /// or class type construction ("ClassType(x,y,z)")
5110 /// or creation of a value-initialized type ("int()").
5111 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5112 SourceLocation LParenOrBraceLoc,
5113 MultiExprArg Exprs,
5114 SourceLocation RParenOrBraceLoc,
5115 bool ListInitialization);
5116
5117 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5118 SourceLocation LParenLoc,
5119 MultiExprArg Exprs,
5120 SourceLocation RParenLoc,
5121 bool ListInitialization);
5122
5123 /// ActOnCXXNew - Parsed a C++ 'new' expression.
5124 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5125 SourceLocation PlacementLParen,
5126 MultiExprArg PlacementArgs,
5127 SourceLocation PlacementRParen,
5128 SourceRange TypeIdParens, Declarator &D,
5129 Expr *Initializer);
5130 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5131 SourceLocation PlacementLParen,
5132 MultiExprArg PlacementArgs,
5133 SourceLocation PlacementRParen,
5134 SourceRange TypeIdParens,
5135 QualType AllocType,
5136 TypeSourceInfo *AllocTypeInfo,
5137 Expr *ArraySize,
5138 SourceRange DirectInitRange,
5139 Expr *Initializer);
5140
5141 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5142 SourceRange R);
5143
5144 /// \brief The scope in which to find allocation functions.
5145 enum AllocationFunctionScope {
5146 /// \brief Only look for allocation functions in the global scope.
5147 AFS_Global,
5148 /// \brief Only look for allocation functions in the scope of the
5149 /// allocated class.
5150 AFS_Class,
5151 /// \brief Look for allocation functions in both the global scope
5152 /// and in the scope of the allocated class.
5153 AFS_Both
5154 };
5155
5156 /// \brief Finds the overloads of operator new and delete that are appropriate
5157 /// for the allocation.
5158 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5159 AllocationFunctionScope NewScope,
5160 AllocationFunctionScope DeleteScope,
5161 QualType AllocType, bool IsArray,
5162 bool &PassAlignment, MultiExprArg PlaceArgs,
5163 FunctionDecl *&OperatorNew,
5164 FunctionDecl *&OperatorDelete,
5165 bool Diagnose = true);
5166 void DeclareGlobalNewDelete();
5167 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5168 ArrayRef<QualType> Params);
5169
5170 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5171 DeclarationName Name, FunctionDecl* &Operator,
5172 bool Diagnose = true);
5173 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5174 bool CanProvideSize,
5175 bool Overaligned,
5176 DeclarationName Name);
5177 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5178 CXXRecordDecl *RD);
5179
5180 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5181 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5182 bool UseGlobal, bool ArrayForm,
5183 Expr *Operand);
5184 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5185 bool IsDelete, bool CallCanBeVirtual,
5186 bool WarnOnNonAbstractTypes,
5187 SourceLocation DtorLoc);
5188
5189 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5190 Expr *Operand, SourceLocation RParen);
5191 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5192 SourceLocation RParen);
5193
5194 /// \brief Parsed one of the type trait support pseudo-functions.
5195 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5196 ArrayRef<ParsedType> Args,
5197 SourceLocation RParenLoc);
5198 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5199 ArrayRef<TypeSourceInfo *> Args,
5200 SourceLocation RParenLoc);
5201
5202 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5203 /// pseudo-functions.
5204 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5205 SourceLocation KWLoc,
5206 ParsedType LhsTy,
5207 Expr *DimExpr,
5208 SourceLocation RParen);
5209
5210 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5211 SourceLocation KWLoc,
5212 TypeSourceInfo *TSInfo,
5213 Expr *DimExpr,
5214 SourceLocation RParen);
5215
5216 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5217 /// pseudo-functions.
5218 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5219 SourceLocation KWLoc,
5220 Expr *Queried,
5221 SourceLocation RParen);
5222
5223 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5224 SourceLocation KWLoc,
5225 Expr *Queried,
5226 SourceLocation RParen);
5227
5228 ExprResult ActOnStartCXXMemberReference(Scope *S,
5229 Expr *Base,
5230 SourceLocation OpLoc,
5231 tok::TokenKind OpKind,
5232 ParsedType &ObjectType,
5233 bool &MayBePseudoDestructor);
5234
5235 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5236 SourceLocation OpLoc,
5237 tok::TokenKind OpKind,
5238 const CXXScopeSpec &SS,
5239 TypeSourceInfo *ScopeType,
5240 SourceLocation CCLoc,
5241 SourceLocation TildeLoc,
5242 PseudoDestructorTypeStorage DestroyedType);
5243
5244 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5245 SourceLocation OpLoc,
5246 tok::TokenKind OpKind,
5247 CXXScopeSpec &SS,
5248 UnqualifiedId &FirstTypeName,
5249 SourceLocation CCLoc,
5250 SourceLocation TildeLoc,
5251 UnqualifiedId &SecondTypeName);
5252
5253 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5254 SourceLocation OpLoc,
5255 tok::TokenKind OpKind,
5256 SourceLocation TildeLoc,
5257 const DeclSpec& DS);
5258
5259 /// MaybeCreateExprWithCleanups - If the current full-expression
5260 /// requires any cleanups, surround it with a ExprWithCleanups node.
5261 /// Otherwise, just returns the passed-in expression.
5262 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5263 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5264 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5265
5266 MaterializeTemporaryExpr *
5267 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5268 bool BoundToLvalueReference);
5269
5270 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5271 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5272 : SourceLocation());
5273 }
5274 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5275 bool DiscardedValue = false,
5276 bool IsConstexpr = false,
5277 bool IsLambdaInitCaptureInitializer = false);
5278 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5279
5280 // Marks SS invalid if it represents an incomplete type.
5281 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5282
5283 DeclContext *computeDeclContext(QualType T);
5284 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5285 bool EnteringContext = false);
5286 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5287 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5288
5289 /// \brief The parser has parsed a global nested-name-specifier '::'.
5290 ///
5291 /// \param CCLoc The location of the '::'.
5292 ///
5293 /// \param SS The nested-name-specifier, which will be updated in-place
5294 /// to reflect the parsed nested-name-specifier.
5295 ///
5296 /// \returns true if an error occurred, false otherwise.
5297 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5298
5299 /// \brief The parser has parsed a '__super' nested-name-specifier.
5300 ///
5301 /// \param SuperLoc The location of the '__super' keyword.
5302 ///
5303 /// \param ColonColonLoc The location of the '::'.
5304 ///
5305 /// \param SS The nested-name-specifier, which will be updated in-place
5306 /// to reflect the parsed nested-name-specifier.
5307 ///
5308 /// \returns true if an error occurred, false otherwise.
5309 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5310 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5311
5312 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5313 bool *CanCorrect = nullptr);
5314 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5315
5316 /// \brief Keeps information about an identifier in a nested-name-spec.
5317 ///
5318 struct NestedNameSpecInfo {
5319 /// \brief The type of the object, if we're parsing nested-name-specifier in
5320 /// a member access expression.
5321 ParsedType ObjectType;
5322
5323 /// \brief The identifier preceding the '::'.
5324 IdentifierInfo *Identifier;
5325
5326 /// \brief The location of the identifier.
5327 SourceLocation IdentifierLoc;
5328
5329 /// \brief The location of the '::'.
5330 SourceLocation CCLoc;
5331
5332 /// \brief Creates info object for the most typical case.
5333 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5334 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5335 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5336 CCLoc(ColonColonLoc) {
5337 }
5338
5339 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5340 SourceLocation ColonColonLoc, QualType ObjectType)
5341 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5342 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5343 }
5344 };
5345
5346 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5347 NestedNameSpecInfo &IdInfo);
5348
5349 bool BuildCXXNestedNameSpecifier(Scope *S,
5350 NestedNameSpecInfo &IdInfo,
5351 bool EnteringContext,
5352 CXXScopeSpec &SS,
5353 NamedDecl *ScopeLookupResult,
5354 bool ErrorRecoveryLookup,
5355 bool *IsCorrectedToColon = nullptr,
5356 bool OnlyNamespace = false);
5357
5358 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5359 ///
5360 /// \param S The scope in which this nested-name-specifier occurs.
5361 ///
5362 /// \param IdInfo Parser information about an identifier in the
5363 /// nested-name-spec.
5364 ///
5365 /// \param EnteringContext Whether we're entering the context nominated by
5366 /// this nested-name-specifier.
5367 ///
5368 /// \param SS The nested-name-specifier, which is both an input
5369 /// parameter (the nested-name-specifier before this type) and an
5370 /// output parameter (containing the full nested-name-specifier,
5371 /// including this new type).
5372 ///
5373 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5374 /// error recovery. In this case do not emit error message.
5375 ///
5376 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5377 /// are allowed. The bool value pointed by this parameter is set to 'true'
5378 /// if the identifier is treated as if it was followed by ':', not '::'.
5379 ///
5380 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5381 ///
5382 /// \returns true if an error occurred, false otherwise.
5383 bool ActOnCXXNestedNameSpecifier(Scope *S,
5384 NestedNameSpecInfo &IdInfo,
5385 bool EnteringContext,
5386 CXXScopeSpec &SS,
5387 bool ErrorRecoveryLookup = false,
5388 bool *IsCorrectedToColon = nullptr,
5389 bool OnlyNamespace = false);
5390
5391 ExprResult ActOnDecltypeExpression(Expr *E);
5392
5393 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5394 const DeclSpec &DS,
5395 SourceLocation ColonColonLoc);
5396
5397 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5398 NestedNameSpecInfo &IdInfo,
5399 bool EnteringContext);
5400
5401 /// \brief The parser has parsed a nested-name-specifier
5402 /// 'template[opt] template-name < template-args >::'.
5403 ///
5404 /// \param S The scope in which this nested-name-specifier occurs.
5405 ///
5406 /// \param SS The nested-name-specifier, which is both an input
5407 /// parameter (the nested-name-specifier before this type) and an
5408 /// output parameter (containing the full nested-name-specifier,
5409 /// including this new type).
5410 ///
5411 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5412 /// \param TemplateName the template name.
5413 /// \param TemplateNameLoc The location of the template name.
5414 /// \param LAngleLoc The location of the opening angle bracket ('<').
5415 /// \param TemplateArgs The template arguments.
5416 /// \param RAngleLoc The location of the closing angle bracket ('>').
5417 /// \param CCLoc The location of the '::'.
5418 ///
5419 /// \param EnteringContext Whether we're entering the context of the
5420 /// nested-name-specifier.
5421 ///
5422 ///
5423 /// \returns true if an error occurred, false otherwise.
5424 bool ActOnCXXNestedNameSpecifier(Scope *S,
5425 CXXScopeSpec &SS,
5426 SourceLocation TemplateKWLoc,
5427 TemplateTy TemplateName,
5428 SourceLocation TemplateNameLoc,
5429 SourceLocation LAngleLoc,
5430 ASTTemplateArgsPtr TemplateArgs,
5431 SourceLocation RAngleLoc,
5432 SourceLocation CCLoc,
5433 bool EnteringContext);
5434
5435 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5436 /// that the parser can use later to reconstruct the given
5437 /// nested-name-specifier.
5438 ///
5439 /// \param SS A nested-name-specifier.
5440 ///
5441 /// \returns A pointer containing all of the information in the
5442 /// nested-name-specifier \p SS.
5443 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5444
5445 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5446 /// the nested-name-specifier structure.
5447 ///
5448 /// \param Annotation The annotation pointer, produced by
5449 /// \c SaveNestedNameSpecifierAnnotation().
5450 ///
5451 /// \param AnnotationRange The source range corresponding to the annotation.
5452 ///
5453 /// \param SS The nested-name-specifier that will be updated with the contents
5454 /// of the annotation pointer.
5455 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5456 SourceRange AnnotationRange,
5457 CXXScopeSpec &SS);
5458
5459 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5460
5461 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5462 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5463 /// After this method is called, according to [C++ 3.4.3p3], names should be
5464 /// looked up in the declarator-id's scope, until the declarator is parsed and
5465 /// ActOnCXXExitDeclaratorScope is called.
5466 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5467 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5468
5469 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5470 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5471 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5472 /// Used to indicate that names should revert to being looked up in the
5473 /// defining scope.
5474 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5475
5476 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5477 /// initializer for the declaration 'Dcl'.
5478 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5479 /// static data member of class X, names should be looked up in the scope of
5480 /// class X.
5481 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5482
5483 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5484 /// initializer for the declaration 'Dcl'.
5485 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5486
5487 /// \brief Create a new lambda closure type.
5488 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5489 TypeSourceInfo *Info,
5490 bool KnownDependent,
5491 LambdaCaptureDefault CaptureDefault);
5492
5493 /// \brief Start the definition of a lambda expression.
5494 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5495 SourceRange IntroducerRange,
5496 TypeSourceInfo *MethodType,
5497 SourceLocation EndLoc,
5498 ArrayRef<ParmVarDecl *> Params,
5499 bool IsConstexprSpecified);
5500
5501 /// \brief Endow the lambda scope info with the relevant properties.
5502 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5503 CXXMethodDecl *CallOperator,
5504 SourceRange IntroducerRange,
5505 LambdaCaptureDefault CaptureDefault,
5506 SourceLocation CaptureDefaultLoc,
5507 bool ExplicitParams,
5508 bool ExplicitResultType,
5509 bool Mutable);
5510
5511 /// \brief Perform initialization analysis of the init-capture and perform
5512 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5513 /// not being used to initialize a reference.
5514 ParsedType actOnLambdaInitCaptureInitialization(
5515 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5516 LambdaCaptureInitKind InitKind, Expr *&Init) {
5517 return ParsedType::make(buildLambdaInitCaptureInitialization(
5518 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5519 }
5520 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5521 IdentifierInfo *Id,
5522 bool DirectInit, Expr *&Init);
5523
5524 /// \brief Create a dummy variable within the declcontext of the lambda's
5525 /// call operator, for name lookup purposes for a lambda init capture.
5526 ///
5527 /// CodeGen handles emission of lambda captures, ignoring these dummy
5528 /// variables appropriately.
5529 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5530 QualType InitCaptureType,
5531 IdentifierInfo *Id,
5532 unsigned InitStyle, Expr *Init);
5533
5534 /// \brief Build the implicit field for an init-capture.
5535 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5536
5537 /// \brief Note that we have finished the explicit captures for the
5538 /// given lambda.
5539 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5540
5541 /// \brief Introduce the lambda parameters into scope.
5542 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5543
5544 /// \brief Deduce a block or lambda's return type based on the return
5545 /// statements present in the body.
5546 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5547
5548 /// ActOnStartOfLambdaDefinition - This is called just before we start
5549 /// parsing the body of a lambda; it analyzes the explicit captures and
5550 /// arguments, and sets up various data-structures for the body of the
5551 /// lambda.
5552 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5553 Declarator &ParamInfo, Scope *CurScope);
5554
5555 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5556 /// is invoked to pop the information about the lambda.
5557 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5558 bool IsInstantiation = false);
5559
5560 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5561 /// was successfully completed.
5562 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5563 Scope *CurScope);
5564
5565 /// \brief Does copying/destroying the captured variable have side effects?
5566 bool CaptureHasSideEffects(const sema::Capture &From);
5567
5568 /// \brief Diagnose if an explicit lambda capture is unused.
5569 void DiagnoseUnusedLambdaCapture(const sema::Capture &From);
5570
5571 /// \brief Complete a lambda-expression having processed and attached the
5572 /// lambda body.
5573 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5574 sema::LambdaScopeInfo *LSI);
5575
5576 /// Get the return type to use for a lambda's conversion function(s) to
5577 /// function pointer type, given the type of the call operator.
5578 QualType
5579 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
5580
5581 /// \brief Define the "body" of the conversion from a lambda object to a
5582 /// function pointer.
5583 ///
5584 /// This routine doesn't actually define a sensible body; rather, it fills
5585 /// in the initialization expression needed to copy the lambda object into
5586 /// the block, and IR generation actually generates the real body of the
5587 /// block pointer conversion.
5588 void DefineImplicitLambdaToFunctionPointerConversion(
5589 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5590
5591 /// \brief Define the "body" of the conversion from a lambda object to a
5592 /// block pointer.
5593 ///
5594 /// This routine doesn't actually define a sensible body; rather, it fills
5595 /// in the initialization expression needed to copy the lambda object into
5596 /// the block, and IR generation actually generates the real body of the
5597 /// block pointer conversion.
5598 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5599 CXXConversionDecl *Conv);
5600
5601 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5602 SourceLocation ConvLocation,
5603 CXXConversionDecl *Conv,
5604 Expr *Src);
5605
5606 // ParseObjCStringLiteral - Parse Objective-C string literals.
5607 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5608 ArrayRef<Expr *> Strings);
5609
5610 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5611
5612 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5613 /// numeric literal expression. Type of the expression will be "NSNumber *"
5614 /// or "id" if NSNumber is unavailable.
5615 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5616 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5617 bool Value);
5618 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5619
5620 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5621 /// '@' prefixed parenthesized expression. The type of the expression will
5622 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5623 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5624 /// "const char *" or C structure with attribute 'objc_boxable'.
5625 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5626
5627 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5628 Expr *IndexExpr,
5629 ObjCMethodDecl *getterMethod,
5630 ObjCMethodDecl *setterMethod);
5631
5632 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5633 MutableArrayRef<ObjCDictionaryElement> Elements);
5634
5635 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5636 TypeSourceInfo *EncodedTypeInfo,
5637 SourceLocation RParenLoc);
5638 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5639 CXXConversionDecl *Method,
5640 bool HadMultipleCandidates);
5641
5642 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5643 SourceLocation EncodeLoc,
5644 SourceLocation LParenLoc,
5645 ParsedType Ty,
5646 SourceLocation RParenLoc);
5647
5648 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5649 ExprResult ParseObjCSelectorExpression(Selector Sel,
5650 SourceLocation AtLoc,
5651 SourceLocation SelLoc,
5652 SourceLocation LParenLoc,
5653 SourceLocation RParenLoc,
5654 bool WarnMultipleSelectors);
5655
5656 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5657 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5658 SourceLocation AtLoc,
5659 SourceLocation ProtoLoc,
5660 SourceLocation LParenLoc,
5661 SourceLocation ProtoIdLoc,
5662 SourceLocation RParenLoc);
5663
5664 //===--------------------------------------------------------------------===//
5665 // C++ Declarations
5666 //
5667 Decl *ActOnStartLinkageSpecification(Scope *S,
5668 SourceLocation ExternLoc,
5669 Expr *LangStr,
5670 SourceLocation LBraceLoc);
5671 Decl *ActOnFinishLinkageSpecification(Scope *S,
5672 Decl *LinkageSpec,
5673 SourceLocation RBraceLoc);
5674
5675
5676 //===--------------------------------------------------------------------===//
5677 // C++ Classes
5678 //
5679 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5680 const CXXScopeSpec *SS = nullptr);
5681 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5682
5683 bool ActOnAccessSpecifier(AccessSpecifier Access,
5684 SourceLocation ASLoc,
5685 SourceLocation ColonLoc,
5686 AttributeList *Attrs = nullptr);
5687
5688 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5689 Declarator &D,
5690 MultiTemplateParamsArg TemplateParameterLists,
5691 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5692 InClassInitStyle InitStyle);
5693
5694 void ActOnStartCXXInClassMemberInitializer();
5695 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5696 SourceLocation EqualLoc,
5697 Expr *Init);
5698
5699 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5700 Scope *S,
5701 CXXScopeSpec &SS,
5702 IdentifierInfo *MemberOrBase,
5703 ParsedType TemplateTypeTy,
5704 const DeclSpec &DS,
5705 SourceLocation IdLoc,
5706 SourceLocation LParenLoc,
5707 ArrayRef<Expr *> Args,
5708 SourceLocation RParenLoc,
5709 SourceLocation EllipsisLoc);
5710
5711 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5712 Scope *S,
5713 CXXScopeSpec &SS,
5714 IdentifierInfo *MemberOrBase,
5715 ParsedType TemplateTypeTy,
5716 const DeclSpec &DS,
5717 SourceLocation IdLoc,
5718 Expr *InitList,
5719 SourceLocation EllipsisLoc);
5720
5721 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5722 Scope *S,
5723 CXXScopeSpec &SS,
5724 IdentifierInfo *MemberOrBase,
5725 ParsedType TemplateTypeTy,
5726 const DeclSpec &DS,
5727 SourceLocation IdLoc,
5728 Expr *Init,
5729 SourceLocation EllipsisLoc);
5730
5731 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5732 Expr *Init,
5733 SourceLocation IdLoc);
5734
5735 MemInitResult BuildBaseInitializer(QualType BaseType,
5736 TypeSourceInfo *BaseTInfo,
5737 Expr *Init,
5738 CXXRecordDecl *ClassDecl,
5739 SourceLocation EllipsisLoc);
5740
5741 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5742 Expr *Init,
5743 CXXRecordDecl *ClassDecl);
5744
5745 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5746 CXXCtorInitializer *Initializer);
5747
5748 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5749 ArrayRef<CXXCtorInitializer *> Initializers = None);
5750
5751 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5752
5753
5754 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5755 /// mark all the non-trivial destructors of its members and bases as
5756 /// referenced.
5757 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5758 CXXRecordDecl *Record);
5759
5760 /// \brief The list of classes whose vtables have been used within
5761 /// this translation unit, and the source locations at which the
5762 /// first use occurred.
5763 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5764
5765 /// \brief The list of vtables that are required but have not yet been
5766 /// materialized.
5767 SmallVector<VTableUse, 16> VTableUses;
5768
5769 /// \brief The set of classes whose vtables have been used within
5770 /// this translation unit, and a bit that will be true if the vtable is
5771 /// required to be emitted (otherwise, it should be emitted only if needed
5772 /// by code generation).
5773 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5774
5775 /// \brief Load any externally-stored vtable uses.
5776 void LoadExternalVTableUses();
5777
5778 /// \brief Note that the vtable for the given class was used at the
5779 /// given location.
5780 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5781 bool DefinitionRequired = false);
5782
5783 /// \brief Mark the exception specifications of all virtual member functions
5784 /// in the given class as needed.
5785 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5786 const CXXRecordDecl *RD);
5787
5788 /// MarkVirtualMembersReferenced - Will mark all members of the given
5789 /// CXXRecordDecl referenced.
5790 void MarkVirtualMembersReferenced(SourceLocation Loc,
5791 const CXXRecordDecl *RD);
5792
5793 /// \brief Define all of the vtables that have been used in this
5794 /// translation unit and reference any virtual members used by those
5795 /// vtables.
5796 ///
5797 /// \returns true if any work was done, false otherwise.
5798 bool DefineUsedVTables();
5799
5800 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5801
5802 void ActOnMemInitializers(Decl *ConstructorDecl,
5803 SourceLocation ColonLoc,
5804 ArrayRef<CXXCtorInitializer*> MemInits,
5805 bool AnyErrors);
5806
5807 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5808 /// ensure that referenceDLLExportedClassMethods is called some point later
5809 /// when all outer classes of Class are complete.
5810 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5811
5812 void referenceDLLExportedClassMethods();
5813
5814 void propagateDLLAttrToBaseClassTemplate(
5815 CXXRecordDecl *Class, Attr *ClassAttr,
5816 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5817 SourceLocation BaseLoc);
5818
5819 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5820
5821 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
5822 /// conditions that are needed for the attribute to have an effect.
5823 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
5824
5825 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5826 Decl *TagDecl,
5827 SourceLocation LBrac,
5828 SourceLocation RBrac,
5829 AttributeList *AttrList);
5830 void ActOnFinishCXXMemberDecls();
5831 void ActOnFinishCXXNonNestedClass(Decl *D);
5832
5833 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5834 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5835 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5836 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5837 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5838 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5839 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5840 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5841 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5842 CachedTokens &Toks);
5843 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5844 bool IsInsideALocalClassWithinATemplateFunction();
5845
5846 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5847 Expr *AssertExpr,
5848 Expr *AssertMessageExpr,
5849 SourceLocation RParenLoc);
5850 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5851 Expr *AssertExpr,
5852 StringLiteral *AssertMessageExpr,
5853 SourceLocation RParenLoc,
5854 bool Failed);
5855
5856 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5857 SourceLocation FriendLoc,
5858 TypeSourceInfo *TSInfo);
5859 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5860 MultiTemplateParamsArg TemplateParams);
5861 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5862 MultiTemplateParamsArg TemplateParams);
5863
5864 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5865 StorageClass& SC);
5866 void CheckConstructor(CXXConstructorDecl *Constructor);
5867 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5868 StorageClass& SC);
5869 bool CheckDestructor(CXXDestructorDecl *Destructor);
5870 void CheckConversionDeclarator(Declarator &D, QualType &R,
5871 StorageClass& SC);
5872 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5873 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5874 StorageClass &SC);
5875 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5876
5877 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5878 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5879 const FunctionProtoType *T);
5880 void CheckDelayedMemberExceptionSpecs();
5881
5882 //===--------------------------------------------------------------------===//
5883 // C++ Derived Classes
5884 //
5885
5886 /// ActOnBaseSpecifier - Parsed a base specifier
5887 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5888 SourceRange SpecifierRange,
5889 bool Virtual, AccessSpecifier Access,
5890 TypeSourceInfo *TInfo,
5891 SourceLocation EllipsisLoc);
5892
5893 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5894 SourceRange SpecifierRange,
5895 ParsedAttributes &Attrs,
5896 bool Virtual, AccessSpecifier Access,
5897 ParsedType basetype,
5898 SourceLocation BaseLoc,
5899 SourceLocation EllipsisLoc);
5900
5901 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5902 MutableArrayRef<CXXBaseSpecifier *> Bases);
5903 void ActOnBaseSpecifiers(Decl *ClassDecl,
5904 MutableArrayRef<CXXBaseSpecifier *> Bases);
5905
5906 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5907 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5908 CXXBasePaths &Paths);
5909
5910 // FIXME: I don't like this name.
5911 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5912
5913 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5914 SourceLocation Loc, SourceRange Range,
5915 CXXCastPath *BasePath = nullptr,
5916 bool IgnoreAccess = false);
5917 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5918 unsigned InaccessibleBaseID,
5919 unsigned AmbigiousBaseConvID,
5920 SourceLocation Loc, SourceRange Range,
5921 DeclarationName Name,
5922 CXXCastPath *BasePath,
5923 bool IgnoreAccess = false);
5924
5925 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5926
5927 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5928 const CXXMethodDecl *Old);
5929
5930 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5931 /// covariant, according to C++ [class.virtual]p5.
5932 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5933 const CXXMethodDecl *Old);
5934
5935 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5936 /// spec is a subset of base spec.
5937 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5938 const CXXMethodDecl *Old);
5939
5940 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5941
5942 /// CheckOverrideControl - Check C++11 override control semantics.
5943 void CheckOverrideControl(NamedDecl *D);
5944
5945 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5946 /// not used in the declaration of an overriding method.
5947 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5948
5949 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5950 /// overrides a virtual member function marked 'final', according to
5951 /// C++11 [class.virtual]p4.
5952 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5953 const CXXMethodDecl *Old);
5954
5955
5956 //===--------------------------------------------------------------------===//
5957 // C++ Access Control
5958 //
5959
5960 enum AccessResult {
5961 AR_accessible,
5962 AR_inaccessible,
5963 AR_dependent,
5964 AR_delayed
5965 };
5966
5967 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5968 NamedDecl *PrevMemberDecl,
5969 AccessSpecifier LexicalAS);
5970
5971 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5972 DeclAccessPair FoundDecl);
5973 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5974 DeclAccessPair FoundDecl);
5975 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5976 SourceRange PlacementRange,
5977 CXXRecordDecl *NamingClass,
5978 DeclAccessPair FoundDecl,
5979 bool Diagnose = true);
5980 AccessResult CheckConstructorAccess(SourceLocation Loc,
5981 CXXConstructorDecl *D,
5982 DeclAccessPair FoundDecl,
5983 const InitializedEntity &Entity,
5984 bool IsCopyBindingRefToTemp = false);
5985 AccessResult CheckConstructorAccess(SourceLocation Loc,
5986 CXXConstructorDecl *D,
5987 DeclAccessPair FoundDecl,
5988 const InitializedEntity &Entity,
5989 const PartialDiagnostic &PDiag);
5990 AccessResult CheckDestructorAccess(SourceLocation Loc,
5991 CXXDestructorDecl *Dtor,
5992 const PartialDiagnostic &PDiag,
5993 QualType objectType = QualType());
5994 AccessResult CheckFriendAccess(NamedDecl *D);
5995 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5996 CXXRecordDecl *NamingClass,
5997 DeclAccessPair Found);
5998 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5999 Expr *ObjectExpr,
6000 Expr *ArgExpr,
6001 DeclAccessPair FoundDecl);
6002 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
6003 DeclAccessPair FoundDecl);
6004 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
6005 QualType Base, QualType Derived,
6006 const CXXBasePath &Path,
6007 unsigned DiagID,
6008 bool ForceCheck = false,
6009 bool ForceUnprivileged = false);
6010 void CheckLookupAccess(const LookupResult &R);
6011 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
6012 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
6013 AccessSpecifier access,
6014 QualType objectType);
6015
6016 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
6017 const MultiLevelTemplateArgumentList &TemplateArgs);
6018 void PerformDependentDiagnostics(const DeclContext *Pattern,
6019 const MultiLevelTemplateArgumentList &TemplateArgs);
6020
6021 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
6022
6023 /// \brief When true, access checking violations are treated as SFINAE
6024 /// failures rather than hard errors.
6025 bool AccessCheckingSFINAE;
6026
6027 enum AbstractDiagSelID {
6028 AbstractNone = -1,
6029 AbstractReturnType,
6030 AbstractParamType,
6031 AbstractVariableType,
6032 AbstractFieldType,
6033 AbstractIvarType,
6034 AbstractSynthesizedIvarType,
6035 AbstractArrayType
6036 };
6037
6038 bool isAbstractType(SourceLocation Loc, QualType T);
6039 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6040 TypeDiagnoser &Diagnoser);
6041 template <typename... Ts>
6042 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6043 const Ts &...Args) {
6044 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6045 return RequireNonAbstractType(Loc, T, Diagnoser);
6046 }
6047
6048 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6049
6050 //===--------------------------------------------------------------------===//
6051 // C++ Overloaded Operators [C++ 13.5]
6052 //
6053
6054 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6055
6056 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6057
6058 //===--------------------------------------------------------------------===//
6059 // C++ Templates [C++ 14]
6060 //
6061 void FilterAcceptableTemplateNames(LookupResult &R,
6062 bool AllowFunctionTemplates = true);
6063 bool hasAnyAcceptableTemplateNames(LookupResult &R,
6064 bool AllowFunctionTemplates = true);
6065
6066 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
6067 QualType ObjectType, bool EnteringContext,
6068 bool &MemberOfUnknownSpecialization);
6069
6070 TemplateNameKind isTemplateName(Scope *S,
6071 CXXScopeSpec &SS,
6072 bool hasTemplateKeyword,
6073 UnqualifiedId &Name,
6074 ParsedType ObjectType,
6075 bool EnteringContext,
6076 TemplateTy &Template,
6077 bool &MemberOfUnknownSpecialization);
6078
6079 /// Determine whether a particular identifier might be the name in a C++1z
6080 /// deduction-guide declaration.
6081 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
6082 SourceLocation NameLoc,
6083 ParsedTemplateTy *Template = nullptr);
6084
6085 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
6086 SourceLocation IILoc,
6087 Scope *S,
6088 const CXXScopeSpec *SS,
6089 TemplateTy &SuggestedTemplate,
6090 TemplateNameKind &SuggestedKind);
6091
6092 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
6093 NamedDecl *Instantiation,
6094 bool InstantiatedFromMember,
6095 const NamedDecl *Pattern,
6096 const NamedDecl *PatternDef,
6097 TemplateSpecializationKind TSK,
6098 bool Complain = true);
6099
6100 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
6101 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
6102
6103 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
6104 SourceLocation EllipsisLoc,
6105 SourceLocation KeyLoc,
6106 IdentifierInfo *ParamName,
6107 SourceLocation ParamNameLoc,
6108 unsigned Depth, unsigned Position,
6109 SourceLocation EqualLoc,
6110 ParsedType DefaultArg);
6111
6112 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
6113 SourceLocation Loc);
6114 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
6115
6116 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
6117 unsigned Depth,
6118 unsigned Position,
6119 SourceLocation EqualLoc,
6120 Expr *DefaultArg);
6121 NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
6122 SourceLocation TmpLoc,
6123 TemplateParameterList *Params,
6124 SourceLocation EllipsisLoc,
6125 IdentifierInfo *ParamName,
6126 SourceLocation ParamNameLoc,
6127 unsigned Depth,
6128 unsigned Position,
6129 SourceLocation EqualLoc,
6130 ParsedTemplateArgument DefaultArg);
6131
6132 TemplateParameterList *
6133 ActOnTemplateParameterList(unsigned Depth,
6134 SourceLocation ExportLoc,
6135 SourceLocation TemplateLoc,
6136 SourceLocation LAngleLoc,
6137 ArrayRef<NamedDecl *> Params,
6138 SourceLocation RAngleLoc,
6139 Expr *RequiresClause);
6140
6141 /// \brief The context in which we are checking a template parameter list.
6142 enum TemplateParamListContext {
6143 TPC_ClassTemplate,
6144 TPC_VarTemplate,
6145 TPC_FunctionTemplate,
6146 TPC_ClassTemplateMember,
6147 TPC_FriendClassTemplate,
6148 TPC_FriendFunctionTemplate,
6149 TPC_FriendFunctionTemplateDefinition,
6150 TPC_TypeAliasTemplate
6151 };
6152
6153 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
6154 TemplateParameterList *OldParams,
6155 TemplateParamListContext TPC);
6156 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
6157 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
6158 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
6159 ArrayRef<TemplateParameterList *> ParamLists,
6160 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
6161
6162 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
6163 SourceLocation KWLoc, CXXScopeSpec &SS,
6164 IdentifierInfo *Name, SourceLocation NameLoc,
6165 AttributeList *Attr,
6166 TemplateParameterList *TemplateParams,
6167 AccessSpecifier AS,
6168 SourceLocation ModulePrivateLoc,
6169 SourceLocation FriendLoc,
6170 unsigned NumOuterTemplateParamLists,
6171 TemplateParameterList **OuterTemplateParamLists,
6172 SkipBodyInfo *SkipBody = nullptr);
6173
6174 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6175 QualType NTTPType,
6176 SourceLocation Loc);
6177
6178 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6179 TemplateArgumentListInfo &Out);
6180
6181 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
6182
6183 void NoteAllFoundTemplates(TemplateName Name);
6184
6185 QualType CheckTemplateIdType(TemplateName Template,
6186 SourceLocation TemplateLoc,
6187 TemplateArgumentListInfo &TemplateArgs);
6188
6189 TypeResult
6190 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6191 TemplateTy Template, IdentifierInfo *TemplateII,
6192 SourceLocation TemplateIILoc,
6193 SourceLocation LAngleLoc,
6194 ASTTemplateArgsPtr TemplateArgs,
6195 SourceLocation RAngleLoc,
6196 bool IsCtorOrDtorName = false,
6197 bool IsClassName = false);
6198
6199 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
6200 /// such as \c class T::template apply<U>.
6201 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6202 TypeSpecifierType TagSpec,
6203 SourceLocation TagLoc,
6204 CXXScopeSpec &SS,
6205 SourceLocation TemplateKWLoc,
6206 TemplateTy TemplateD,
6207 SourceLocation TemplateLoc,
6208 SourceLocation LAngleLoc,
6209 ASTTemplateArgsPtr TemplateArgsIn,
6210 SourceLocation RAngleLoc);
6211
6212 DeclResult ActOnVarTemplateSpecialization(
6213 Scope *S, Declarator &D, TypeSourceInfo *DI,
6214 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6215 StorageClass SC, bool IsPartialSpecialization);
6216
6217 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6218 SourceLocation TemplateLoc,
6219 SourceLocation TemplateNameLoc,
6220 const TemplateArgumentListInfo &TemplateArgs);
6221
6222 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6223 const DeclarationNameInfo &NameInfo,
6224 VarTemplateDecl *Template,
6225 SourceLocation TemplateLoc,
6226 const TemplateArgumentListInfo *TemplateArgs);
6227
6228 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6229 SourceLocation TemplateKWLoc,
6230 LookupResult &R,
6231 bool RequiresADL,
6232 const TemplateArgumentListInfo *TemplateArgs);
6233
6234 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6235 SourceLocation TemplateKWLoc,
6236 const DeclarationNameInfo &NameInfo,
6237 const TemplateArgumentListInfo *TemplateArgs);
6238
6239 TemplateNameKind ActOnDependentTemplateName(
6240 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6241 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6242 TemplateTy &Template, bool AllowInjectedClassName = false);
6243
6244 DeclResult
6245 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6246 SourceLocation KWLoc,
6247 SourceLocation ModulePrivateLoc,
6248 TemplateIdAnnotation &TemplateId,
6249 AttributeList *Attr,
6250 MultiTemplateParamsArg TemplateParameterLists,
6251 SkipBodyInfo *SkipBody = nullptr);
6252
6253 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6254 TemplateDecl *PrimaryTemplate,
6255 unsigned NumExplicitArgs,
6256 ArrayRef<TemplateArgument> Args);
6257 void CheckTemplatePartialSpecialization(
6258 ClassTemplatePartialSpecializationDecl *Partial);
6259 void CheckTemplatePartialSpecialization(
6260 VarTemplatePartialSpecializationDecl *Partial);
6261
6262 Decl *ActOnTemplateDeclarator(Scope *S,
6263 MultiTemplateParamsArg TemplateParameterLists,
6264 Declarator &D);
6265
6266 bool
6267 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6268 TemplateSpecializationKind NewTSK,
6269 NamedDecl *PrevDecl,
6270 TemplateSpecializationKind PrevTSK,
6271 SourceLocation PrevPtOfInstantiation,
6272 bool &SuppressNew);
6273
6274 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6275 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6276 LookupResult &Previous);
6277
6278 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6279 TemplateArgumentListInfo *ExplicitTemplateArgs,
6280 LookupResult &Previous);
6281 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6282 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6283
6284 DeclResult
6285 ActOnExplicitInstantiation(Scope *S,
6286 SourceLocation ExternLoc,
6287 SourceLocation TemplateLoc,
6288 unsigned TagSpec,
6289 SourceLocation KWLoc,
6290 const CXXScopeSpec &SS,
6291 TemplateTy Template,
6292 SourceLocation TemplateNameLoc,
6293 SourceLocation LAngleLoc,
6294 ASTTemplateArgsPtr TemplateArgs,
6295 SourceLocation RAngleLoc,
6296 AttributeList *Attr);
6297
6298 DeclResult
6299 ActOnExplicitInstantiation(Scope *S,
6300 SourceLocation ExternLoc,
6301 SourceLocation TemplateLoc,
6302 unsigned TagSpec,
6303 SourceLocation KWLoc,
6304 CXXScopeSpec &SS,
6305 IdentifierInfo *Name,
6306 SourceLocation NameLoc,
6307 AttributeList *Attr);
6308
6309 DeclResult ActOnExplicitInstantiation(Scope *S,
6310 SourceLocation ExternLoc,
6311 SourceLocation TemplateLoc,
6312 Declarator &D);
6313
6314 TemplateArgumentLoc
6315 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6316 SourceLocation TemplateLoc,
6317 SourceLocation RAngleLoc,
6318 Decl *Param,
6319 SmallVectorImpl<TemplateArgument>
6320 &Converted,
6321 bool &HasDefaultArg);
6322
6323 /// \brief Specifies the context in which a particular template
6324 /// argument is being checked.
6325 enum CheckTemplateArgumentKind {
6326 /// \brief The template argument was specified in the code or was
6327 /// instantiated with some deduced template arguments.
6328 CTAK_Specified,
6329
6330 /// \brief The template argument was deduced via template argument
6331 /// deduction.
6332 CTAK_Deduced,
6333
6334 /// \brief The template argument was deduced from an array bound
6335 /// via template argument deduction.
6336 CTAK_DeducedFromArrayBound
6337 };
6338
6339 bool CheckTemplateArgument(NamedDecl *Param,
6340 TemplateArgumentLoc &Arg,
6341 NamedDecl *Template,
6342 SourceLocation TemplateLoc,
6343 SourceLocation RAngleLoc,
6344 unsigned ArgumentPackIndex,
6345 SmallVectorImpl<TemplateArgument> &Converted,
6346 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6347
6348 /// \brief Check that the given template arguments can be be provided to
6349 /// the given template, converting the arguments along the way.
6350 ///
6351 /// \param Template The template to which the template arguments are being
6352 /// provided.
6353 ///
6354 /// \param TemplateLoc The location of the template name in the source.
6355 ///
6356 /// \param TemplateArgs The list of template arguments. If the template is
6357 /// a template template parameter, this function may extend the set of
6358 /// template arguments to also include substituted, defaulted template
6359 /// arguments.
6360 ///
6361 /// \param PartialTemplateArgs True if the list of template arguments is
6362 /// intentionally partial, e.g., because we're checking just the initial
6363 /// set of template arguments.
6364 ///
6365 /// \param Converted Will receive the converted, canonicalized template
6366 /// arguments.
6367 ///
6368 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6369 /// contain the converted forms of the template arguments as written.
6370 /// Otherwise, \p TemplateArgs will not be modified.
6371 ///
6372 /// \returns true if an error occurred, false otherwise.
6373 bool CheckTemplateArgumentList(TemplateDecl *Template,
6374 SourceLocation TemplateLoc,
6375 TemplateArgumentListInfo &TemplateArgs,
6376 bool PartialTemplateArgs,
6377 SmallVectorImpl<TemplateArgument> &Converted,
6378 bool UpdateArgsWithConversions = true);
6379
6380 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6381 TemplateArgumentLoc &Arg,
6382 SmallVectorImpl<TemplateArgument> &Converted);
6383
6384 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6385 TypeSourceInfo *Arg);
6386 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6387 QualType InstantiatedParamType, Expr *Arg,
6388 TemplateArgument &Converted,
6389 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6390 bool CheckTemplateTemplateArgument(TemplateParameterList *Params,
6391 TemplateArgumentLoc &Arg);
6392
6393 ExprResult
6394 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6395 QualType ParamType,
6396 SourceLocation Loc);
6397 ExprResult
6398 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6399 SourceLocation Loc);
6400
6401 /// \brief Enumeration describing how template parameter lists are compared
6402 /// for equality.
6403 enum TemplateParameterListEqualKind {
6404 /// \brief We are matching the template parameter lists of two templates
6405 /// that might be redeclarations.
6406 ///
6407 /// \code
6408 /// template<typename T> struct X;
6409 /// template<typename T> struct X;
6410 /// \endcode
6411 TPL_TemplateMatch,
6412
6413 /// \brief We are matching the template parameter lists of two template
6414 /// template parameters as part of matching the template parameter lists
6415 /// of two templates that might be redeclarations.
6416 ///
6417 /// \code
6418 /// template<template<int I> class TT> struct X;
6419 /// template<template<int Value> class Other> struct X;
6420 /// \endcode
6421 TPL_TemplateTemplateParmMatch,
6422
6423 /// \brief We are matching the template parameter lists of a template
6424 /// template argument against the template parameter lists of a template
6425 /// template parameter.
6426 ///
6427 /// \code
6428 /// template<template<int Value> class Metafun> struct X;
6429 /// template<int Value> struct integer_c;
6430 /// X<integer_c> xic;
6431 /// \endcode
6432 TPL_TemplateTemplateArgumentMatch
6433 };
6434
6435 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6436 TemplateParameterList *Old,
6437 bool Complain,
6438 TemplateParameterListEqualKind Kind,
6439 SourceLocation TemplateArgLoc
6440 = SourceLocation());
6441
6442 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6443
6444 /// \brief Called when the parser has parsed a C++ typename
6445 /// specifier, e.g., "typename T::type".
6446 ///
6447 /// \param S The scope in which this typename type occurs.
6448 /// \param TypenameLoc the location of the 'typename' keyword
6449 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6450 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6451 /// \param IdLoc the location of the identifier.
6452 TypeResult
6453 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6454 const CXXScopeSpec &SS, const IdentifierInfo &II,
6455 SourceLocation IdLoc);
6456
6457 /// \brief Called when the parser has parsed a C++ typename
6458 /// specifier that ends in a template-id, e.g.,
6459 /// "typename MetaFun::template apply<T1, T2>".
6460 ///
6461 /// \param S The scope in which this typename type occurs.
6462 /// \param TypenameLoc the location of the 'typename' keyword
6463 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6464 /// \param TemplateLoc the location of the 'template' keyword, if any.
6465 /// \param TemplateName The template name.
6466 /// \param TemplateII The identifier used to name the template.
6467 /// \param TemplateIILoc The location of the template name.
6468 /// \param LAngleLoc The location of the opening angle bracket ('<').
6469 /// \param TemplateArgs The template arguments.
6470 /// \param RAngleLoc The location of the closing angle bracket ('>').
6471 TypeResult
6472 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6473 const CXXScopeSpec &SS,
6474 SourceLocation TemplateLoc,
6475 TemplateTy TemplateName,
6476 IdentifierInfo *TemplateII,
6477 SourceLocation TemplateIILoc,
6478 SourceLocation LAngleLoc,
6479 ASTTemplateArgsPtr TemplateArgs,
6480 SourceLocation RAngleLoc);
6481
6482 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6483 SourceLocation KeywordLoc,
6484 NestedNameSpecifierLoc QualifierLoc,
6485 const IdentifierInfo &II,
6486 SourceLocation IILoc);
6487
6488 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6489 SourceLocation Loc,
6490 DeclarationName Name);
6491 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6492
6493 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6494 bool RebuildTemplateParamsInCurrentInstantiation(
6495 TemplateParameterList *Params);
6496
6497 std::string
6498 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6499 const TemplateArgumentList &Args);
6500
6501 std::string
6502 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6503 const TemplateArgument *Args,
6504 unsigned NumArgs);
6505
6506 //===--------------------------------------------------------------------===//
6507 // C++ Variadic Templates (C++0x [temp.variadic])
6508 //===--------------------------------------------------------------------===//
6509
6510 /// Determine whether an unexpanded parameter pack might be permitted in this
6511 /// location. Useful for error recovery.
6512 bool isUnexpandedParameterPackPermitted();
6513
6514 /// \brief The context in which an unexpanded parameter pack is
6515 /// being diagnosed.
6516 ///
6517 /// Note that the values of this enumeration line up with the first
6518 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6519 enum UnexpandedParameterPackContext {
6520 /// \brief An arbitrary expression.
6521 UPPC_Expression = 0,
6522
6523 /// \brief The base type of a class type.
6524 UPPC_BaseType,
6525
6526 /// \brief The type of an arbitrary declaration.
6527 UPPC_DeclarationType,
6528
6529 /// \brief The type of a data member.
6530 UPPC_DataMemberType,
6531
6532 /// \brief The size of a bit-field.
6533 UPPC_BitFieldWidth,
6534
6535 /// \brief The expression in a static assertion.
6536 UPPC_StaticAssertExpression,
6537
6538 /// \brief The fixed underlying type of an enumeration.
6539 UPPC_FixedUnderlyingType,
6540
6541 /// \brief The enumerator value.
6542 UPPC_EnumeratorValue,
6543
6544 /// \brief A using declaration.
6545 UPPC_UsingDeclaration,
6546
6547 /// \brief A friend declaration.
6548 UPPC_FriendDeclaration,
6549
6550 /// \brief A declaration qualifier.
6551 UPPC_DeclarationQualifier,
6552
6553 /// \brief An initializer.
6554 UPPC_Initializer,
6555
6556 /// \brief A default argument.
6557 UPPC_DefaultArgument,
6558
6559 /// \brief The type of a non-type template parameter.
6560 UPPC_NonTypeTemplateParameterType,
6561
6562 /// \brief The type of an exception.
6563 UPPC_ExceptionType,
6564
6565 /// \brief Partial specialization.
6566 UPPC_PartialSpecialization,
6567
6568 /// \brief Microsoft __if_exists.
6569 UPPC_IfExists,
6570
6571 /// \brief Microsoft __if_not_exists.
6572 UPPC_IfNotExists,
6573
6574 /// \brief Lambda expression.
6575 UPPC_Lambda,
6576
6577 /// \brief Block expression,
6578 UPPC_Block
6579 };
6580
6581 /// \brief Diagnose unexpanded parameter packs.
6582 ///
6583 /// \param Loc The location at which we should emit the diagnostic.
6584 ///
6585 /// \param UPPC The context in which we are diagnosing unexpanded
6586 /// parameter packs.
6587 ///
6588 /// \param Unexpanded the set of unexpanded parameter packs.
6589 ///
6590 /// \returns true if an error occurred, false otherwise.
6591 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6592 UnexpandedParameterPackContext UPPC,
6593 ArrayRef<UnexpandedParameterPack> Unexpanded);
6594
6595 /// \brief If the given type contains an unexpanded parameter pack,
6596 /// diagnose the error.
6597 ///
6598 /// \param Loc The source location where a diagnostc should be emitted.
6599 ///
6600 /// \param T The type that is being checked for unexpanded parameter
6601 /// packs.
6602 ///
6603 /// \returns true if an error occurred, false otherwise.
6604 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6605 UnexpandedParameterPackContext UPPC);
6606
6607 /// \brief If the given expression contains an unexpanded parameter
6608 /// pack, diagnose the error.
6609 ///
6610 /// \param E The expression that is being checked for unexpanded
6611 /// parameter packs.
6612 ///
6613 /// \returns true if an error occurred, false otherwise.
6614 bool DiagnoseUnexpandedParameterPack(Expr *E,
6615 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6616
6617 /// \brief If the given nested-name-specifier contains an unexpanded
6618 /// parameter pack, diagnose the error.
6619 ///
6620 /// \param SS The nested-name-specifier that is being checked for
6621 /// unexpanded parameter packs.
6622 ///
6623 /// \returns true if an error occurred, false otherwise.
6624 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6625 UnexpandedParameterPackContext UPPC);
6626
6627 /// \brief If the given name contains an unexpanded parameter pack,
6628 /// diagnose the error.
6629 ///
6630 /// \param NameInfo The name (with source location information) that
6631 /// is being checked for unexpanded parameter packs.
6632 ///
6633 /// \returns true if an error occurred, false otherwise.
6634 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6635 UnexpandedParameterPackContext UPPC);
6636
6637 /// \brief If the given template name contains an unexpanded parameter pack,
6638 /// diagnose the error.
6639 ///
6640 /// \param Loc The location of the template name.
6641 ///
6642 /// \param Template The template name that is being checked for unexpanded
6643 /// parameter packs.
6644 ///
6645 /// \returns true if an error occurred, false otherwise.
6646 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6647 TemplateName Template,
6648 UnexpandedParameterPackContext UPPC);
6649
6650 /// \brief If the given template argument contains an unexpanded parameter
6651 /// pack, diagnose the error.
6652 ///
6653 /// \param Arg The template argument that is being checked for unexpanded
6654 /// parameter packs.
6655 ///
6656 /// \returns true if an error occurred, false otherwise.
6657 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6658 UnexpandedParameterPackContext UPPC);
6659
6660 /// \brief Collect the set of unexpanded parameter packs within the given
6661 /// template argument.
6662 ///
6663 /// \param Arg The template argument that will be traversed to find
6664 /// unexpanded parameter packs.
6665 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6666 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6667
6668 /// \brief Collect the set of unexpanded parameter packs within the given
6669 /// template argument.
6670 ///
6671 /// \param Arg The template argument that will be traversed to find
6672 /// unexpanded parameter packs.
6673 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6674 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6675
6676 /// \brief Collect the set of unexpanded parameter packs within the given
6677 /// type.
6678 ///
6679 /// \param T The type that will be traversed to find
6680 /// unexpanded parameter packs.
6681 void collectUnexpandedParameterPacks(QualType T,
6682 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6683
6684 /// \brief Collect the set of unexpanded parameter packs within the given
6685 /// type.
6686 ///
6687 /// \param TL The type that will be traversed to find
6688 /// unexpanded parameter packs.
6689 void collectUnexpandedParameterPacks(TypeLoc TL,
6690 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6691
6692 /// \brief Collect the set of unexpanded parameter packs within the given
6693 /// nested-name-specifier.
6694 ///
6695 /// \param NNS The nested-name-specifier that will be traversed to find
6696 /// unexpanded parameter packs.
6697 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6698 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6699
6700 /// \brief Collect the set of unexpanded parameter packs within the given
6701 /// name.
6702 ///
6703 /// \param NameInfo The name that will be traversed to find
6704 /// unexpanded parameter packs.
6705 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6706 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6707
6708 /// \brief Invoked when parsing a template argument followed by an
6709 /// ellipsis, which creates a pack expansion.
6710 ///
6711 /// \param Arg The template argument preceding the ellipsis, which
6712 /// may already be invalid.
6713 ///
6714 /// \param EllipsisLoc The location of the ellipsis.
6715 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6716 SourceLocation EllipsisLoc);
6717
6718 /// \brief Invoked when parsing a type followed by an ellipsis, which
6719 /// creates a pack expansion.
6720 ///
6721 /// \param Type The type preceding the ellipsis, which will become
6722 /// the pattern of the pack expansion.
6723 ///
6724 /// \param EllipsisLoc The location of the ellipsis.
6725 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6726
6727 /// \brief Construct a pack expansion type from the pattern of the pack
6728 /// expansion.
6729 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6730 SourceLocation EllipsisLoc,
6731 Optional<unsigned> NumExpansions);
6732
6733 /// \brief Construct a pack expansion type from the pattern of the pack
6734 /// expansion.
6735 QualType CheckPackExpansion(QualType Pattern,
6736 SourceRange PatternRange,
6737 SourceLocation EllipsisLoc,
6738 Optional<unsigned> NumExpansions);
6739
6740 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6741 /// creates a pack expansion.
6742 ///
6743 /// \param Pattern The expression preceding the ellipsis, which will become
6744 /// the pattern of the pack expansion.
6745 ///
6746 /// \param EllipsisLoc The location of the ellipsis.
6747 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6748
6749 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6750 /// creates a pack expansion.
6751 ///
6752 /// \param Pattern The expression preceding the ellipsis, which will become
6753 /// the pattern of the pack expansion.
6754 ///
6755 /// \param EllipsisLoc The location of the ellipsis.
6756 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6757 Optional<unsigned> NumExpansions);
6758
6759 /// \brief Determine whether we could expand a pack expansion with the
6760 /// given set of parameter packs into separate arguments by repeatedly
6761 /// transforming the pattern.
6762 ///
6763 /// \param EllipsisLoc The location of the ellipsis that identifies the
6764 /// pack expansion.
6765 ///
6766 /// \param PatternRange The source range that covers the entire pattern of
6767 /// the pack expansion.
6768 ///
6769 /// \param Unexpanded The set of unexpanded parameter packs within the
6770 /// pattern.
6771 ///
6772 /// \param ShouldExpand Will be set to \c true if the transformer should
6773 /// expand the corresponding pack expansions into separate arguments. When
6774 /// set, \c NumExpansions must also be set.
6775 ///
6776 /// \param RetainExpansion Whether the caller should add an unexpanded
6777 /// pack expansion after all of the expanded arguments. This is used
6778 /// when extending explicitly-specified template argument packs per
6779 /// C++0x [temp.arg.explicit]p9.
6780 ///
6781 /// \param NumExpansions The number of separate arguments that will be in
6782 /// the expanded form of the corresponding pack expansion. This is both an
6783 /// input and an output parameter, which can be set by the caller if the
6784 /// number of expansions is known a priori (e.g., due to a prior substitution)
6785 /// and will be set by the callee when the number of expansions is known.
6786 /// The callee must set this value when \c ShouldExpand is \c true; it may
6787 /// set this value in other cases.
6788 ///
6789 /// \returns true if an error occurred (e.g., because the parameter packs
6790 /// are to be instantiated with arguments of different lengths), false
6791 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6792 /// must be set.
6793 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6794 SourceRange PatternRange,
6795 ArrayRef<UnexpandedParameterPack> Unexpanded,
6796 const MultiLevelTemplateArgumentList &TemplateArgs,
6797 bool &ShouldExpand,
6798 bool &RetainExpansion,
6799 Optional<unsigned> &NumExpansions);
6800
6801 /// \brief Determine the number of arguments in the given pack expansion
6802 /// type.
6803 ///
6804 /// This routine assumes that the number of arguments in the expansion is
6805 /// consistent across all of the unexpanded parameter packs in its pattern.
6806 ///
6807 /// Returns an empty Optional if the type can't be expanded.
6808 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6809 const MultiLevelTemplateArgumentList &TemplateArgs);
6810
6811 /// \brief Determine whether the given declarator contains any unexpanded
6812 /// parameter packs.
6813 ///
6814 /// This routine is used by the parser to disambiguate function declarators
6815 /// with an ellipsis prior to the ')', e.g.,
6816 ///
6817 /// \code
6818 /// void f(T...);
6819 /// \endcode
6820 ///
6821 /// To determine whether we have an (unnamed) function parameter pack or
6822 /// a variadic function.
6823 ///
6824 /// \returns true if the declarator contains any unexpanded parameter packs,
6825 /// false otherwise.
6826 bool containsUnexpandedParameterPacks(Declarator &D);
6827
6828 /// \brief Returns the pattern of the pack expansion for a template argument.
6829 ///
6830 /// \param OrigLoc The template argument to expand.
6831 ///
6832 /// \param Ellipsis Will be set to the location of the ellipsis.
6833 ///
6834 /// \param NumExpansions Will be set to the number of expansions that will
6835 /// be generated from this pack expansion, if known a priori.
6836 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6837 TemplateArgumentLoc OrigLoc,
6838 SourceLocation &Ellipsis,
6839 Optional<unsigned> &NumExpansions) const;
6840
6841 /// Given a template argument that contains an unexpanded parameter pack, but
6842 /// which has already been substituted, attempt to determine the number of
6843 /// elements that will be produced once this argument is fully-expanded.
6844 ///
6845 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6846 /// avoid actually expanding the pack where possible.
6847 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6848
6849 //===--------------------------------------------------------------------===//
6850 // C++ Template Argument Deduction (C++ [temp.deduct])
6851 //===--------------------------------------------------------------------===//
6852
6853 /// Adjust the type \p ArgFunctionType to match the calling convention,
6854 /// noreturn, and optionally the exception specification of \p FunctionType.
6855 /// Deduction often wants to ignore these properties when matching function
6856 /// types.
6857 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6858 bool AdjustExceptionSpec = false);
6859
6860 /// \brief Describes the result of template argument deduction.
6861 ///
6862 /// The TemplateDeductionResult enumeration describes the result of
6863 /// template argument deduction, as returned from
6864 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6865 /// structure provides additional information about the results of
6866 /// template argument deduction, e.g., the deduced template argument
6867 /// list (if successful) or the specific template parameters or
6868 /// deduced arguments that were involved in the failure.
6869 enum TemplateDeductionResult {
6870 /// \brief Template argument deduction was successful.
6871 TDK_Success = 0,
6872 /// \brief The declaration was invalid; do nothing.
6873 TDK_Invalid,
6874 /// \brief Template argument deduction exceeded the maximum template
6875 /// instantiation depth (which has already been diagnosed).
6876 TDK_InstantiationDepth,
6877 /// \brief Template argument deduction did not deduce a value
6878 /// for every template parameter.
6879 TDK_Incomplete,
6880 /// \brief Template argument deduction produced inconsistent
6881 /// deduced values for the given template parameter.
6882 TDK_Inconsistent,
6883 /// \brief Template argument deduction failed due to inconsistent
6884 /// cv-qualifiers on a template parameter type that would
6885 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6886 /// but were given a non-const "X".
6887 TDK_Underqualified,
6888 /// \brief Substitution of the deduced template argument values
6889 /// resulted in an error.
6890 TDK_SubstitutionFailure,
6891 /// \brief After substituting deduced template arguments, a dependent
6892 /// parameter type did not match the corresponding argument.
6893 TDK_DeducedMismatch,
6894 /// \brief After substituting deduced template arguments, an element of
6895 /// a dependent parameter type did not match the corresponding element
6896 /// of the corresponding argument (when deducing from an initializer list).
6897 TDK_DeducedMismatchNested,
6898 /// \brief A non-depnedent component of the parameter did not match the
6899 /// corresponding component of the argument.
6900 TDK_NonDeducedMismatch,
6901 /// \brief When performing template argument deduction for a function
6902 /// template, there were too many call arguments.
6903 TDK_TooManyArguments,
6904 /// \brief When performing template argument deduction for a function
6905 /// template, there were too few call arguments.
6906 TDK_TooFewArguments,
6907 /// \brief The explicitly-specified template arguments were not valid
6908 /// template arguments for the given template.
6909 TDK_InvalidExplicitArguments,
6910 /// \brief Checking non-dependent argument conversions failed.
6911 TDK_NonDependentConversionFailure,
6912 /// \brief Deduction failed; that's all we know.
6913 TDK_MiscellaneousDeductionFailure,
6914 /// \brief CUDA Target attributes do not match.
6915 TDK_CUDATargetMismatch
6916 };
6917
6918 TemplateDeductionResult
6919 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6920 const TemplateArgumentList &TemplateArgs,
6921 sema::TemplateDeductionInfo &Info);
6922
6923 TemplateDeductionResult
6924 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6925 const TemplateArgumentList &TemplateArgs,
6926 sema::TemplateDeductionInfo &Info);
6927
6928 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6929 FunctionTemplateDecl *FunctionTemplate,
6930 TemplateArgumentListInfo &ExplicitTemplateArgs,
6931 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6932 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6933 sema::TemplateDeductionInfo &Info);
6934
6935 /// brief A function argument from which we performed template argument
6936 // deduction for a call.
6937 struct OriginalCallArg {
6938 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6939 unsigned ArgIdx, QualType OriginalArgType)
6940 : OriginalParamType(OriginalParamType),
6941 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6942 OriginalArgType(OriginalArgType) {}
6943
6944 QualType OriginalParamType;
6945 bool DecomposedParam;
6946 unsigned ArgIdx;
6947 QualType OriginalArgType;
6948 };
6949
6950 TemplateDeductionResult FinishTemplateArgumentDeduction(
6951 FunctionTemplateDecl *FunctionTemplate,
6952 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6953 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6954 sema::TemplateDeductionInfo &Info,
6955 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6956 bool PartialOverloading = false,
6957 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6958
6959 TemplateDeductionResult DeduceTemplateArguments(
6960 FunctionTemplateDecl *FunctionTemplate,
6961 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6962 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6963 bool PartialOverloading,
6964 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6965
6966 TemplateDeductionResult
6967 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6968 TemplateArgumentListInfo *ExplicitTemplateArgs,
6969 QualType ArgFunctionType,
6970 FunctionDecl *&Specialization,
6971 sema::TemplateDeductionInfo &Info,
6972 bool IsAddressOfFunction = false);
6973
6974 TemplateDeductionResult
6975 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6976 QualType ToType,
6977 CXXConversionDecl *&Specialization,
6978 sema::TemplateDeductionInfo &Info);
6979
6980 TemplateDeductionResult
6981 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6982 TemplateArgumentListInfo *ExplicitTemplateArgs,
6983 FunctionDecl *&Specialization,
6984 sema::TemplateDeductionInfo &Info,
6985 bool IsAddressOfFunction = false);
6986
6987 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6988 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6989 /// \brief Substitute Replacement for auto in TypeWithAuto
6990 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6991 QualType Replacement);
6992 /// \brief Completely replace the \c auto in \p TypeWithAuto by
6993 /// \p Replacement. This does not retain any \c auto type sugar.
6994 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6995
6996 /// \brief Result type of DeduceAutoType.
6997 enum DeduceAutoResult {
6998 DAR_Succeeded,
6999 DAR_Failed,
7000 DAR_FailedAlreadyDiagnosed
7001 };
7002
7003 DeduceAutoResult
7004 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
7005 Optional<unsigned> DependentDeductionDepth = None);
7006 DeduceAutoResult
7007 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
7008 Optional<unsigned> DependentDeductionDepth = None);
7009 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
7010 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
7011 bool Diagnose = true);
7012
7013 /// \brief Declare implicit deduction guides for a class template if we've
7014 /// not already done so.
7015 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
7016 SourceLocation Loc);
7017
7018 QualType DeduceTemplateSpecializationFromInitializer(
7019 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
7020 const InitializationKind &Kind, MultiExprArg Init);
7021
7022 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
7023 QualType Type, TypeSourceInfo *TSI,
7024 SourceRange Range, bool DirectInit,
7025 Expr *Init);
7026
7027 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
7028
7029 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
7030 SourceLocation ReturnLoc,
7031 Expr *&RetExpr, AutoType *AT);
7032
7033 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
7034 FunctionTemplateDecl *FT2,
7035 SourceLocation Loc,
7036 TemplatePartialOrderingContext TPOC,
7037 unsigned NumCallArguments1,
7038 unsigned NumCallArguments2);
7039 UnresolvedSetIterator
7040 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
7041 TemplateSpecCandidateSet &FailedCandidates,
7042 SourceLocation Loc,
7043 const PartialDiagnostic &NoneDiag,
7044 const PartialDiagnostic &AmbigDiag,
7045 const PartialDiagnostic &CandidateDiag,
7046 bool Complain = true, QualType TargetType = QualType());
7047
7048 ClassTemplatePartialSpecializationDecl *
7049 getMoreSpecializedPartialSpecialization(
7050 ClassTemplatePartialSpecializationDecl *PS1,
7051 ClassTemplatePartialSpecializationDecl *PS2,
7052 SourceLocation Loc);
7053
7054 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
7055 sema::TemplateDeductionInfo &Info);
7056
7057 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
7058 VarTemplatePartialSpecializationDecl *PS1,
7059 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
7060
7061 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
7062 sema::TemplateDeductionInfo &Info);
7063
7064 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
7065 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
7066
7067 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
7068 bool OnlyDeduced,
7069 unsigned Depth,
7070 llvm::SmallBitVector &Used);
7071 void MarkDeducedTemplateParameters(
7072 const FunctionTemplateDecl *FunctionTemplate,
7073 llvm::SmallBitVector &Deduced) {
7074 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
7075 }
7076 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
7077 const FunctionTemplateDecl *FunctionTemplate,
7078 llvm::SmallBitVector &Deduced);
7079
7080 //===--------------------------------------------------------------------===//
7081 // C++ Template Instantiation
7082 //
7083
7084 MultiLevelTemplateArgumentList
7085 getTemplateInstantiationArgs(NamedDecl *D,
7086 const TemplateArgumentList *Innermost = nullptr,
7087 bool RelativeToPrimary = false,
7088 const FunctionDecl *Pattern = nullptr);
7089
7090 /// A context in which code is being synthesized (where a source location
7091 /// alone is not sufficient to identify the context). This covers template
7092 /// instantiation and various forms of implicitly-generated functions.
7093 struct CodeSynthesisContext {
7094 /// \brief The kind of template instantiation we are performing
7095 enum SynthesisKind {
7096 /// We are instantiating a template declaration. The entity is
7097 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
7098 TemplateInstantiation,
7099
7100 /// We are instantiating a default argument for a template
7101 /// parameter. The Entity is the template parameter whose argument is
7102 /// being instantiated, the Template is the template, and the
7103 /// TemplateArgs/NumTemplateArguments provide the template arguments as
7104 /// specified.
7105 DefaultTemplateArgumentInstantiation,
7106
7107 /// We are instantiating a default argument for a function.
7108 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
7109 /// provides the template arguments as specified.
7110 DefaultFunctionArgumentInstantiation,
7111
7112 /// We are substituting explicit template arguments provided for
7113 /// a function template. The entity is a FunctionTemplateDecl.
7114 ExplicitTemplateArgumentSubstitution,
7115
7116 /// We are substituting template argument determined as part of
7117 /// template argument deduction for either a class template
7118 /// partial specialization or a function template. The
7119 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
7120 /// a TemplateDecl.
7121 DeducedTemplateArgumentSubstitution,
7122
7123 /// We are substituting prior template arguments into a new
7124 /// template parameter. The template parameter itself is either a
7125 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
7126 PriorTemplateArgumentSubstitution,
7127
7128 /// We are checking the validity of a default template argument that
7129 /// has been used when naming a template-id.
7130 DefaultTemplateArgumentChecking,
7131
7132 /// We are instantiating the exception specification for a function
7133 /// template which was deferred until it was needed.
7134 ExceptionSpecInstantiation,
7135
7136 /// We are declaring an implicit special member function.
7137 DeclaringSpecialMember,
7138
7139 /// We are defining a synthesized function (such as a defaulted special
7140 /// member).
7141 DefiningSynthesizedFunction,
7142
7143 /// Added for Template instantiation observation.
7144 /// Memoization means we are _not_ instantiating a template because
7145 /// it is already instantiated (but we entered a context where we
7146 /// would have had to if it was not already instantiated).
7147 Memoization
7148 } Kind;
7149
7150 /// \brief Was the enclosing context a non-instantiation SFINAE context?
7151 bool SavedInNonInstantiationSFINAEContext;
7152
7153 /// \brief The point of instantiation or synthesis within the source code.
7154 SourceLocation PointOfInstantiation;
7155
7156 /// \brief The entity that is being synthesized.
7157 Decl *Entity;
7158
7159 /// \brief The template (or partial specialization) in which we are
7160 /// performing the instantiation, for substitutions of prior template
7161 /// arguments.
7162 NamedDecl *Template;
7163
7164 /// \brief The list of template arguments we are substituting, if they
7165 /// are not part of the entity.
7166 const TemplateArgument *TemplateArgs;
7167
7168 // FIXME: Wrap this union around more members, or perhaps store the
7169 // kind-specific members in the RAII object owning the context.
7170 union {
7171 /// \brief The number of template arguments in TemplateArgs.
7172 unsigned NumTemplateArgs;
7173
7174 /// \brief The special member being declared or defined.
7175 CXXSpecialMember SpecialMember;
7176 };
7177
7178 ArrayRef<TemplateArgument> template_arguments() const {
7179 assert(Kind != DeclaringSpecialMember)(static_cast <bool> (Kind != DeclaringSpecialMember) ? void
(0) : __assert_fail ("Kind != DeclaringSpecialMember", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 7179, __extension__ __PRETTY_FUNCTION__))
;
7180 return {TemplateArgs, NumTemplateArgs};
7181 }
7182
7183 /// \brief The template deduction info object associated with the
7184 /// substitution or checking of explicit or deduced template arguments.
7185 sema::TemplateDeductionInfo *DeductionInfo;
7186
7187 /// \brief The source range that covers the construct that cause
7188 /// the instantiation, e.g., the template-id that causes a class
7189 /// template instantiation.
7190 SourceRange InstantiationRange;
7191
7192 CodeSynthesisContext()
7193 : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
7194 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
7195
7196 /// \brief Determines whether this template is an actual instantiation
7197 /// that should be counted toward the maximum instantiation depth.
7198 bool isInstantiationRecord() const;
7199 };
7200
7201 /// \brief List of active code synthesis contexts.
7202 ///
7203 /// This vector is treated as a stack. As synthesis of one entity requires
7204 /// synthesis of another, additional contexts are pushed onto the stack.
7205 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
7206
7207 /// Specializations whose definitions are currently being instantiated.
7208 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7209
7210 /// Non-dependent types used in templates that have already been instantiated
7211 /// by some template instantiation.
7212 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7213
7214 /// \brief Extra modules inspected when performing a lookup during a template
7215 /// instantiation. Computed lazily.
7216 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7217
7218 /// \brief Cache of additional modules that should be used for name lookup
7219 /// within the current template instantiation. Computed lazily; use
7220 /// getLookupModules() to get a complete set.
7221 llvm::DenseSet<Module*> LookupModulesCache;
7222
7223 /// \brief Get the set of additional modules that should be checked during
7224 /// name lookup. A module and its imports become visible when instanting a
7225 /// template defined within it.
7226 llvm::DenseSet<Module*> &getLookupModules();
7227
7228 /// \brief Map from the most recent declaration of a namespace to the most
7229 /// recent visible declaration of that namespace.
7230 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7231
7232 /// \brief Whether we are in a SFINAE context that is not associated with
7233 /// template instantiation.
7234 ///
7235 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7236 /// of a template instantiation or template argument deduction.
7237 bool InNonInstantiationSFINAEContext;
7238
7239 /// \brief The number of \p CodeSynthesisContexts that are not template
7240 /// instantiations and, therefore, should not be counted as part of the
7241 /// instantiation depth.
7242 ///
7243 /// When the instantiation depth reaches the user-configurable limit
7244 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7245 // FIXME: Should we have a similar limit for other forms of synthesis?
7246 unsigned NonInstantiationEntries;
7247
7248 /// \brief The depth of the context stack at the point when the most recent
7249 /// error or warning was produced.
7250 ///
7251 /// This value is used to suppress printing of redundant context stacks
7252 /// when there are multiple errors or warnings in the same instantiation.
7253 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7254 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7255
7256 /// \brief The template instantiation callbacks to trace or track
7257 /// instantiations (objects can be chained).
7258 ///
7259 /// This callbacks is used to print, trace or track template
7260 /// instantiations as they are being constructed.
7261 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
7262 TemplateInstCallbacks;
7263
7264 /// \brief The current index into pack expansion arguments that will be
7265 /// used for substitution of parameter packs.
7266 ///
7267 /// The pack expansion index will be -1 to indicate that parameter packs
7268 /// should be instantiated as themselves. Otherwise, the index specifies
7269 /// which argument within the parameter pack will be used for substitution.
7270 int ArgumentPackSubstitutionIndex;
7271
7272 /// \brief RAII object used to change the argument pack substitution index
7273 /// within a \c Sema object.
7274 ///
7275 /// See \c ArgumentPackSubstitutionIndex for more information.
7276 class ArgumentPackSubstitutionIndexRAII {
7277 Sema &Self;
7278 int OldSubstitutionIndex;
7279
7280 public:
7281 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7282 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7283 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7284 }
7285
7286 ~ArgumentPackSubstitutionIndexRAII() {
7287 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7288 }
7289 };
7290
7291 friend class ArgumentPackSubstitutionRAII;
7292
7293 /// \brief For each declaration that involved template argument deduction, the
7294 /// set of diagnostics that were suppressed during that template argument
7295 /// deduction.
7296 ///
7297 /// FIXME: Serialize this structure to the AST file.
7298 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7299 SuppressedDiagnosticsMap;
7300 SuppressedDiagnosticsMap SuppressedDiagnostics;
7301
7302 /// \brief A stack object to be created when performing template
7303 /// instantiation.
7304 ///
7305 /// Construction of an object of type \c InstantiatingTemplate
7306 /// pushes the current instantiation onto the stack of active
7307 /// instantiations. If the size of this stack exceeds the maximum
7308 /// number of recursive template instantiations, construction
7309 /// produces an error and evaluates true.
7310 ///
7311 /// Destruction of this object will pop the named instantiation off
7312 /// the stack.
7313 struct InstantiatingTemplate {
7314 /// \brief Note that we are instantiating a class template,
7315 /// function template, variable template, alias template,
7316 /// or a member thereof.
7317 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7318 Decl *Entity,
7319 SourceRange InstantiationRange = SourceRange());
7320
7321 struct ExceptionSpecification {};
7322 /// \brief Note that we are instantiating an exception specification
7323 /// of a function template.
7324 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7325 FunctionDecl *Entity, ExceptionSpecification,
7326 SourceRange InstantiationRange = SourceRange());
7327
7328 /// \brief Note that we are instantiating a default argument in a
7329 /// template-id.
7330 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7331 TemplateParameter Param, TemplateDecl *Template,
7332 ArrayRef<TemplateArgument> TemplateArgs,
7333 SourceRange InstantiationRange = SourceRange());
7334
7335 /// \brief Note that we are substituting either explicitly-specified or
7336 /// deduced template arguments during function template argument deduction.
7337 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7338 FunctionTemplateDecl *FunctionTemplate,
7339 ArrayRef<TemplateArgument> TemplateArgs,
7340 CodeSynthesisContext::SynthesisKind Kind,
7341 sema::TemplateDeductionInfo &DeductionInfo,
7342 SourceRange InstantiationRange = SourceRange());
7343
7344 /// \brief Note that we are instantiating as part of template
7345 /// argument deduction for a class template declaration.
7346 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7347 TemplateDecl *Template,
7348 ArrayRef<TemplateArgument> TemplateArgs,
7349 sema::TemplateDeductionInfo &DeductionInfo,
7350 SourceRange InstantiationRange = SourceRange());
7351
7352 /// \brief Note that we are instantiating as part of template
7353 /// argument deduction for a class template partial
7354 /// specialization.
7355 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7356 ClassTemplatePartialSpecializationDecl *PartialSpec,
7357 ArrayRef<TemplateArgument> TemplateArgs,
7358 sema::TemplateDeductionInfo &DeductionInfo,
7359 SourceRange InstantiationRange = SourceRange());
7360
7361 /// \brief Note that we are instantiating as part of template
7362 /// argument deduction for a variable template partial
7363 /// specialization.
7364 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7365 VarTemplatePartialSpecializationDecl *PartialSpec,
7366 ArrayRef<TemplateArgument> TemplateArgs,
7367 sema::TemplateDeductionInfo &DeductionInfo,
7368 SourceRange InstantiationRange = SourceRange());
7369
7370 /// \brief Note that we are instantiating a default argument for a function
7371 /// parameter.
7372 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7373 ParmVarDecl *Param,
7374 ArrayRef<TemplateArgument> TemplateArgs,
7375 SourceRange InstantiationRange = SourceRange());
7376
7377 /// \brief Note that we are substituting prior template arguments into a
7378 /// non-type parameter.
7379 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7380 NamedDecl *Template,
7381 NonTypeTemplateParmDecl *Param,
7382 ArrayRef<TemplateArgument> TemplateArgs,
7383 SourceRange InstantiationRange);
7384
7385 /// \brief Note that we are substituting prior template arguments into a
7386 /// template template parameter.
7387 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7388 NamedDecl *Template,
7389 TemplateTemplateParmDecl *Param,
7390 ArrayRef<TemplateArgument> TemplateArgs,
7391 SourceRange InstantiationRange);
7392
7393 /// \brief Note that we are checking the default template argument
7394 /// against the template parameter for a given template-id.
7395 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7396 TemplateDecl *Template,
7397 NamedDecl *Param,
7398 ArrayRef<TemplateArgument> TemplateArgs,
7399 SourceRange InstantiationRange);
7400
7401
7402 /// \brief Note that we have finished instantiating this template.
7403 void Clear();
7404
7405 ~InstantiatingTemplate() { Clear(); }
7406
7407 /// \brief Determines whether we have exceeded the maximum
7408 /// recursive template instantiations.
7409 bool isInvalid() const { return Invalid; }
7410
7411 /// \brief Determine whether we are already instantiating this
7412 /// specialization in some surrounding active instantiation.
7413 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7414
7415 private:
7416 Sema &SemaRef;
7417 bool Invalid;
7418 bool AlreadyInstantiating;
7419 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7420 SourceRange InstantiationRange);
7421
7422 InstantiatingTemplate(
7423 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7424 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7425 Decl *Entity, NamedDecl *Template = nullptr,
7426 ArrayRef<TemplateArgument> TemplateArgs = None,
7427 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7428
7429 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7430
7431 InstantiatingTemplate&
7432 operator=(const InstantiatingTemplate&) = delete;
7433 };
7434
7435 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7436 void popCodeSynthesisContext();
7437
7438 /// Determine whether we are currently performing template instantiation.
7439 bool inTemplateInstantiation() const {
7440 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7441 }
7442
7443 void PrintContextStack() {
7444 if (!CodeSynthesisContexts.empty() &&
7445 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7446 PrintInstantiationStack();
7447 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7448 }
7449 if (PragmaAttributeCurrentTargetDecl)
7450 PrintPragmaAttributeInstantiationPoint();
7451 }
7452 void PrintInstantiationStack();
7453
7454 void PrintPragmaAttributeInstantiationPoint();
7455
7456 /// \brief Determines whether we are currently in a context where
7457 /// template argument substitution failures are not considered
7458 /// errors.
7459 ///
7460 /// \returns An empty \c Optional if we're not in a SFINAE context.
7461 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7462 /// template-deduction context object, which can be used to capture
7463 /// diagnostics that will be suppressed.
7464 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7465
7466 /// \brief Determines whether we are currently in a context that
7467 /// is not evaluated as per C++ [expr] p5.
7468 bool isUnevaluatedContext() const {
7469 assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 7470, __extension__ __PRETTY_FUNCTION__))
7470 "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 7470, __extension__ __PRETTY_FUNCTION__))
;
7471 return ExprEvalContexts.back().isUnevaluated();
7472 }
7473
7474 /// \brief RAII class used to determine whether SFINAE has
7475 /// trapped any errors that occur during template argument
7476 /// deduction.
7477 class SFINAETrap {
7478 Sema &SemaRef;
7479 unsigned PrevSFINAEErrors;
7480 bool PrevInNonInstantiationSFINAEContext;
7481 bool PrevAccessCheckingSFINAE;
7482 bool PrevLastDiagnosticIgnored;
7483
7484 public:
7485 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7486 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7487 PrevInNonInstantiationSFINAEContext(
7488 SemaRef.InNonInstantiationSFINAEContext),
7489 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
7490 PrevLastDiagnosticIgnored(
7491 SemaRef.getDiagnostics().isLastDiagnosticIgnored())
7492 {
7493 if (!SemaRef.isSFINAEContext())
7494 SemaRef.InNonInstantiationSFINAEContext = true;
7495 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7496 }
7497
7498 ~SFINAETrap() {
7499 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7500 SemaRef.InNonInstantiationSFINAEContext
7501 = PrevInNonInstantiationSFINAEContext;
7502 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7503 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
7504 PrevLastDiagnosticIgnored);
7505 }
7506
7507 /// \brief Determine whether any SFINAE errors have been trapped.
7508 bool hasErrorOccurred() const {
7509 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7510 }
7511 };
7512
7513 /// \brief RAII class used to indicate that we are performing provisional
7514 /// semantic analysis to determine the validity of a construct, so
7515 /// typo-correction and diagnostics in the immediate context (not within
7516 /// implicitly-instantiated templates) should be suppressed.
7517 class TentativeAnalysisScope {
7518 Sema &SemaRef;
7519 // FIXME: Using a SFINAETrap for this is a hack.
7520 SFINAETrap Trap;
7521 bool PrevDisableTypoCorrection;
7522 public:
7523 explicit TentativeAnalysisScope(Sema &SemaRef)
7524 : SemaRef(SemaRef), Trap(SemaRef, true),
7525 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7526 SemaRef.DisableTypoCorrection = true;
7527 }
7528 ~TentativeAnalysisScope() {
7529 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7530 }
7531 };
7532
7533 /// \brief The current instantiation scope used to store local
7534 /// variables.
7535 LocalInstantiationScope *CurrentInstantiationScope;
7536
7537 /// \brief Tracks whether we are in a context where typo correction is
7538 /// disabled.
7539 bool DisableTypoCorrection;
7540
7541 /// \brief The number of typos corrected by CorrectTypo.
7542 unsigned TyposCorrected;
7543
7544 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7545 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7546
7547 /// \brief A cache containing identifiers for which typo correction failed and
7548 /// their locations, so that repeated attempts to correct an identifier in a
7549 /// given location are ignored if typo correction already failed for it.
7550 IdentifierSourceLocations TypoCorrectionFailures;
7551
7552 /// \brief Worker object for performing CFG-based warnings.
7553 sema::AnalysisBasedWarnings AnalysisWarnings;
7554 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7555
7556 /// \brief An entity for which implicit template instantiation is required.
7557 ///
7558 /// The source location associated with the declaration is the first place in
7559 /// the source code where the declaration was "used". It is not necessarily
7560 /// the point of instantiation (which will be either before or after the
7561 /// namespace-scope declaration that triggered this implicit instantiation),
7562 /// However, it is the location that diagnostics should generally refer to,
7563 /// because users will need to know what code triggered the instantiation.
7564 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7565
7566 /// \brief The queue of implicit template instantiations that are required
7567 /// but have not yet been performed.
7568 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7569
7570 /// Queue of implicit template instantiations that cannot be performed
7571 /// eagerly.
7572 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
7573
7574 class GlobalEagerInstantiationScope {
7575 public:
7576 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
7577 : S(S), Enabled(Enabled) {
7578 if (!Enabled) return;
7579
7580 SavedPendingInstantiations.swap(S.PendingInstantiations);
7581 SavedVTableUses.swap(S.VTableUses);
7582 }
7583
7584 void perform() {
7585 if (Enabled) {
7586 S.DefineUsedVTables();
7587 S.PerformPendingInstantiations();
7588 }
7589 }
7590
7591 ~GlobalEagerInstantiationScope() {
7592 if (!Enabled) return;
7593
7594 // Restore the set of pending vtables.
7595 assert(S.VTableUses.empty() &&(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 7596, __extension__ __PRETTY_FUNCTION__))
7596 "VTableUses should be empty before it is discarded.")(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 7596, __extension__ __PRETTY_FUNCTION__))
;
7597 S.VTableUses.swap(SavedVTableUses);
7598
7599 // Restore the set of pending implicit instantiations.
7600 assert(S.PendingInstantiations.empty() &&(static_cast <bool> (S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 7601, __extension__ __PRETTY_FUNCTION__))
7601 "PendingInstantiations should be empty before it is discarded.")(static_cast <bool> (S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 7601, __extension__ __PRETTY_FUNCTION__))
;
7602 S.PendingInstantiations.swap(SavedPendingInstantiations);
7603 }
7604
7605 private:
7606 Sema &S;
7607 SmallVector<VTableUse, 16> SavedVTableUses;
7608 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7609 bool Enabled;
7610 };
7611
7612 /// \brief The queue of implicit template instantiations that are required
7613 /// and must be performed within the current local scope.
7614 ///
7615 /// This queue is only used for member functions of local classes in
7616 /// templates, which must be instantiated in the same scope as their
7617 /// enclosing function, so that they can reference function-local
7618 /// types, static variables, enumerators, etc.
7619 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7620
7621 class LocalEagerInstantiationScope {
7622 public:
7623 LocalEagerInstantiationScope(Sema &S) : S(S) {
7624 SavedPendingLocalImplicitInstantiations.swap(
7625 S.PendingLocalImplicitInstantiations);
7626 }
7627
7628 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
7629
7630 ~LocalEagerInstantiationScope() {
7631 assert(S.PendingLocalImplicitInstantiations.empty() &&(static_cast <bool> (S.PendingLocalImplicitInstantiations
.empty() && "there shouldn't be any pending local implicit instantiations"
) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 7632, __extension__ __PRETTY_FUNCTION__))
7632 "there shouldn't be any pending local implicit instantiations")(static_cast <bool> (S.PendingLocalImplicitInstantiations
.empty() && "there shouldn't be any pending local implicit instantiations"
) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 7632, __extension__ __PRETTY_FUNCTION__))
;
7633 SavedPendingLocalImplicitInstantiations.swap(
7634 S.PendingLocalImplicitInstantiations);
7635 }
7636
7637 private:
7638 Sema &S;
7639 std::deque<PendingImplicitInstantiation>
7640 SavedPendingLocalImplicitInstantiations;
7641 };
7642
7643 /// A helper class for building up ExtParameterInfos.
7644 class ExtParameterInfoBuilder {
7645 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7646 bool HasInteresting = false;
7647
7648 public:
7649 /// Set the ExtParameterInfo for the parameter at the given index,
7650 ///
7651 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7652 assert(Infos.size() <= index)(static_cast <bool> (Infos.size() <= index) ? void (
0) : __assert_fail ("Infos.size() <= index", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 7652, __extension__ __PRETTY_FUNCTION__))
;
7653 Infos.resize(index);
7654 Infos.push_back(info);
7655
7656 if (!HasInteresting)
7657 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7658 }
7659
7660 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7661 /// ExtParameterInfo array we've built up.
7662 const FunctionProtoType::ExtParameterInfo *
7663 getPointerOrNull(unsigned numParams) {
7664 if (!HasInteresting) return nullptr;
7665 Infos.resize(numParams);
7666 return Infos.data();
7667 }
7668 };
7669
7670 void PerformPendingInstantiations(bool LocalOnly = false);
7671
7672 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7673 const MultiLevelTemplateArgumentList &TemplateArgs,
7674 SourceLocation Loc, DeclarationName Entity,
7675 bool AllowDeducedTST = false);
7676
7677 QualType SubstType(QualType T,
7678 const MultiLevelTemplateArgumentList &TemplateArgs,
7679 SourceLocation Loc, DeclarationName Entity);
7680
7681 TypeSourceInfo *SubstType(TypeLoc TL,
7682 const MultiLevelTemplateArgumentList &TemplateArgs,
7683 SourceLocation Loc, DeclarationName Entity);
7684
7685 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7686 const MultiLevelTemplateArgumentList &TemplateArgs,
7687 SourceLocation Loc,
7688 DeclarationName Entity,
7689 CXXRecordDecl *ThisContext,
7690 unsigned ThisTypeQuals);
7691 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7692 const MultiLevelTemplateArgumentList &Args);
7693 bool SubstExceptionSpec(SourceLocation Loc,
7694 FunctionProtoType::ExceptionSpecInfo &ESI,
7695 SmallVectorImpl<QualType> &ExceptionStorage,
7696 const MultiLevelTemplateArgumentList &Args);
7697 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7698 const MultiLevelTemplateArgumentList &TemplateArgs,
7699 int indexAdjustment,
7700 Optional<unsigned> NumExpansions,
7701 bool ExpectParameterPack);
7702 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7703 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7704 const MultiLevelTemplateArgumentList &TemplateArgs,
7705 SmallVectorImpl<QualType> &ParamTypes,
7706 SmallVectorImpl<ParmVarDecl *> *OutParams,
7707 ExtParameterInfoBuilder &ParamInfos);
7708 ExprResult SubstExpr(Expr *E,
7709 const MultiLevelTemplateArgumentList &TemplateArgs);
7710
7711 /// \brief Substitute the given template arguments into a list of
7712 /// expressions, expanding pack expansions if required.
7713 ///
7714 /// \param Exprs The list of expressions to substitute into.
7715 ///
7716 /// \param IsCall Whether this is some form of call, in which case
7717 /// default arguments will be dropped.
7718 ///
7719 /// \param TemplateArgs The set of template arguments to substitute.
7720 ///
7721 /// \param Outputs Will receive all of the substituted arguments.
7722 ///
7723 /// \returns true if an error occurred, false otherwise.
7724 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7725 const MultiLevelTemplateArgumentList &TemplateArgs,
7726 SmallVectorImpl<Expr *> &Outputs);
7727
7728 StmtResult SubstStmt(Stmt *S,
7729 const MultiLevelTemplateArgumentList &TemplateArgs);
7730
7731 TemplateParameterList *
7732 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
7733 const MultiLevelTemplateArgumentList &TemplateArgs);
7734
7735 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7736 const MultiLevelTemplateArgumentList &TemplateArgs);
7737
7738 ExprResult SubstInitializer(Expr *E,
7739 const MultiLevelTemplateArgumentList &TemplateArgs,
7740 bool CXXDirectInit);
7741
7742 bool
7743 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7744 CXXRecordDecl *Pattern,
7745 const MultiLevelTemplateArgumentList &TemplateArgs);
7746
7747 bool
7748 InstantiateClass(SourceLocation PointOfInstantiation,
7749 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7750 const MultiLevelTemplateArgumentList &TemplateArgs,
7751 TemplateSpecializationKind TSK,
7752 bool Complain = true);
7753
7754 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7755 EnumDecl *Instantiation, EnumDecl *Pattern,
7756 const MultiLevelTemplateArgumentList &TemplateArgs,
7757 TemplateSpecializationKind TSK);
7758
7759 bool InstantiateInClassInitializer(
7760 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7761 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7762
7763 struct LateInstantiatedAttribute {
7764 const Attr *TmplAttr;
7765 LocalInstantiationScope *Scope;
7766 Decl *NewDecl;
7767
7768 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7769 Decl *D)
7770 : TmplAttr(A), Scope(S), NewDecl(D)
7771 { }
7772 };
7773 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7774
7775 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7776 const Decl *Pattern, Decl *Inst,
7777 LateInstantiatedAttrVec *LateAttrs = nullptr,
7778 LocalInstantiationScope *OuterMostScope = nullptr);
7779
7780 void
7781 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7782 const Decl *Pattern, Decl *Inst,
7783 LateInstantiatedAttrVec *LateAttrs = nullptr,
7784 LocalInstantiationScope *OuterMostScope = nullptr);
7785
7786 bool usesPartialOrExplicitSpecialization(
7787 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
7788
7789 bool
7790 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7791 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7792 TemplateSpecializationKind TSK,
7793 bool Complain = true);
7794
7795 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7796 CXXRecordDecl *Instantiation,
7797 const MultiLevelTemplateArgumentList &TemplateArgs,
7798 TemplateSpecializationKind TSK);
7799
7800 void InstantiateClassTemplateSpecializationMembers(
7801 SourceLocation PointOfInstantiation,
7802 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7803 TemplateSpecializationKind TSK);
7804
7805 NestedNameSpecifierLoc
7806 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7807 const MultiLevelTemplateArgumentList &TemplateArgs);
7808
7809 DeclarationNameInfo
7810 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7811 const MultiLevelTemplateArgumentList &TemplateArgs);
7812 TemplateName
7813 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7814 SourceLocation Loc,
7815 const MultiLevelTemplateArgumentList &TemplateArgs);
7816 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7817 TemplateArgumentListInfo &Result,
7818 const MultiLevelTemplateArgumentList &TemplateArgs);
7819
7820 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7821 FunctionDecl *Function);
7822 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
7823 const TemplateArgumentList *Args,
7824 SourceLocation Loc);
7825 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7826 FunctionDecl *Function,
7827 bool Recursive = false,
7828 bool DefinitionRequired = false,
7829 bool AtEndOfTU = false);
7830 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7831 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7832 const TemplateArgumentList &TemplateArgList,
7833 const TemplateArgumentListInfo &TemplateArgsInfo,
7834 SmallVectorImpl<TemplateArgument> &Converted,
7835 SourceLocation PointOfInstantiation, void *InsertPos,
7836 LateInstantiatedAttrVec *LateAttrs = nullptr,
7837 LocalInstantiationScope *StartingScope = nullptr);
7838 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7839 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7840 const MultiLevelTemplateArgumentList &TemplateArgs);
7841 void
7842 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7843 const MultiLevelTemplateArgumentList &TemplateArgs,
7844 LateInstantiatedAttrVec *LateAttrs,
7845 DeclContext *Owner,
7846 LocalInstantiationScope *StartingScope,
7847 bool InstantiatingVarTemplate = false);
7848 void InstantiateVariableInitializer(
7849 VarDecl *Var, VarDecl *OldVar,
7850 const MultiLevelTemplateArgumentList &TemplateArgs);
7851 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7852 VarDecl *Var, bool Recursive = false,
7853 bool DefinitionRequired = false,
7854 bool AtEndOfTU = false);
7855
7856 void InstantiateMemInitializers(CXXConstructorDecl *New,
7857 const CXXConstructorDecl *Tmpl,
7858 const MultiLevelTemplateArgumentList &TemplateArgs);
7859
7860 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7861 const MultiLevelTemplateArgumentList &TemplateArgs,
7862 bool FindingInstantiatedContext = false);
7863 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7864 const MultiLevelTemplateArgumentList &TemplateArgs);
7865
7866 // Objective-C declarations.
7867 enum ObjCContainerKind {
7868 OCK_None = -1,
7869 OCK_Interface = 0,
7870 OCK_Protocol,
7871 OCK_Category,
7872 OCK_ClassExtension,
7873 OCK_Implementation,
7874 OCK_CategoryImplementation
7875 };
7876 ObjCContainerKind getObjCContainerKind() const;
7877
7878 DeclResult actOnObjCTypeParam(Scope *S,
7879 ObjCTypeParamVariance variance,
7880 SourceLocation varianceLoc,
7881 unsigned index,
7882 IdentifierInfo *paramName,
7883 SourceLocation paramLoc,
7884 SourceLocation colonLoc,
7885 ParsedType typeBound);
7886
7887 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7888 ArrayRef<Decl *> typeParams,
7889 SourceLocation rAngleLoc);
7890 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7891
7892 Decl *ActOnStartClassInterface(Scope *S,
7893 SourceLocation AtInterfaceLoc,
7894 IdentifierInfo *ClassName,
7895 SourceLocation ClassLoc,
7896 ObjCTypeParamList *typeParamList,
7897 IdentifierInfo *SuperName,
7898 SourceLocation SuperLoc,
7899 ArrayRef<ParsedType> SuperTypeArgs,
7900 SourceRange SuperTypeArgsRange,
7901 Decl * const *ProtoRefs,
7902 unsigned NumProtoRefs,
7903 const SourceLocation *ProtoLocs,
7904 SourceLocation EndProtoLoc,
7905 AttributeList *AttrList);
7906
7907 void ActOnSuperClassOfClassInterface(Scope *S,
7908 SourceLocation AtInterfaceLoc,
7909 ObjCInterfaceDecl *IDecl,
7910 IdentifierInfo *ClassName,
7911 SourceLocation ClassLoc,
7912 IdentifierInfo *SuperName,
7913 SourceLocation SuperLoc,
7914 ArrayRef<ParsedType> SuperTypeArgs,
7915 SourceRange SuperTypeArgsRange);
7916
7917 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7918 SmallVectorImpl<SourceLocation> &ProtocolLocs,
7919 IdentifierInfo *SuperName,
7920 SourceLocation SuperLoc);
7921
7922 Decl *ActOnCompatibilityAlias(
7923 SourceLocation AtCompatibilityAliasLoc,
7924 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7925 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7926
7927 bool CheckForwardProtocolDeclarationForCircularDependency(
7928 IdentifierInfo *PName,
7929 SourceLocation &PLoc, SourceLocation PrevLoc,
7930 const ObjCList<ObjCProtocolDecl> &PList);
7931
7932 Decl *ActOnStartProtocolInterface(
7933 SourceLocation AtProtoInterfaceLoc,
7934 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7935 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7936 const SourceLocation *ProtoLocs,
7937 SourceLocation EndProtoLoc,
7938 AttributeList *AttrList);
7939
7940 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7941 IdentifierInfo *ClassName,
7942 SourceLocation ClassLoc,
7943 ObjCTypeParamList *typeParamList,
7944 IdentifierInfo *CategoryName,
7945 SourceLocation CategoryLoc,
7946 Decl * const *ProtoRefs,
7947 unsigned NumProtoRefs,
7948 const SourceLocation *ProtoLocs,
7949 SourceLocation EndProtoLoc,
7950 AttributeList *AttrList);
7951
7952 Decl *ActOnStartClassImplementation(
7953 SourceLocation AtClassImplLoc,
7954 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7955 IdentifierInfo *SuperClassname,
7956 SourceLocation SuperClassLoc);
7957
7958 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7959 IdentifierInfo *ClassName,
7960 SourceLocation ClassLoc,
7961 IdentifierInfo *CatName,
7962 SourceLocation CatLoc);
7963
7964 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7965 ArrayRef<Decl *> Decls);
7966
7967 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7968 IdentifierInfo **IdentList,
7969 SourceLocation *IdentLocs,
7970 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7971 unsigned NumElts);
7972
7973 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7974 ArrayRef<IdentifierLocPair> IdentList,
7975 AttributeList *attrList);
7976
7977 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7978 ArrayRef<IdentifierLocPair> ProtocolId,
7979 SmallVectorImpl<Decl *> &Protocols);
7980
7981 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7982 SourceLocation ProtocolLoc,
7983 IdentifierInfo *TypeArgId,
7984 SourceLocation TypeArgLoc,
7985 bool SelectProtocolFirst = false);
7986
7987 /// Given a list of identifiers (and their locations), resolve the
7988 /// names to either Objective-C protocol qualifiers or type
7989 /// arguments, as appropriate.
7990 void actOnObjCTypeArgsOrProtocolQualifiers(
7991 Scope *S,
7992 ParsedType baseType,
7993 SourceLocation lAngleLoc,
7994 ArrayRef<IdentifierInfo *> identifiers,
7995 ArrayRef<SourceLocation> identifierLocs,
7996 SourceLocation rAngleLoc,
7997 SourceLocation &typeArgsLAngleLoc,
7998 SmallVectorImpl<ParsedType> &typeArgs,
7999 SourceLocation &typeArgsRAngleLoc,
8000 SourceLocation &protocolLAngleLoc,
8001 SmallVectorImpl<Decl *> &protocols,
8002 SourceLocation &protocolRAngleLoc,
8003 bool warnOnIncompleteProtocols);
8004
8005 /// Build a an Objective-C protocol-qualified 'id' type where no
8006 /// base type was specified.
8007 TypeResult actOnObjCProtocolQualifierType(
8008 SourceLocation lAngleLoc,
8009 ArrayRef<Decl *> protocols,
8010 ArrayRef<SourceLocation> protocolLocs,
8011 SourceLocation rAngleLoc);
8012
8013 /// Build a specialized and/or protocol-qualified Objective-C type.
8014 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
8015 Scope *S,
8016 SourceLocation Loc,
8017 ParsedType BaseType,
8018 SourceLocation TypeArgsLAngleLoc,
8019 ArrayRef<ParsedType> TypeArgs,
8020 SourceLocation TypeArgsRAngleLoc,
8021 SourceLocation ProtocolLAngleLoc,
8022 ArrayRef<Decl *> Protocols,
8023 ArrayRef<SourceLocation> ProtocolLocs,
8024 SourceLocation ProtocolRAngleLoc);
8025
8026 /// Build an Objective-C type parameter type.
8027 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
8028 SourceLocation ProtocolLAngleLoc,
8029 ArrayRef<ObjCProtocolDecl *> Protocols,
8030 ArrayRef<SourceLocation> ProtocolLocs,
8031 SourceLocation ProtocolRAngleLoc,
8032 bool FailOnError = false);
8033
8034 /// Build an Objective-C object pointer type.
8035 QualType BuildObjCObjectType(QualType BaseType,
8036 SourceLocation Loc,
8037 SourceLocation TypeArgsLAngleLoc,
8038 ArrayRef<TypeSourceInfo *> TypeArgs,
8039 SourceLocation TypeArgsRAngleLoc,
8040 SourceLocation ProtocolLAngleLoc,
8041 ArrayRef<ObjCProtocolDecl *> Protocols,
8042 ArrayRef<SourceLocation> ProtocolLocs,
8043 SourceLocation ProtocolRAngleLoc,
8044 bool FailOnError = false);
8045
8046 /// Check the application of the Objective-C '__kindof' qualifier to
8047 /// the given type.
8048 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
8049
8050 /// Ensure attributes are consistent with type.
8051 /// \param [in, out] Attributes The attributes to check; they will
8052 /// be modified to be consistent with \p PropertyTy.
8053 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
8054 SourceLocation Loc,
8055 unsigned &Attributes,
8056 bool propertyInPrimaryClass);
8057
8058 /// Process the specified property declaration and create decls for the
8059 /// setters and getters as needed.
8060 /// \param property The property declaration being processed
8061 void ProcessPropertyDecl(ObjCPropertyDecl *property);
8062
8063
8064 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
8065 ObjCPropertyDecl *SuperProperty,
8066 const IdentifierInfo *Name,
8067 bool OverridingProtocolProperty);
8068
8069 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
8070 ObjCInterfaceDecl *ID);
8071
8072 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
8073 ArrayRef<Decl *> allMethods = None,
8074 ArrayRef<DeclGroupPtrTy> allTUVars = None);
8075
8076 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
8077 SourceLocation LParenLoc,
8078 FieldDeclarator &FD, ObjCDeclSpec &ODS,
8079 Selector GetterSel, Selector SetterSel,
8080 tok::ObjCKeywordKind MethodImplKind,
8081 DeclContext *lexicalDC = nullptr);
8082
8083 Decl *ActOnPropertyImplDecl(Scope *S,
8084 SourceLocation AtLoc,
8085 SourceLocation PropertyLoc,
8086 bool ImplKind,
8087 IdentifierInfo *PropertyId,
8088 IdentifierInfo *PropertyIvar,
8089 SourceLocation PropertyIvarLoc,
8090 ObjCPropertyQueryKind QueryKind);
8091
8092 enum ObjCSpecialMethodKind {
8093 OSMK_None,
8094 OSMK_Alloc,
8095 OSMK_New,
8096 OSMK_Copy,
8097 OSMK_RetainingInit,
8098 OSMK_NonRetainingInit
8099 };
8100
8101 struct ObjCArgInfo {
8102 IdentifierInfo *Name;
8103 SourceLocation NameLoc;
8104 // The Type is null if no type was specified, and the DeclSpec is invalid
8105 // in this case.
8106 ParsedType Type;
8107 ObjCDeclSpec DeclSpec;
8108
8109 /// ArgAttrs - Attribute list for this argument.
8110 AttributeList *ArgAttrs;
8111 };
8112
8113 Decl *ActOnMethodDeclaration(
8114 Scope *S,
8115 SourceLocation BeginLoc, // location of the + or -.
8116 SourceLocation EndLoc, // location of the ; or {.
8117 tok::TokenKind MethodType,
8118 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
8119 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
8120 // optional arguments. The number of types/arguments is obtained
8121 // from the Sel.getNumArgs().
8122 ObjCArgInfo *ArgInfo,
8123 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
8124 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
8125 bool isVariadic, bool MethodDefinition);
8126
8127 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
8128 const ObjCObjectPointerType *OPT,
8129 bool IsInstance);
8130 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
8131 bool IsInstance);
8132
8133 bool CheckARCMethodDecl(ObjCMethodDecl *method);
8134 bool inferObjCARCLifetime(ValueDecl *decl);
8135
8136 ExprResult
8137 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
8138 Expr *BaseExpr,
8139 SourceLocation OpLoc,
8140 DeclarationName MemberName,
8141 SourceLocation MemberLoc,
8142 SourceLocation SuperLoc, QualType SuperType,
8143 bool Super);
8144
8145 ExprResult
8146 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
8147 IdentifierInfo &propertyName,
8148 SourceLocation receiverNameLoc,
8149 SourceLocation propertyNameLoc);
8150
8151 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
8152
8153 /// \brief Describes the kind of message expression indicated by a message
8154 /// send that starts with an identifier.
8155 enum ObjCMessageKind {
8156 /// \brief The message is sent to 'super'.
8157 ObjCSuperMessage,
8158 /// \brief The message is an instance message.
8159 ObjCInstanceMessage,
8160 /// \brief The message is a class message, and the identifier is a type
8161 /// name.
8162 ObjCClassMessage
8163 };
8164
8165 ObjCMessageKind getObjCMessageKind(Scope *S,
8166 IdentifierInfo *Name,
8167 SourceLocation NameLoc,
8168 bool IsSuper,
8169 bool HasTrailingDot,
8170 ParsedType &ReceiverType);
8171
8172 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
8173 Selector Sel,
8174 SourceLocation LBracLoc,
8175 ArrayRef<SourceLocation> SelectorLocs,
8176 SourceLocation RBracLoc,
8177 MultiExprArg Args);
8178
8179 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
8180 QualType ReceiverType,
8181 SourceLocation SuperLoc,
8182 Selector Sel,
8183 ObjCMethodDecl *Method,
8184 SourceLocation LBracLoc,
8185 ArrayRef<SourceLocation> SelectorLocs,
8186 SourceLocation RBracLoc,
8187 MultiExprArg Args,
8188 bool isImplicit = false);
8189
8190 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
8191 bool isSuperReceiver,
8192 SourceLocation Loc,
8193 Selector Sel,
8194 ObjCMethodDecl *Method,
8195 MultiExprArg Args);
8196
8197 ExprResult ActOnClassMessage(Scope *S,
8198 ParsedType Receiver,
8199 Selector Sel,
8200 SourceLocation LBracLoc,
8201 ArrayRef<SourceLocation> SelectorLocs,
8202 SourceLocation RBracLoc,
8203 MultiExprArg Args);
8204
8205 ExprResult BuildInstanceMessage(Expr *Receiver,
8206 QualType ReceiverType,
8207 SourceLocation SuperLoc,
8208 Selector Sel,
8209 ObjCMethodDecl *Method,
8210 SourceLocation LBracLoc,
8211 ArrayRef<SourceLocation> SelectorLocs,
8212 SourceLocation RBracLoc,
8213 MultiExprArg Args,
8214 bool isImplicit = false);
8215
8216 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
8217 QualType ReceiverType,
8218 SourceLocation Loc,
8219 Selector Sel,
8220 ObjCMethodDecl *Method,
8221 MultiExprArg Args);
8222
8223 ExprResult ActOnInstanceMessage(Scope *S,
8224 Expr *Receiver,
8225 Selector Sel,
8226 SourceLocation LBracLoc,
8227 ArrayRef<SourceLocation> SelectorLocs,
8228 SourceLocation RBracLoc,
8229 MultiExprArg Args);
8230
8231 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
8232 ObjCBridgeCastKind Kind,
8233 SourceLocation BridgeKeywordLoc,
8234 TypeSourceInfo *TSInfo,
8235 Expr *SubExpr);
8236
8237 ExprResult ActOnObjCBridgedCast(Scope *S,
8238 SourceLocation LParenLoc,
8239 ObjCBridgeCastKind Kind,
8240 SourceLocation BridgeKeywordLoc,
8241 ParsedType Type,
8242 SourceLocation RParenLoc,
8243 Expr *SubExpr);
8244
8245 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8246
8247 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8248
8249 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8250 CastKind &Kind);
8251
8252 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8253 QualType DestType, QualType SrcType,
8254 ObjCInterfaceDecl *&RelatedClass,
8255 ObjCMethodDecl *&ClassMethod,
8256 ObjCMethodDecl *&InstanceMethod,
8257 TypedefNameDecl *&TDNDecl,
8258 bool CfToNs, bool Diagnose = true);
8259
8260 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8261 QualType DestType, QualType SrcType,
8262 Expr *&SrcExpr, bool Diagnose = true);
8263
8264 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8265 bool Diagnose = true);
8266
8267 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8268
8269 /// \brief Check whether the given new method is a valid override of the
8270 /// given overridden method, and set any properties that should be inherited.
8271 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8272 const ObjCMethodDecl *Overridden);
8273
8274 /// \brief Describes the compatibility of a result type with its method.
8275 enum ResultTypeCompatibilityKind {
8276 RTC_Compatible,
8277 RTC_Incompatible,
8278 RTC_Unknown
8279 };
8280
8281 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8282 ObjCInterfaceDecl *CurrentClass,
8283 ResultTypeCompatibilityKind RTC);
8284
8285 enum PragmaOptionsAlignKind {
8286 POAK_Native, // #pragma options align=native
8287 POAK_Natural, // #pragma options align=natural
8288 POAK_Packed, // #pragma options align=packed
8289 POAK_Power, // #pragma options align=power
8290 POAK_Mac68k, // #pragma options align=mac68k
8291 POAK_Reset // #pragma options align=reset
8292 };
8293
8294 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
8295 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
8296 PragmaClangSectionAction Action,
8297 PragmaClangSectionKind SecKind, StringRef SecName);
8298
8299 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8300 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8301 SourceLocation PragmaLoc);
8302
8303 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8304 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8305 StringRef SlotLabel, Expr *Alignment);
8306
8307 enum class PragmaPackDiagnoseKind {
8308 NonDefaultStateAtInclude,
8309 ChangedStateAtExit
8310 };
8311
8312 void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
8313 SourceLocation IncludeLoc);
8314 void DiagnoseUnterminatedPragmaPack();
8315
8316 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8317 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8318
8319 /// ActOnPragmaMSComment - Called on well formed
8320 /// \#pragma comment(kind, "arg").
8321 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8322 StringRef Arg);
8323
8324 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8325 /// pointers_to_members(representation method[, general purpose
8326 /// representation]).
8327 void ActOnPragmaMSPointersToMembers(
8328 LangOptions::PragmaMSPointersToMembersKind Kind,
8329 SourceLocation PragmaLoc);
8330
8331 /// \brief Called on well formed \#pragma vtordisp().
8332 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8333 SourceLocation PragmaLoc,
8334 MSVtorDispAttr::Mode Value);
8335
8336 enum PragmaSectionKind {
8337 PSK_DataSeg,
8338 PSK_BSSSeg,
8339 PSK_ConstSeg,
8340 PSK_CodeSeg,
8341 };
8342
8343 bool UnifySection(StringRef SectionName,
8344 int SectionFlags,
8345 DeclaratorDecl *TheDecl);
8346 bool UnifySection(StringRef SectionName,
8347 int SectionFlags,
8348 SourceLocation PragmaSectionLocation);
8349
8350 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8351 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8352 PragmaMsStackAction Action,
8353 llvm::StringRef StackSlotLabel,
8354 StringLiteral *SegmentName,
8355 llvm::StringRef PragmaName);
8356
8357 /// \brief Called on well formed \#pragma section().
8358 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8359 int SectionFlags, StringLiteral *SegmentName);
8360
8361 /// \brief Called on well-formed \#pragma init_seg().
8362 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8363 StringLiteral *SegmentName);
8364
8365 /// \brief Called on #pragma clang __debug dump II
8366 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8367
8368 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8369 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8370 StringRef Value);
8371
8372 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8373 void ActOnPragmaUnused(const Token &Identifier,
8374 Scope *curScope,
8375 SourceLocation PragmaLoc);
8376
8377 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8378 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8379 SourceLocation PragmaLoc);
8380
8381 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8382 SourceLocation Loc);
8383 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8384
8385 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8386 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8387 SourceLocation PragmaLoc,
8388 SourceLocation WeakNameLoc);
8389
8390 /// ActOnPragmaRedefineExtname - Called on well formed
8391 /// \#pragma redefine_extname oldname newname.
8392 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8393 IdentifierInfo* AliasName,
8394 SourceLocation PragmaLoc,
8395 SourceLocation WeakNameLoc,
8396 SourceLocation AliasNameLoc);
8397
8398 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8399 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8400 IdentifierInfo* AliasName,
8401 SourceLocation PragmaLoc,
8402 SourceLocation WeakNameLoc,
8403 SourceLocation AliasNameLoc);
8404
8405 /// ActOnPragmaFPContract - Called on well formed
8406 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8407 /// \#pragma clang fp contract
8408 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8409
8410 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8411 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8412 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8413
8414 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8415 void AddMsStructLayoutForRecord(RecordDecl *RD);
8416
8417 /// FreePackedContext - Deallocate and null out PackContext.
8418 void FreePackedContext();
8419
8420 /// PushNamespaceVisibilityAttr - Note that we've entered a
8421 /// namespace with a visibility attribute.
8422 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8423 SourceLocation Loc);
8424
8425 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8426 /// add an appropriate visibility attribute.
8427 void AddPushedVisibilityAttribute(Decl *RD);
8428
8429 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8430 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8431 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8432
8433 /// FreeVisContext - Deallocate and null out VisContext.
8434 void FreeVisContext();
8435
8436 /// AddCFAuditedAttribute - Check whether we're currently within
8437 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8438 /// the appropriate attribute.
8439 void AddCFAuditedAttribute(Decl *D);
8440
8441 /// \brief Called on well-formed '\#pragma clang attribute push'.
8442 void ActOnPragmaAttributePush(AttributeList &Attribute,
8443 SourceLocation PragmaLoc,
8444 attr::ParsedSubjectMatchRuleSet Rules);
8445
8446 /// \brief Called on well-formed '\#pragma clang attribute pop'.
8447 void ActOnPragmaAttributePop(SourceLocation PragmaLoc);
8448
8449 /// \brief Adds the attributes that have been specified using the
8450 /// '\#pragma clang attribute push' directives to the given declaration.
8451 void AddPragmaAttributes(Scope *S, Decl *D);
8452
8453 void DiagnoseUnterminatedPragmaAttribute();
8454
8455 /// \brief Called on well formed \#pragma clang optimize.
8456 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8457
8458 /// \brief Get the location for the currently active "\#pragma clang optimize
8459 /// off". If this location is invalid, then the state of the pragma is "on".
8460 SourceLocation getOptimizeOffPragmaLocation() const {
8461 return OptimizeOffPragmaLocation;
8462 }
8463
8464 /// \brief Only called on function definitions; if there is a pragma in scope
8465 /// with the effect of a range-based optnone, consider marking the function
8466 /// with attribute optnone.
8467 void AddRangeBasedOptnone(FunctionDecl *FD);
8468
8469 /// \brief Adds the 'optnone' attribute to the function declaration if there
8470 /// are no conflicts; Loc represents the location causing the 'optnone'
8471 /// attribute to be added (usually because of a pragma).
8472 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8473
8474 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8475 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8476 unsigned SpellingListIndex, bool IsPackExpansion);
8477 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8478 unsigned SpellingListIndex, bool IsPackExpansion);
8479
8480 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8481 /// declaration.
8482 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8483 unsigned SpellingListIndex);
8484
8485 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8486 /// declaration.
8487 void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8488 unsigned SpellingListIndex);
8489
8490 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8491 /// declaration.
8492 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8493 unsigned SpellingListIndex);
8494
8495 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8496 /// declaration.
8497 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8498 Expr *MinBlocks, unsigned SpellingListIndex);
8499
8500 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8501 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8502 unsigned SpellingListIndex, bool InInstantiation = false);
8503
8504 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8505 ParameterABI ABI, unsigned SpellingListIndex);
8506
8507 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8508 unsigned SpellingListIndex, bool isNSConsumed,
8509 bool isTemplateInstantiation);
8510
8511 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
8512
8513 //===--------------------------------------------------------------------===//
8514 // C++ Coroutines TS
8515 //
8516 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
8517 StringRef Keyword);
8518 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8519 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8520 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8521
8522 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8523 bool IsImplicit = false);
8524 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8525 UnresolvedLookupExpr* Lookup);
8526 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8527 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8528 bool IsImplicit = false);
8529 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8530 bool buildCoroutineParameterMoves(SourceLocation Loc);
8531 VarDecl *buildCoroutinePromise(SourceLocation Loc);
8532 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8533
8534 //===--------------------------------------------------------------------===//
8535 // OpenCL extensions.
8536 //
8537private:
8538 std::string CurrOpenCLExtension;
8539 /// Extensions required by an OpenCL type.
8540 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8541 /// Extensions required by an OpenCL declaration.
8542 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8543public:
8544 llvm::StringRef getCurrentOpenCLExtension() const {
8545 return CurrOpenCLExtension;
8546 }
8547 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8548 CurrOpenCLExtension = Ext;
8549 }
8550
8551 /// \brief Set OpenCL extensions for a type which can only be used when these
8552 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8553 /// \param Exts A space separated list of OpenCL extensions.
8554 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8555
8556 /// \brief Set OpenCL extensions for a declaration which can only be
8557 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8558 /// nothing.
8559 /// \param Exts A space separated list of OpenCL extensions.
8560 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8561
8562 /// \brief Set current OpenCL extensions for a type which can only be used
8563 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8564 /// empty, do nothing.
8565 void setCurrentOpenCLExtensionForType(QualType T);
8566
8567 /// \brief Set current OpenCL extensions for a declaration which
8568 /// can only be used when these OpenCL extensions are enabled. If current
8569 /// OpenCL extension is empty, do nothing.
8570 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8571
8572 bool isOpenCLDisabledDecl(Decl *FD);
8573
8574 /// \brief Check if type \p T corresponding to declaration specifier \p DS
8575 /// is disabled due to required OpenCL extensions being disabled. If so,
8576 /// emit diagnostics.
8577 /// \return true if type is disabled.
8578 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8579
8580 /// \brief Check if declaration \p D used by expression \p E
8581 /// is disabled due to required OpenCL extensions being disabled. If so,
8582 /// emit diagnostics.
8583 /// \return true if type is disabled.
8584 bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
8585
8586 //===--------------------------------------------------------------------===//
8587 // OpenMP directives and clauses.
8588 //
8589private:
8590 void *VarDataSharingAttributesStack;
8591 /// Set to true inside '#pragma omp declare target' region.
8592 bool IsInOpenMPDeclareTargetContext = false;
8593 /// \brief Initialization of data-sharing attributes stack.
8594 void InitDataSharingAttributesStack();
8595 void DestroyDataSharingAttributesStack();
8596 ExprResult
8597 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8598 bool StrictlyPositive = true);
8599 /// Returns OpenMP nesting level for current directive.
8600 unsigned getOpenMPNestingLevel() const;
8601
8602 /// Adjusts the function scopes index for the target-based regions.
8603 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
8604 unsigned Level) const;
8605
8606 /// Push new OpenMP function region for non-capturing function.
8607 void pushOpenMPFunctionRegion();
8608
8609 /// Pop OpenMP function region for non-capturing function.
8610 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
8611
8612 /// Checks if a type or a declaration is disabled due to the owning extension
8613 /// being disabled, and emits diagnostic messages if it is disabled.
8614 /// \param D type or declaration to be checked.
8615 /// \param DiagLoc source location for the diagnostic message.
8616 /// \param DiagInfo information to be emitted for the diagnostic message.
8617 /// \param SrcRange source range of the declaration.
8618 /// \param Map maps type or declaration to the extensions.
8619 /// \param Selector selects diagnostic message: 0 for type and 1 for
8620 /// declaration.
8621 /// \return true if the type or declaration is disabled.
8622 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8623 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8624 MapT &Map, unsigned Selector = 0,
8625 SourceRange SrcRange = SourceRange());
8626
8627public:
8628 /// \brief Return true if the provided declaration \a VD should be captured by
8629 /// reference.
8630 /// \param Level Relative level of nested OpenMP construct for that the check
8631 /// is performed.
8632 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8633
8634 /// \brief Check if the specified variable is used in one of the private
8635 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8636 /// constructs.
8637 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8638 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8639 ExprObjectKind OK, SourceLocation Loc);
8640
8641 /// \brief Check if the specified variable is used in 'private' clause.
8642 /// \param Level Relative level of nested OpenMP construct for that the check
8643 /// is performed.
8644 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8645
8646 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
8647 /// for \p FD based on DSA for the provided corresponding captured declaration
8648 /// \p D.
8649 void setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level);
8650
8651 /// \brief Check if the specified variable is captured by 'target' directive.
8652 /// \param Level Relative level of nested OpenMP construct for that the check
8653 /// is performed.
8654 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8655
8656 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8657 Expr *Op);
8658 /// \brief Called on start of new data sharing attribute block.
8659 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8660 const DeclarationNameInfo &DirName, Scope *CurScope,
8661 SourceLocation Loc);
8662 /// \brief Start analysis of clauses.
8663 void StartOpenMPClause(OpenMPClauseKind K);
8664 /// \brief End analysis of clauses.
8665 void EndOpenMPClause();
8666 /// \brief Called on end of data sharing attribute block.
8667 void EndOpenMPDSABlock(Stmt *CurDirective);
8668
8669 /// \brief Check if the current region is an OpenMP loop region and if it is,
8670 /// mark loop control variable, used in \p Init for loop initialization, as
8671 /// private by default.
8672 /// \param Init First part of the for loop.
8673 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8674
8675 // OpenMP directives and clauses.
8676 /// \brief Called on correct id-expression from the '#pragma omp
8677 /// threadprivate'.
8678 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8679 CXXScopeSpec &ScopeSpec,
8680 const DeclarationNameInfo &Id);
8681 /// \brief Called on well-formed '#pragma omp threadprivate'.
8682 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8683 SourceLocation Loc,
8684 ArrayRef<Expr *> VarList);
8685 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8686 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8687 SourceLocation Loc,
8688 ArrayRef<Expr *> VarList);
8689 /// \brief Check if the specified type is allowed to be used in 'omp declare
8690 /// reduction' construct.
8691 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8692 TypeResult ParsedType);
8693 /// \brief Called on start of '#pragma omp declare reduction'.
8694 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8695 Scope *S, DeclContext *DC, DeclarationName Name,
8696 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8697 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8698 /// \brief Initialize declare reduction construct initializer.
8699 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8700 /// \brief Finish current declare reduction construct initializer.
8701 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8702 /// \brief Initialize declare reduction construct initializer.
8703 /// \return omp_priv variable.
8704 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8705 /// \brief Finish current declare reduction construct initializer.
8706 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
8707 VarDecl *OmpPrivParm);
8708 /// \brief Called at the end of '#pragma omp declare reduction'.
8709 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8710 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8711
8712 /// Called on the start of target region i.e. '#pragma omp declare target'.
8713 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8714 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8715 void ActOnFinishOpenMPDeclareTargetDirective();
8716 /// Called on correct id-expression from the '#pragma omp declare target'.
8717 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8718 const DeclarationNameInfo &Id,
8719 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8720 NamedDeclSetType &SameDirectiveDecls);
8721 /// Check declaration inside target region.
8722 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
8723 SourceLocation IdLoc = SourceLocation());
8724 /// Return true inside OpenMP declare target region.
8725 bool isInOpenMPDeclareTargetContext() const {
8726 return IsInOpenMPDeclareTargetContext;
8727 }
8728 /// Return true inside OpenMP target region.
8729 bool isInOpenMPTargetExecutionDirective() const;
8730 /// Return true if (un)supported features for the current target should be
8731 /// diagnosed if OpenMP (offloading) is enabled.
8732 bool shouldDiagnoseTargetSupportFromOpenMP() const {
8733 return !getLangOpts().OpenMPIsDevice || isInOpenMPDeclareTargetContext() ||
8734 isInOpenMPTargetExecutionDirective();
8735 }
8736
8737 /// Return the number of captured regions created for an OpenMP directive.
8738 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8739
8740 /// \brief Initialization of captured region for OpenMP region.
8741 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8742 /// \brief End of OpenMP region.
8743 ///
8744 /// \param S Statement associated with the current OpenMP region.
8745 /// \param Clauses List of clauses for the current OpenMP region.
8746 ///
8747 /// \returns Statement for finished OpenMP region.
8748 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8749 StmtResult ActOnOpenMPExecutableDirective(
8750 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8751 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8752 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8753 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8754 /// of the associated statement.
8755 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8756 Stmt *AStmt,
8757 SourceLocation StartLoc,
8758 SourceLocation EndLoc);
8759 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8760 /// of the associated statement.
8761 StmtResult ActOnOpenMPSimdDirective(
8762 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8763 SourceLocation EndLoc,
8764 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8765 /// \brief Called on well-formed '\#pragma omp for' after parsing
8766 /// of the associated statement.
8767 StmtResult ActOnOpenMPForDirective(
8768 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8769 SourceLocation EndLoc,
8770 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8771 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8772 /// of the associated statement.
8773 StmtResult ActOnOpenMPForSimdDirective(
8774 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8775 SourceLocation EndLoc,
8776 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8777 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8778 /// of the associated statement.
8779 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8780 Stmt *AStmt, SourceLocation StartLoc,
8781 SourceLocation EndLoc);
8782 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8783 /// associated statement.
8784 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8785 SourceLocation EndLoc);
8786 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8787 /// associated statement.
8788 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8789 Stmt *AStmt, SourceLocation StartLoc,
8790 SourceLocation EndLoc);
8791 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8792 /// associated statement.
8793 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8794 SourceLocation EndLoc);
8795 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8796 /// associated statement.
8797 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8798 ArrayRef<OMPClause *> Clauses,
8799 Stmt *AStmt, SourceLocation StartLoc,
8800 SourceLocation EndLoc);
8801 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8802 /// of the associated statement.
8803 StmtResult ActOnOpenMPParallelForDirective(
8804 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8805 SourceLocation EndLoc,
8806 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8807 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8808 /// parsing of the associated statement.
8809 StmtResult ActOnOpenMPParallelForSimdDirective(
8810 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8811 SourceLocation EndLoc,
8812 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8813 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8814 /// parsing of the associated statement.
8815 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8816 Stmt *AStmt,
8817 SourceLocation StartLoc,
8818 SourceLocation EndLoc);
8819 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8820 /// associated statement.
8821 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8822 Stmt *AStmt, SourceLocation StartLoc,
8823 SourceLocation EndLoc);
8824 /// \brief Called on well-formed '\#pragma omp taskyield'.
8825 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8826 SourceLocation EndLoc);
8827 /// \brief Called on well-formed '\#pragma omp barrier'.
8828 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8829 SourceLocation EndLoc);
8830 /// \brief Called on well-formed '\#pragma omp taskwait'.
8831 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8832 SourceLocation EndLoc);
8833 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8834 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8835 Stmt *AStmt, SourceLocation StartLoc,
8836 SourceLocation EndLoc);
8837 /// \brief Called on well-formed '\#pragma omp flush'.
8838 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8839 SourceLocation StartLoc,
8840 SourceLocation EndLoc);
8841 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8842 /// associated statement.
8843 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8844 Stmt *AStmt, SourceLocation StartLoc,
8845 SourceLocation EndLoc);
8846 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8847 /// associated statement.
8848 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8849 Stmt *AStmt, SourceLocation StartLoc,
8850 SourceLocation EndLoc);
8851 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8852 /// associated statement.
8853 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8854 Stmt *AStmt, SourceLocation StartLoc,
8855 SourceLocation EndLoc);
8856 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8857 /// the associated statement.
8858 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8859 Stmt *AStmt, SourceLocation StartLoc,
8860 SourceLocation EndLoc);
8861 /// \brief Called on well-formed '\#pragma omp target enter data' after
8862 /// parsing of the associated statement.
8863 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8864 SourceLocation StartLoc,
8865 SourceLocation EndLoc,
8866 Stmt *AStmt);
8867 /// \brief Called on well-formed '\#pragma omp target exit data' after
8868 /// parsing of the associated statement.
8869 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8870 SourceLocation StartLoc,
8871 SourceLocation EndLoc,
8872 Stmt *AStmt);
8873 /// \brief Called on well-formed '\#pragma omp target parallel' after
8874 /// parsing of the associated statement.
8875 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8876 Stmt *AStmt,
8877 SourceLocation StartLoc,
8878 SourceLocation EndLoc);
8879 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8880 /// parsing of the associated statement.
8881 StmtResult ActOnOpenMPTargetParallelForDirective(
8882 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8883 SourceLocation EndLoc,
8884 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8885 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8886 /// associated statement.
8887 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8888 Stmt *AStmt, SourceLocation StartLoc,
8889 SourceLocation EndLoc);
8890 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8891 StmtResult
8892 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8893 SourceLocation EndLoc,
8894 OpenMPDirectiveKind CancelRegion);
8895 /// \brief Called on well-formed '\#pragma omp cancel'.
8896 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8897 SourceLocation StartLoc,
8898 SourceLocation EndLoc,
8899 OpenMPDirectiveKind CancelRegion);
8900 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8901 /// associated statement.
8902 StmtResult ActOnOpenMPTaskLoopDirective(
8903 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8904 SourceLocation EndLoc,
8905 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8906 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8907 /// the associated statement.
8908 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8909 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8910 SourceLocation EndLoc,
8911 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8912 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8913 /// of the associated statement.
8914 StmtResult ActOnOpenMPDistributeDirective(
8915 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8916 SourceLocation EndLoc,
8917 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8918 /// \brief Called on well-formed '\#pragma omp target update'.
8919 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8920 SourceLocation StartLoc,
8921 SourceLocation EndLoc,
8922 Stmt *AStmt);
8923 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8924 /// parsing of the associated statement.
8925 StmtResult ActOnOpenMPDistributeParallelForDirective(
8926 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8927 SourceLocation EndLoc,
8928 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8929 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8930 /// after parsing of the associated statement.
8931 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8932 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8933 SourceLocation EndLoc,
8934 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8935 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8936 /// parsing of the associated statement.
8937 StmtResult ActOnOpenMPDistributeSimdDirective(
8938 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8939 SourceLocation EndLoc,
8940 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8941 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8942 /// parsing of the associated statement.
8943 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8944 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8945 SourceLocation EndLoc,
8946 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8947 /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8948 /// the associated statement.
8949 StmtResult ActOnOpenMPTargetSimdDirective(
8950 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8951 SourceLocation EndLoc,
8952 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8953 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8954 /// the associated statement.
8955 StmtResult ActOnOpenMPTeamsDistributeDirective(
8956 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8957 SourceLocation EndLoc,
8958 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8959 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8960 /// of the associated statement.
8961 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8962 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8963 SourceLocation EndLoc,
8964 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8965 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8966 /// after parsing of the associated statement.
8967 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8968 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8969 SourceLocation EndLoc,
8970 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8971 /// Called on well-formed '\#pragma omp teams distribute parallel for'
8972 /// after parsing of the associated statement.
8973 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8974 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8975 SourceLocation EndLoc,
8976 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8977 /// Called on well-formed '\#pragma omp target teams' after parsing of the
8978 /// associated statement.
8979 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8980 Stmt *AStmt,
8981 SourceLocation StartLoc,
8982 SourceLocation EndLoc);
8983 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8984 /// of the associated statement.
8985 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8986 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8987 SourceLocation EndLoc,
8988 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8989 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8990 /// after parsing of the associated statement.
8991 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8992 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8993 SourceLocation EndLoc,
8994 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8995 /// Called on well-formed '\#pragma omp target teams distribute parallel for
8996 /// simd' after parsing of the associated statement.
8997 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8998 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8999 SourceLocation EndLoc,
9000 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
9001 /// Called on well-formed '\#pragma omp target teams distribute simd' after
9002 /// parsing of the associated statement.
9003 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
9004 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9005 SourceLocation EndLoc,
9006 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
9007
9008 /// Checks correctness of linear modifiers.
9009 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9010 SourceLocation LinLoc);
9011 /// Checks that the specified declaration matches requirements for the linear
9012 /// decls.
9013 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9014 OpenMPLinearClauseKind LinKind, QualType Type);
9015
9016 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
9017 /// the associated method/function.
9018 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
9019 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
9020 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
9021 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
9022 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
9023
9024 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
9025 Expr *Expr,
9026 SourceLocation StartLoc,
9027 SourceLocation LParenLoc,
9028 SourceLocation EndLoc);
9029 /// \brief Called on well-formed 'if' clause.
9030 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9031 Expr *Condition, SourceLocation StartLoc,
9032 SourceLocation LParenLoc,
9033 SourceLocation NameModifierLoc,
9034 SourceLocation ColonLoc,
9035 SourceLocation EndLoc);
9036 /// \brief Called on well-formed 'final' clause.
9037 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
9038 SourceLocation LParenLoc,
9039 SourceLocation EndLoc);
9040 /// \brief Called on well-formed 'num_threads' clause.
9041 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9042 SourceLocation StartLoc,
9043 SourceLocation LParenLoc,
9044 SourceLocation EndLoc);
9045 /// \brief Called on well-formed 'safelen' clause.
9046 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
9047 SourceLocation StartLoc,
9048 SourceLocation LParenLoc,
9049 SourceLocation EndLoc);
9050 /// \brief Called on well-formed 'simdlen' clause.
9051 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
9052 SourceLocation LParenLoc,
9053 SourceLocation EndLoc);
9054 /// \brief Called on well-formed 'collapse' clause.
9055 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
9056 SourceLocation StartLoc,
9057 SourceLocation LParenLoc,
9058 SourceLocation EndLoc);
9059 /// \brief Called on well-formed 'ordered' clause.
9060 OMPClause *
9061 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
9062 SourceLocation LParenLoc = SourceLocation(),
9063 Expr *NumForLoops = nullptr);
9064 /// \brief Called on well-formed 'grainsize' clause.
9065 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
9066 SourceLocation LParenLoc,
9067 SourceLocation EndLoc);
9068 /// \brief Called on well-formed 'num_tasks' clause.
9069 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
9070 SourceLocation LParenLoc,
9071 SourceLocation EndLoc);
9072 /// \brief Called on well-formed 'hint' clause.
9073 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
9074 SourceLocation LParenLoc,
9075 SourceLocation EndLoc);
9076
9077 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
9078 unsigned Argument,
9079 SourceLocation ArgumentLoc,
9080 SourceLocation StartLoc,
9081 SourceLocation LParenLoc,
9082 SourceLocation EndLoc);
9083 /// \brief Called on well-formed 'default' clause.
9084 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9085 SourceLocation KindLoc,
9086 SourceLocation StartLoc,
9087 SourceLocation LParenLoc,
9088 SourceLocation EndLoc);
9089 /// \brief Called on well-formed 'proc_bind' clause.
9090 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9091 SourceLocation KindLoc,
9092 SourceLocation StartLoc,
9093 SourceLocation LParenLoc,
9094 SourceLocation EndLoc);
9095
9096 OMPClause *ActOnOpenMPSingleExprWithArgClause(
9097 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
9098 SourceLocation StartLoc, SourceLocation LParenLoc,
9099 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
9100 SourceLocation EndLoc);
9101 /// \brief Called on well-formed 'schedule' clause.
9102 OMPClause *ActOnOpenMPScheduleClause(
9103 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
9104 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
9105 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9106 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
9107
9108 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
9109 SourceLocation EndLoc);
9110 /// \brief Called on well-formed 'nowait' clause.
9111 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9112 SourceLocation EndLoc);
9113 /// \brief Called on well-formed 'untied' clause.
9114 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9115 SourceLocation EndLoc);
9116 /// \brief Called on well-formed 'mergeable' clause.
9117 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9118 SourceLocation EndLoc);
9119 /// \brief Called on well-formed 'read' clause.
9120 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
9121 SourceLocation EndLoc);
9122 /// \brief Called on well-formed 'write' clause.
9123 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
9124 SourceLocation EndLoc);
9125 /// \brief Called on well-formed 'update' clause.
9126 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9127 SourceLocation EndLoc);
9128 /// \brief Called on well-formed 'capture' clause.
9129 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9130 SourceLocation EndLoc);
9131 /// \brief Called on well-formed 'seq_cst' clause.
9132 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9133 SourceLocation EndLoc);
9134 /// \brief Called on well-formed 'threads' clause.
9135 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9136 SourceLocation EndLoc);
9137 /// \brief Called on well-formed 'simd' clause.
9138 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9139 SourceLocation EndLoc);
9140 /// \brief Called on well-formed 'nogroup' clause.
9141 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9142 SourceLocation EndLoc);
9143
9144 OMPClause *ActOnOpenMPVarListClause(
9145 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
9146 SourceLocation StartLoc, SourceLocation LParenLoc,
9147 SourceLocation ColonLoc, SourceLocation EndLoc,
9148 CXXScopeSpec &ReductionIdScopeSpec,
9149 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
9150 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
9151 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9152 SourceLocation DepLinMapLoc);
9153 /// \brief Called on well-formed 'private' clause.
9154 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9155 SourceLocation StartLoc,
9156 SourceLocation LParenLoc,
9157 SourceLocation EndLoc);
9158 /// \brief Called on well-formed 'firstprivate' clause.
9159 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9160 SourceLocation StartLoc,
9161 SourceLocation LParenLoc,
9162 SourceLocation EndLoc);
9163 /// \brief Called on well-formed 'lastprivate' clause.
9164 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9165 SourceLocation StartLoc,
9166 SourceLocation LParenLoc,
9167 SourceLocation EndLoc);
9168 /// \brief Called on well-formed 'shared' clause.
9169 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9170 SourceLocation StartLoc,
9171 SourceLocation LParenLoc,
9172 SourceLocation EndLoc);
9173 /// \brief Called on well-formed 'reduction' clause.
9174 OMPClause *ActOnOpenMPReductionClause(
9175 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9176 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9177 CXXScopeSpec &ReductionIdScopeSpec,
9178 const DeclarationNameInfo &ReductionId,
9179 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9180 /// Called on well-formed 'task_reduction' clause.
9181 OMPClause *ActOnOpenMPTaskReductionClause(
9182 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9183 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9184 CXXScopeSpec &ReductionIdScopeSpec,
9185 const DeclarationNameInfo &ReductionId,
9186 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9187 /// Called on well-formed 'in_reduction' clause.
9188 OMPClause *ActOnOpenMPInReductionClause(
9189 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9190 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9191 CXXScopeSpec &ReductionIdScopeSpec,
9192 const DeclarationNameInfo &ReductionId,
9193 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9194 /// \brief Called on well-formed 'linear' clause.
9195 OMPClause *
9196 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
9197 SourceLocation StartLoc, SourceLocation LParenLoc,
9198 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
9199 SourceLocation ColonLoc, SourceLocation EndLoc);
9200 /// \brief Called on well-formed 'aligned' clause.
9201 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
9202 Expr *Alignment,
9203 SourceLocation StartLoc,
9204 SourceLocation LParenLoc,
9205 SourceLocation ColonLoc,
9206 SourceLocation EndLoc);
9207 /// \brief Called on well-formed 'copyin' clause.
9208 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9209 SourceLocation StartLoc,
9210 SourceLocation LParenLoc,
9211 SourceLocation EndLoc);
9212 /// \brief Called on well-formed 'copyprivate' clause.
9213 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9214 SourceLocation StartLoc,
9215 SourceLocation LParenLoc,
9216 SourceLocation EndLoc);
9217 /// \brief Called on well-formed 'flush' pseudo clause.
9218 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9219 SourceLocation StartLoc,
9220 SourceLocation LParenLoc,
9221 SourceLocation EndLoc);
9222 /// \brief Called on well-formed 'depend' clause.
9223 OMPClause *
9224 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
9225 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
9226 SourceLocation StartLoc, SourceLocation LParenLoc,
9227 SourceLocation EndLoc);
9228 /// \brief Called on well-formed 'device' clause.
9229 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9230 SourceLocation LParenLoc,
9231 SourceLocation EndLoc);
9232 /// \brief Called on well-formed 'map' clause.
9233 OMPClause *
9234 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
9235 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9236 SourceLocation MapLoc, SourceLocation ColonLoc,
9237 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9238 SourceLocation LParenLoc, SourceLocation EndLoc);
9239 /// \brief Called on well-formed 'num_teams' clause.
9240 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
9241 SourceLocation LParenLoc,
9242 SourceLocation EndLoc);
9243 /// \brief Called on well-formed 'thread_limit' clause.
9244 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
9245 SourceLocation StartLoc,
9246 SourceLocation LParenLoc,
9247 SourceLocation EndLoc);
9248 /// \brief Called on well-formed 'priority' clause.
9249 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
9250 SourceLocation LParenLoc,
9251 SourceLocation EndLoc);
9252 /// \brief Called on well-formed 'dist_schedule' clause.
9253 OMPClause *ActOnOpenMPDistScheduleClause(
9254 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
9255 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
9256 SourceLocation CommaLoc, SourceLocation EndLoc);
9257 /// \brief Called on well-formed 'defaultmap' clause.
9258 OMPClause *ActOnOpenMPDefaultmapClause(
9259 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
9260 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
9261 SourceLocation KindLoc, SourceLocation EndLoc);
9262 /// \brief Called on well-formed 'to' clause.
9263 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
9264 SourceLocation StartLoc,
9265 SourceLocation LParenLoc,
9266 SourceLocation EndLoc);
9267 /// \brief Called on well-formed 'from' clause.
9268 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
9269 SourceLocation StartLoc,
9270 SourceLocation LParenLoc,
9271 SourceLocation EndLoc);
9272 /// Called on well-formed 'use_device_ptr' clause.
9273 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
9274 SourceLocation StartLoc,
9275 SourceLocation LParenLoc,
9276 SourceLocation EndLoc);
9277 /// Called on well-formed 'is_device_ptr' clause.
9278 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
9279 SourceLocation StartLoc,
9280 SourceLocation LParenLoc,
9281 SourceLocation EndLoc);
9282
9283 /// \brief The kind of conversion being performed.
9284 enum CheckedConversionKind {
9285 /// \brief An implicit conversion.
9286 CCK_ImplicitConversion,
9287 /// \brief A C-style cast.
9288 CCK_CStyleCast,
9289 /// \brief A functional-style cast.
9290 CCK_FunctionalCast,
9291 /// \brief A cast other than a C-style cast.
9292 CCK_OtherCast
9293 };
9294
9295 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
9296 /// cast. If there is already an implicit cast, merge into the existing one.
9297 /// If isLvalue, the result of the cast is an lvalue.
9298 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
9299 ExprValueKind VK = VK_RValue,
9300 const CXXCastPath *BasePath = nullptr,
9301 CheckedConversionKind CCK
9302 = CCK_ImplicitConversion);
9303
9304 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
9305 /// to the conversion from scalar type ScalarTy to the Boolean type.
9306 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
9307
9308 /// IgnoredValueConversions - Given that an expression's result is
9309 /// syntactically ignored, perform any conversions that are
9310 /// required.
9311 ExprResult IgnoredValueConversions(Expr *E);
9312
9313 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9314 // functions and arrays to their respective pointers (C99 6.3.2.1).
9315 ExprResult UsualUnaryConversions(Expr *E);
9316
9317 /// CallExprUnaryConversions - a special case of an unary conversion
9318 /// performed on a function designator of a call expression.
9319 ExprResult CallExprUnaryConversions(Expr *E);
9320
9321 // DefaultFunctionArrayConversion - converts functions and arrays
9322 // to their respective pointers (C99 6.3.2.1).
9323 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9324
9325 // DefaultFunctionArrayLvalueConversion - converts functions and
9326 // arrays to their respective pointers and performs the
9327 // lvalue-to-rvalue conversion.
9328 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9329 bool Diagnose = true);
9330
9331 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9332 // the operand. This is DefaultFunctionArrayLvalueConversion,
9333 // except that it assumes the operand isn't of function or array
9334 // type.
9335 ExprResult DefaultLvalueConversion(Expr *E);
9336
9337 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9338 // do not have a prototype. Integer promotions are performed on each
9339 // argument, and arguments that have type float are promoted to double.
9340 ExprResult DefaultArgumentPromotion(Expr *E);
9341
9342 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9343 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9344 /// we don't have xvalues there.
9345 ExprResult TemporaryMaterializationConversion(Expr *E);
9346
9347 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9348 enum VariadicCallType {
9349 VariadicFunction,
9350 VariadicBlock,
9351 VariadicMethod,
9352 VariadicConstructor,
9353 VariadicDoesNotApply
9354 };
9355
9356 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9357 const FunctionProtoType *Proto,
9358 Expr *Fn);
9359
9360 // Used for determining in which context a type is allowed to be passed to a
9361 // vararg function.
9362 enum VarArgKind {
9363 VAK_Valid,
9364 VAK_ValidInCXX11,
9365 VAK_Undefined,
9366 VAK_MSVCUndefined,
9367 VAK_Invalid
9368 };
9369
9370 // Determines which VarArgKind fits an expression.
9371 VarArgKind isValidVarArgType(const QualType &Ty);
9372
9373 /// Check to see if the given expression is a valid argument to a variadic
9374 /// function, issuing a diagnostic if not.
9375 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9376
9377 /// Check to see if a given expression could have '.c_str()' called on it.
9378 bool hasCStrMethod(const Expr *E);
9379
9380 /// GatherArgumentsForCall - Collector argument expressions for various
9381 /// form of call prototypes.
9382 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9383 const FunctionProtoType *Proto,
9384 unsigned FirstParam, ArrayRef<Expr *> Args,
9385 SmallVectorImpl<Expr *> &AllArgs,
9386 VariadicCallType CallType = VariadicDoesNotApply,
9387 bool AllowExplicit = false,
9388 bool IsListInitialization = false);
9389
9390 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9391 // will create a runtime trap if the resulting type is not a POD type.
9392 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9393 FunctionDecl *FDecl);
9394
9395 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9396 // operands and then handles various conversions that are common to binary
9397 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9398 // routine returns the first non-arithmetic type found. The client is
9399 // responsible for emitting appropriate error diagnostics.
9400 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9401 bool IsCompAssign = false);
9402
9403 /// AssignConvertType - All of the 'assignment' semantic checks return this
9404 /// enum to indicate whether the assignment was allowed. These checks are
9405 /// done for simple assignments, as well as initialization, return from
9406 /// function, argument passing, etc. The query is phrased in terms of a
9407 /// source and destination type.
9408 enum AssignConvertType {
9409 /// Compatible - the types are compatible according to the standard.
9410 Compatible,
9411
9412 /// PointerToInt - The assignment converts a pointer to an int, which we
9413 /// accept as an extension.
9414 PointerToInt,
9415
9416 /// IntToPointer - The assignment converts an int to a pointer, which we
9417 /// accept as an extension.
9418 IntToPointer,
9419
9420 /// FunctionVoidPointer - The assignment is between a function pointer and
9421 /// void*, which the standard doesn't allow, but we accept as an extension.
9422 FunctionVoidPointer,
9423
9424 /// IncompatiblePointer - The assignment is between two pointers types that
9425 /// are not compatible, but we accept them as an extension.
9426 IncompatiblePointer,
9427
9428 /// IncompatiblePointerSign - The assignment is between two pointers types
9429 /// which point to integers which have a different sign, but are otherwise
9430 /// identical. This is a subset of the above, but broken out because it's by
9431 /// far the most common case of incompatible pointers.
9432 IncompatiblePointerSign,
9433
9434 /// CompatiblePointerDiscardsQualifiers - The assignment discards
9435 /// c/v/r qualifiers, which we accept as an extension.
9436 CompatiblePointerDiscardsQualifiers,
9437
9438 /// IncompatiblePointerDiscardsQualifiers - The assignment
9439 /// discards qualifiers that we don't permit to be discarded,
9440 /// like address spaces.
9441 IncompatiblePointerDiscardsQualifiers,
9442
9443 /// IncompatibleNestedPointerQualifiers - The assignment is between two
9444 /// nested pointer types, and the qualifiers other than the first two
9445 /// levels differ e.g. char ** -> const char **, but we accept them as an
9446 /// extension.
9447 IncompatibleNestedPointerQualifiers,
9448
9449 /// IncompatibleVectors - The assignment is between two vector types that
9450 /// have the same size, which we accept as an extension.
9451 IncompatibleVectors,
9452
9453 /// IntToBlockPointer - The assignment converts an int to a block
9454 /// pointer. We disallow this.
9455 IntToBlockPointer,
9456
9457 /// IncompatibleBlockPointer - The assignment is between two block
9458 /// pointers types that are not compatible.
9459 IncompatibleBlockPointer,
9460
9461 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9462 /// id type and something else (that is incompatible with it). For example,
9463 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9464 IncompatibleObjCQualifiedId,
9465
9466 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9467 /// object with __weak qualifier.
9468 IncompatibleObjCWeakRef,
9469
9470 /// Incompatible - We reject this conversion outright, it is invalid to
9471 /// represent it in the AST.
9472 Incompatible
9473 };
9474
9475 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9476 /// assignment conversion type specified by ConvTy. This returns true if the
9477 /// conversion was invalid or false if the conversion was accepted.
9478 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9479 SourceLocation Loc,
9480 QualType DstType, QualType SrcType,
9481 Expr *SrcExpr, AssignmentAction Action,
9482 bool *Complained = nullptr);
9483
9484 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9485 /// enum. If AllowMask is true, then we also allow the complement of a valid
9486 /// value, to be used as a mask.
9487 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9488 bool AllowMask) const;
9489
9490 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9491 /// integer not in the range of enum values.
9492 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9493 Expr *SrcExpr);
9494
9495 /// CheckAssignmentConstraints - Perform type checking for assignment,
9496 /// argument passing, variable initialization, and function return values.
9497 /// C99 6.5.16.
9498 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9499 QualType LHSType,
9500 QualType RHSType);
9501
9502 /// Check assignment constraints and optionally prepare for a conversion of
9503 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9504 /// is true.
9505 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9506 ExprResult &RHS,
9507 CastKind &Kind,
9508 bool ConvertRHS = true);
9509
9510 /// Check assignment constraints for an assignment of RHS to LHSType.
9511 ///
9512 /// \param LHSType The destination type for the assignment.
9513 /// \param RHS The source expression for the assignment.
9514 /// \param Diagnose If \c true, diagnostics may be produced when checking
9515 /// for assignability. If a diagnostic is produced, \p RHS will be
9516 /// set to ExprError(). Note that this function may still return
9517 /// without producing a diagnostic, even for an invalid assignment.
9518 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9519 /// in an audited Core Foundation API and does not need to be checked
9520 /// for ARC retain issues.
9521 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9522 /// conversions necessary to perform the assignment. If \c false,
9523 /// \p Diagnose must also be \c false.
9524 AssignConvertType CheckSingleAssignmentConstraints(
9525 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9526 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9527
9528 // \brief If the lhs type is a transparent union, check whether we
9529 // can initialize the transparent union with the given expression.
9530 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9531 ExprResult &RHS);
9532
9533 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9534
9535 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9536
9537 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9538 AssignmentAction Action,
9539 bool AllowExplicit = false);
9540 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9541 AssignmentAction Action,
9542 bool AllowExplicit,
9543 ImplicitConversionSequence& ICS);
9544 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9545 const ImplicitConversionSequence& ICS,
9546 AssignmentAction Action,
9547 CheckedConversionKind CCK
9548 = CCK_ImplicitConversion);
9549 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9550 const StandardConversionSequence& SCS,
9551 AssignmentAction Action,
9552 CheckedConversionKind CCK);
9553
9554 /// the following "Check" methods will return a valid/converted QualType
9555 /// or a null QualType (indicating an error diagnostic was issued).
9556
9557 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9558 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9559 ExprResult &RHS);
9560 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9561 ExprResult &RHS);
9562 QualType CheckPointerToMemberOperands( // C++ 5.5
9563 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9564 SourceLocation OpLoc, bool isIndirect);
9565 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9566 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9567 bool IsDivide);
9568 QualType CheckRemainderOperands( // C99 6.5.5
9569 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9570 bool IsCompAssign = false);
9571 QualType CheckAdditionOperands( // C99 6.5.6
9572 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9573 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9574 QualType CheckSubtractionOperands( // C99 6.5.6
9575 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9576 QualType* CompLHSTy = nullptr);
9577 QualType CheckShiftOperands( // C99 6.5.7
9578 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9579 BinaryOperatorKind Opc, bool IsCompAssign = false);
9580 QualType CheckCompareOperands( // C99 6.5.8/9
9581 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9582 BinaryOperatorKind Opc, bool isRelational);
9583 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9584 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9585 BinaryOperatorKind Opc);
9586 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9587 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9588 BinaryOperatorKind Opc);
9589 // CheckAssignmentOperands is used for both simple and compound assignment.
9590 // For simple assignment, pass both expressions and a null converted type.
9591 // For compound assignment, pass both expressions and the converted type.
9592 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9593 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9594
9595 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9596 UnaryOperatorKind Opcode, Expr *Op);
9597 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9598 BinaryOperatorKind Opcode,
9599 Expr *LHS, Expr *RHS);
9600 ExprResult checkPseudoObjectRValue(Expr *E);
9601 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9602
9603 QualType CheckConditionalOperands( // C99 6.5.15
9604 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9605 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9606 QualType CXXCheckConditionalOperands( // C++ 5.16
9607 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9608 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9609 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9610 bool ConvertArgs = true);
9611 QualType FindCompositePointerType(SourceLocation Loc,
9612 ExprResult &E1, ExprResult &E2,
9613 bool ConvertArgs = true) {
9614 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9615 QualType Composite =
9616 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
8
Calling 'Sema::FindCompositePointerType'
9617 E1 = E1Tmp;
9618 E2 = E2Tmp;
9619 return Composite;
9620 }
9621
9622 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9623 SourceLocation QuestionLoc);
9624
9625 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9626 SourceLocation QuestionLoc);
9627
9628 void DiagnoseAlwaysNonNullPointer(Expr *E,
9629 Expr::NullPointerConstantKind NullType,
9630 bool IsEqual, SourceRange Range);
9631
9632 /// type checking for vector binary operators.
9633 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9634 SourceLocation Loc, bool IsCompAssign,
9635 bool AllowBothBool, bool AllowBoolConversion);
9636 QualType GetSignedVectorType(QualType V);
9637 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9638 SourceLocation Loc,
9639 BinaryOperatorKind Opc);
9640 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9641 SourceLocation Loc);
9642
9643 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9644 bool isLaxVectorConversion(QualType srcType, QualType destType);
9645
9646 /// type checking declaration initializers (C99 6.7.8)
9647 bool CheckForConstantInitializer(Expr *e, QualType t);
9648
9649 // type checking C++ declaration initializers (C++ [dcl.init]).
9650
9651 /// ReferenceCompareResult - Expresses the result of comparing two
9652 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9653 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9654 enum ReferenceCompareResult {
9655 /// Ref_Incompatible - The two types are incompatible, so direct
9656 /// reference binding is not possible.
9657 Ref_Incompatible = 0,
9658 /// Ref_Related - The two types are reference-related, which means
9659 /// that their unqualified forms (T1 and T2) are either the same
9660 /// or T1 is a base class of T2.
9661 Ref_Related,
9662 /// Ref_Compatible - The two types are reference-compatible.
9663 Ref_Compatible
9664 };
9665
9666 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9667 QualType T1, QualType T2,
9668 bool &DerivedToBase,
9669 bool &ObjCConversion,
9670 bool &ObjCLifetimeConversion);
9671
9672 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9673 Expr *CastExpr, CastKind &CastKind,
9674 ExprValueKind &VK, CXXCastPath &Path);
9675
9676 /// \brief Force an expression with unknown-type to an expression of the
9677 /// given type.
9678 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9679
9680 /// \brief Type-check an expression that's being passed to an
9681 /// __unknown_anytype parameter.
9682 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9683 Expr *result, QualType &paramType);
9684
9685 // CheckVectorCast - check type constraints for vectors.
9686 // Since vectors are an extension, there are no C standard reference for this.
9687 // We allow casting between vectors and integer datatypes of the same size.
9688 // returns true if the cast is invalid
9689 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9690 CastKind &Kind);
9691
9692 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9693 /// implicit casts if necessary.
9694 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9695
9696 // CheckExtVectorCast - check type constraints for extended vectors.
9697 // Since vectors are an extension, there are no C standard reference for this.
9698 // We allow casting between vectors and integer datatypes of the same size,
9699 // or vectors and the element type of that vector.
9700 // returns the cast expr
9701 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9702 CastKind &Kind);
9703
9704 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9705 SourceLocation LParenLoc,
9706 Expr *CastExpr,
9707 SourceLocation RParenLoc);
9708
9709 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9710
9711 /// \brief Checks for invalid conversions and casts between
9712 /// retainable pointers and other pointer kinds for ARC and Weak.
9713 ARCConversionResult CheckObjCConversion(SourceRange castRange,
9714 QualType castType, Expr *&op,
9715 CheckedConversionKind CCK,
9716 bool Diagnose = true,
9717 bool DiagnoseCFAudited = false,
9718 BinaryOperatorKind Opc = BO_PtrMemD
9719 );
9720
9721 Expr *stripARCUnbridgedCast(Expr *e);
9722 void diagnoseARCUnbridgedCast(Expr *e);
9723
9724 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9725 QualType ExprType);
9726
9727 /// checkRetainCycles - Check whether an Objective-C message send
9728 /// might create an obvious retain cycle.
9729 void checkRetainCycles(ObjCMessageExpr *msg);
9730 void checkRetainCycles(Expr *receiver, Expr *argument);
9731 void checkRetainCycles(VarDecl *Var, Expr *Init);
9732
9733 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9734 /// to weak/__unsafe_unretained type.
9735 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9736
9737 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9738 /// to weak/__unsafe_unretained expression.
9739 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9740
9741 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9742 /// \param Method - May be null.
9743 /// \param [out] ReturnType - The return type of the send.
9744 /// \return true iff there were any incompatible types.
9745 bool CheckMessageArgumentTypes(QualType ReceiverType,
9746 MultiExprArg Args, Selector Sel,
9747 ArrayRef<SourceLocation> SelectorLocs,
9748 ObjCMethodDecl *Method, bool isClassMessage,
9749 bool isSuperMessage,
9750 SourceLocation lbrac, SourceLocation rbrac,
9751 SourceRange RecRange,
9752 QualType &ReturnType, ExprValueKind &VK);
9753
9754 /// \brief Determine the result of a message send expression based on
9755 /// the type of the receiver, the method expected to receive the message,
9756 /// and the form of the message send.
9757 QualType getMessageSendResultType(QualType ReceiverType,
9758 ObjCMethodDecl *Method,
9759 bool isClassMessage, bool isSuperMessage);
9760
9761 /// \brief If the given expression involves a message send to a method
9762 /// with a related result type, emit a note describing what happened.
9763 void EmitRelatedResultTypeNote(const Expr *E);
9764
9765 /// \brief Given that we had incompatible pointer types in a return
9766 /// statement, check whether we're in a method with a related result
9767 /// type, and if so, emit a note describing what happened.
9768 void EmitRelatedResultTypeNoteForReturn(QualType destType);
9769
9770 class ConditionResult {
9771 Decl *ConditionVar;
9772 FullExprArg Condition;
9773 bool Invalid;
9774 bool HasKnownValue;
9775 bool KnownValue;
9776
9777 friend class Sema;
9778 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9779 bool IsConstexpr)
9780 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9781 HasKnownValue(IsConstexpr && Condition.get() &&
9782 !Condition.get()->isValueDependent()),
9783 KnownValue(HasKnownValue &&
9784 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9785 explicit ConditionResult(bool Invalid)
9786 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9787 HasKnownValue(false), KnownValue(false) {}
9788
9789 public:
9790 ConditionResult() : ConditionResult(false) {}
9791 bool isInvalid() const { return Invalid; }
9792 std::pair<VarDecl *, Expr *> get() const {
9793 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9794 Condition.get());
9795 }
9796 llvm::Optional<bool> getKnownValue() const {
9797 if (!HasKnownValue)
9798 return None;
9799 return KnownValue;
9800 }
9801 };
9802 static ConditionResult ConditionError() { return ConditionResult(true); }
9803
9804 enum class ConditionKind {
9805 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9806 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9807 Switch ///< An integral condition for a 'switch' statement.
9808 };
9809
9810 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9811 Expr *SubExpr, ConditionKind CK);
9812
9813 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9814 SourceLocation StmtLoc,
9815 ConditionKind CK);
9816
9817 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9818
9819 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9820 SourceLocation StmtLoc,
9821 ConditionKind CK);
9822 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9823
9824 /// CheckBooleanCondition - Diagnose problems involving the use of
9825 /// the given expression as a boolean condition (e.g. in an if
9826 /// statement). Also performs the standard function and array
9827 /// decays, possibly changing the input variable.
9828 ///
9829 /// \param Loc - A location associated with the condition, e.g. the
9830 /// 'if' keyword.
9831 /// \return true iff there were any errors
9832 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9833 bool IsConstexpr = false);
9834
9835 /// DiagnoseAssignmentAsCondition - Given that an expression is
9836 /// being used as a boolean condition, warn if it's an assignment.
9837 void DiagnoseAssignmentAsCondition(Expr *E);
9838
9839 /// \brief Redundant parentheses over an equality comparison can indicate
9840 /// that the user intended an assignment used as condition.
9841 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9842
9843 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9844 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9845
9846 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9847 /// the specified width and sign. If an overflow occurs, detect it and emit
9848 /// the specified diagnostic.
9849 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9850 unsigned NewWidth, bool NewSign,
9851 SourceLocation Loc, unsigned DiagID);
9852
9853 /// Checks that the Objective-C declaration is declared in the global scope.
9854 /// Emits an error and marks the declaration as invalid if it's not declared
9855 /// in the global scope.
9856 bool CheckObjCDeclScope(Decl *D);
9857
9858 /// \brief Abstract base class used for diagnosing integer constant
9859 /// expression violations.
9860 class VerifyICEDiagnoser {
9861 public:
9862 bool Suppress;
9863
9864 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9865
9866 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9867 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9868 virtual ~VerifyICEDiagnoser() { }
9869 };
9870
9871 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9872 /// and reports the appropriate diagnostics. Returns false on success.
9873 /// Can optionally return the value of the expression.
9874 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9875 VerifyICEDiagnoser &Diagnoser,
9876 bool AllowFold = true);
9877 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9878 unsigned DiagID,
9879 bool AllowFold = true);
9880 ExprResult VerifyIntegerConstantExpression(Expr *E,
9881 llvm::APSInt *Result = nullptr);
9882
9883 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9884 /// the correct width, and that the field type is valid.
9885 /// Returns false on success.
9886 /// Can optionally return whether the bit-field is of width 0
9887 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9888 QualType FieldTy, bool IsMsStruct,
9889 Expr *BitWidth, bool *ZeroWidth = nullptr);
9890
9891private:
9892 unsigned ForceCUDAHostDeviceDepth = 0;
9893
9894public:
9895 /// Increments our count of the number of times we've seen a pragma forcing
9896 /// functions to be __host__ __device__. So long as this count is greater
9897 /// than zero, all functions encountered will be __host__ __device__.
9898 void PushForceCUDAHostDevice();
9899
9900 /// Decrements our count of the number of times we've seen a pragma forcing
9901 /// functions to be __host__ __device__. Returns false if the count is 0
9902 /// before incrementing, so you can emit an error.
9903 bool PopForceCUDAHostDevice();
9904
9905 /// Diagnostics that are emitted only if we discover that the given function
9906 /// must be codegen'ed. Because handling these correctly adds overhead to
9907 /// compilation, this is currently only enabled for CUDA compilations.
9908 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9909 std::vector<PartialDiagnosticAt>>
9910 CUDADeferredDiags;
9911
9912 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
9913 /// key in a hashtable, both the FD and location are hashed.
9914 struct FunctionDeclAndLoc {
9915 CanonicalDeclPtr<FunctionDecl> FD;
9916 SourceLocation Loc;
9917 };
9918
9919 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9920 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
9921 /// same deferred diag twice.
9922 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9923
9924 /// An inverse call graph, mapping known-emitted functions to one of their
9925 /// known-emitted callers (plus the location of the call).
9926 ///
9927 /// Functions that we can tell a priori must be emitted aren't added to this
9928 /// map.
9929 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9930 /* Caller = */ FunctionDeclAndLoc>
9931 CUDAKnownEmittedFns;
9932
9933 /// A partial call graph maintained during CUDA compilation to support
9934 /// deferred diagnostics.
9935 ///
9936 /// Functions are only added here if, at the time they're considered, they are
9937 /// not known-emitted. As soon as we discover that a function is
9938 /// known-emitted, we remove it and everything it transitively calls from this
9939 /// set and add those functions to CUDAKnownEmittedFns.
9940 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9941 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9942 SourceLocation>>
9943 CUDACallGraph;
9944
9945 /// Diagnostic builder for CUDA errors which may or may not be deferred.
9946 ///
9947 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9948 /// which are not allowed to appear inside __device__ functions and are
9949 /// allowed to appear in __host__ __device__ functions only if the host+device
9950 /// function is never codegen'ed.
9951 ///
9952 /// To handle this, we use the notion of "deferred diagnostics", where we
9953 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9954 ///
9955 /// This class lets you emit either a regular diagnostic, a deferred
9956 /// diagnostic, or no diagnostic at all, according to an argument you pass to
9957 /// its constructor, thus simplifying the process of creating these "maybe
9958 /// deferred" diagnostics.
9959 class CUDADiagBuilder {
9960 public:
9961 enum Kind {
9962 /// Emit no diagnostics.
9963 K_Nop,
9964 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9965 K_Immediate,
9966 /// Emit the diagnostic immediately, and, if it's a warning or error, also
9967 /// emit a call stack showing how this function can be reached by an a
9968 /// priori known-emitted function.
9969 K_ImmediateWithCallStack,
9970 /// Create a deferred diagnostic, which is emitted only if the function
9971 /// it's attached to is codegen'ed. Also emit a call stack as with
9972 /// K_ImmediateWithCallStack.
9973 K_Deferred
9974 };
9975
9976 CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9977 FunctionDecl *Fn, Sema &S);
9978 ~CUDADiagBuilder();
9979
9980 /// Convertible to bool: True if we immediately emitted an error, false if
9981 /// we didn't emit an error or we created a deferred error.
9982 ///
9983 /// Example usage:
9984 ///
9985 /// if (CUDADiagBuilder(...) << foo << bar)
9986 /// return ExprError();
9987 ///
9988 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9989 /// want to use these instead of creating a CUDADiagBuilder yourself.
9990 operator bool() const { return ImmediateDiag.hasValue(); }
9991
9992 template <typename T>
9993 friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9994 const T &Value) {
9995 if (Diag.ImmediateDiag.hasValue())
9996 *Diag.ImmediateDiag << Value;
9997 else if (Diag.PartialDiag.hasValue())
9998 *Diag.PartialDiag << Value;
9999 return Diag;
10000 }
10001
10002 private:
10003 Sema &S;
10004 SourceLocation Loc;
10005 unsigned DiagID;
10006 FunctionDecl *Fn;
10007 bool ShowCallStack;
10008
10009 // Invariant: At most one of these Optionals has a value.
10010 // FIXME: Switch these to a Variant once that exists.
10011 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
10012 llvm::Optional<PartialDiagnostic> PartialDiag;
10013 };
10014
10015 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
10016 /// is "used as device code".
10017 ///
10018 /// - If CurContext is a __host__ function, does not emit any diagnostics.
10019 /// - If CurContext is a __device__ or __global__ function, emits the
10020 /// diagnostics immediately.
10021 /// - If CurContext is a __host__ __device__ function and we are compiling for
10022 /// the device, creates a diagnostic which is emitted if and when we realize
10023 /// that the function will be codegen'ed.
10024 ///
10025 /// Example usage:
10026 ///
10027 /// // Variable-length arrays are not allowed in CUDA device code.
10028 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
10029 /// return ExprError();
10030 /// // Otherwise, continue parsing as normal.
10031 CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
10032
10033 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
10034 /// is "used as host code".
10035 ///
10036 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
10037 CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
10038
10039 enum CUDAFunctionTarget {
10040 CFT_Device,
10041 CFT_Global,
10042 CFT_Host,
10043 CFT_HostDevice,
10044 CFT_InvalidTarget
10045 };
10046
10047 /// Determines whether the given function is a CUDA device/host/kernel/etc.
10048 /// function.
10049 ///
10050 /// Use this rather than examining the function's attributes yourself -- you
10051 /// will get it wrong. Returns CFT_Host if D is null.
10052 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
10053 bool IgnoreImplicitHDAttr = false);
10054 CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
10055
10056 /// Gets the CUDA target for the current context.
10057 CUDAFunctionTarget CurrentCUDATarget() {
10058 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
10059 }
10060
10061 // CUDA function call preference. Must be ordered numerically from
10062 // worst to best.
10063 enum CUDAFunctionPreference {
10064 CFP_Never, // Invalid caller/callee combination.
10065 CFP_WrongSide, // Calls from host-device to host or device
10066 // function that do not match current compilation
10067 // mode.
10068 CFP_HostDevice, // Any calls to host/device functions.
10069 CFP_SameSide, // Calls from host-device to host or device
10070 // function matching current compilation mode.
10071 CFP_Native, // host-to-host or device-to-device calls.
10072 };
10073
10074 /// Identifies relative preference of a given Caller/Callee
10075 /// combination, based on their host/device attributes.
10076 /// \param Caller function which needs address of \p Callee.
10077 /// nullptr in case of global context.
10078 /// \param Callee target function
10079 ///
10080 /// \returns preference value for particular Caller/Callee combination.
10081 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
10082 const FunctionDecl *Callee);
10083
10084 /// Determines whether Caller may invoke Callee, based on their CUDA
10085 /// host/device attributes. Returns false if the call is not allowed.
10086 ///
10087 /// Note: Will return true for CFP_WrongSide calls. These may appear in
10088 /// semantically correct CUDA programs, but only if they're never codegen'ed.
10089 bool IsAllowedCUDACall(const FunctionDecl *Caller,
10090 const FunctionDecl *Callee) {
10091 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
10092 }
10093
10094 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
10095 /// depending on FD and the current compilation settings.
10096 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
10097 const LookupResult &Previous);
10098
10099public:
10100 /// Check whether we're allowed to call Callee from the current context.
10101 ///
10102 /// - If the call is never allowed in a semantically-correct program
10103 /// (CFP_Never), emits an error and returns false.
10104 ///
10105 /// - If the call is allowed in semantically-correct programs, but only if
10106 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
10107 /// be emitted if and when the caller is codegen'ed, and returns true.
10108 ///
10109 /// Will only create deferred diagnostics for a given SourceLocation once,
10110 /// so you can safely call this multiple times without generating duplicate
10111 /// deferred errors.
10112 ///
10113 /// - Otherwise, returns true without emitting any diagnostics.
10114 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
10115
10116 /// Set __device__ or __host__ __device__ attributes on the given lambda
10117 /// operator() method.
10118 ///
10119 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
10120 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
10121 /// functions become __host__ __device__ themselves.
10122 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
10123
10124 /// Finds a function in \p Matches with highest calling priority
10125 /// from \p Caller context and erases all functions with lower
10126 /// calling priority.
10127 void EraseUnwantedCUDAMatches(
10128 const FunctionDecl *Caller,
10129 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
10130
10131 /// Given a implicit special member, infer its CUDA target from the
10132 /// calls it needs to make to underlying base/field special members.
10133 /// \param ClassDecl the class for which the member is being created.
10134 /// \param CSM the kind of special member.
10135 /// \param MemberDecl the special member itself.
10136 /// \param ConstRHS true if this is a copy operation with a const object on
10137 /// its RHS.
10138 /// \param Diagnose true if this call should emit diagnostics.
10139 /// \return true if there was an error inferring.
10140 /// The result of this call is implicit CUDA target attribute(s) attached to
10141 /// the member declaration.
10142 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
10143 CXXSpecialMember CSM,
10144 CXXMethodDecl *MemberDecl,
10145 bool ConstRHS,
10146 bool Diagnose);
10147
10148 /// \return true if \p CD can be considered empty according to CUDA
10149 /// (E.2.3.1 in CUDA 7.5 Programming guide).
10150 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
10151 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
10152
10153 /// Check whether NewFD is a valid overload for CUDA. Emits
10154 /// diagnostics and invalidates NewFD if not.
10155 void checkCUDATargetOverload(FunctionDecl *NewFD,
10156 const LookupResult &Previous);
10157 /// Copies target attributes from the template TD to the function FD.
10158 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
10159
10160 /// \name Code completion
10161 //@{
10162 /// \brief Describes the context in which code completion occurs.
10163 enum ParserCompletionContext {
10164 /// \brief Code completion occurs at top-level or namespace context.
10165 PCC_Namespace,
10166 /// \brief Code completion occurs within a class, struct, or union.
10167 PCC_Class,
10168 /// \brief Code completion occurs within an Objective-C interface, protocol,
10169 /// or category.
10170 PCC_ObjCInterface,
10171 /// \brief Code completion occurs within an Objective-C implementation or
10172 /// category implementation
10173 PCC_ObjCImplementation,
10174 /// \brief Code completion occurs within the list of instance variables
10175 /// in an Objective-C interface, protocol, category, or implementation.
10176 PCC_ObjCInstanceVariableList,
10177 /// \brief Code completion occurs following one or more template
10178 /// headers.
10179 PCC_Template,
10180 /// \brief Code completion occurs following one or more template
10181 /// headers within a class.
10182 PCC_MemberTemplate,
10183 /// \brief Code completion occurs within an expression.
10184 PCC_Expression,
10185 /// \brief Code completion occurs within a statement, which may
10186 /// also be an expression or a declaration.
10187 PCC_Statement,
10188 /// \brief Code completion occurs at the beginning of the
10189 /// initialization statement (or expression) in a for loop.
10190 PCC_ForInit,
10191 /// \brief Code completion occurs within the condition of an if,
10192 /// while, switch, or for statement.
10193 PCC_Condition,
10194 /// \brief Code completion occurs within the body of a function on a
10195 /// recovery path, where we do not have a specific handle on our position
10196 /// in the grammar.
10197 PCC_RecoveryInFunction,
10198 /// \brief Code completion occurs where only a type is permitted.
10199 PCC_Type,
10200 /// \brief Code completion occurs in a parenthesized expression, which
10201 /// might also be a type cast.
10202 PCC_ParenthesizedExpression,
10203 /// \brief Code completion occurs within a sequence of declaration
10204 /// specifiers within a function, method, or block.
10205 PCC_LocalDeclarationSpecifiers
10206 };
10207
10208 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
10209 void CodeCompleteOrdinaryName(Scope *S,
10210 ParserCompletionContext CompletionContext);
10211 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
10212 bool AllowNonIdentifiers,
10213 bool AllowNestedNameSpecifiers);
10214
10215 struct CodeCompleteExpressionData;
10216 void CodeCompleteExpression(Scope *S,
10217 const CodeCompleteExpressionData &Data);
10218 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
10219 SourceLocation OpLoc, bool IsArrow,
10220 bool IsBaseExprStatement);
10221 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
10222 void CodeCompleteTag(Scope *S, unsigned TagSpec);
10223 void CodeCompleteTypeQualifiers(DeclSpec &DS);
10224 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
10225 const VirtSpecifiers *VS = nullptr);
10226 void CodeCompleteBracketDeclarator(Scope *S);
10227 void CodeCompleteCase(Scope *S);
10228 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
10229 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
10230 ArrayRef<Expr *> Args);
10231 void CodeCompleteInitializer(Scope *S, Decl *D);
10232 void CodeCompleteReturn(Scope *S);
10233 void CodeCompleteAfterIf(Scope *S);
10234 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
10235
10236 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
10237 bool EnteringContext);
10238 void CodeCompleteUsing(Scope *S);
10239 void CodeCompleteUsingDirective(Scope *S);
10240 void CodeCompleteNamespaceDecl(Scope *S);
10241 void CodeCompleteNamespaceAliasDecl(Scope *S);
10242 void CodeCompleteOperatorName(Scope *S);
10243 void CodeCompleteConstructorInitializer(
10244 Decl *Constructor,
10245 ArrayRef<CXXCtorInitializer *> Initializers);
10246
10247 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
10248 bool AfterAmpersand);
10249
10250 void CodeCompleteObjCAtDirective(Scope *S);
10251 void CodeCompleteObjCAtVisibility(Scope *S);
10252 void CodeCompleteObjCAtStatement(Scope *S);
10253 void CodeCompleteObjCAtExpression(Scope *S);
10254 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
10255 void CodeCompleteObjCPropertyGetter(Scope *S);
10256 void CodeCompleteObjCPropertySetter(Scope *S);
10257 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
10258 bool IsParameter);
10259 void CodeCompleteObjCMessageReceiver(Scope *S);
10260 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
10261 ArrayRef<IdentifierInfo *> SelIdents,
10262 bool AtArgumentExpression);
10263 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
10264 ArrayRef<IdentifierInfo *> SelIdents,
10265 bool AtArgumentExpression,
10266 bool IsSuper = false);
10267 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
10268 ArrayRef<IdentifierInfo *> SelIdents,
10269 bool AtArgumentExpression,
10270 ObjCInterfaceDecl *Super = nullptr);
10271 void CodeCompleteObjCForCollection(Scope *S,
10272 DeclGroupPtrTy IterationVar);
10273 void CodeCompleteObjCSelector(Scope *S,
10274 ArrayRef<IdentifierInfo *> SelIdents);
10275 void CodeCompleteObjCProtocolReferences(
10276 ArrayRef<IdentifierLocPair> Protocols);
10277 void CodeCompleteObjCProtocolDecl(Scope *S);
10278 void CodeCompleteObjCInterfaceDecl(Scope *S);
10279 void CodeCompleteObjCSuperclass(Scope *S,
10280 IdentifierInfo *ClassName,
10281 SourceLocation ClassNameLoc);
10282 void CodeCompleteObjCImplementationDecl(Scope *S);
10283 void CodeCompleteObjCInterfaceCategory(Scope *S,
10284 IdentifierInfo *ClassName,
10285 SourceLocation ClassNameLoc);
10286 void CodeCompleteObjCImplementationCategory(Scope *S,
10287 IdentifierInfo *ClassName,
10288 SourceLocation ClassNameLoc);
10289 void CodeCompleteObjCPropertyDefinition(Scope *S);
10290 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
10291 IdentifierInfo *PropertyName);
10292 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
10293 ParsedType ReturnType);
10294 void CodeCompleteObjCMethodDeclSelector(Scope *S,
10295 bool IsInstanceMethod,
10296 bool AtParameterName,
10297 ParsedType ReturnType,
10298 ArrayRef<IdentifierInfo *> SelIdents);
10299 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
10300 SourceLocation ClassNameLoc,
10301 bool IsBaseExprStatement);
10302 void CodeCompletePreprocessorDirective(bool InConditional);
10303 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
10304 void CodeCompletePreprocessorMacroName(bool IsDefinition);
10305 void CodeCompletePreprocessorExpression();
10306 void CodeCompletePreprocessorMacroArgument(Scope *S,
10307 IdentifierInfo *Macro,
10308 MacroInfo *MacroInfo,
10309 unsigned Argument);
10310 void CodeCompleteNaturalLanguage();
10311 void CodeCompleteAvailabilityPlatformName();
10312 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
10313 CodeCompletionTUInfo &CCTUInfo,
10314 SmallVectorImpl<CodeCompletionResult> &Results);
10315 //@}
10316
10317 //===--------------------------------------------------------------------===//
10318 // Extra semantic analysis beyond the C type system
10319
10320public:
10321 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10322 unsigned ByteNo) const;
10323
10324private:
10325 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10326 const ArraySubscriptExpr *ASE=nullptr,
10327 bool AllowOnePastEnd=true, bool IndexNegated=false);
10328 void CheckArrayAccess(const Expr *E);
10329 // Used to grab the relevant information from a FormatAttr and a
10330 // FunctionDeclaration.
10331 struct FormatStringInfo {
10332 unsigned FormatIdx;
10333 unsigned FirstDataArg;
10334 bool HasVAListArg;
10335 };
10336
10337 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10338 FormatStringInfo *FSI);
10339 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10340 const FunctionProtoType *Proto);
10341 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10342 ArrayRef<const Expr *> Args);
10343 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10344 const FunctionProtoType *Proto);
10345 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10346 void CheckConstructorCall(FunctionDecl *FDecl,
10347 ArrayRef<const Expr *> Args,
10348 const FunctionProtoType *Proto,
10349 SourceLocation Loc);
10350
10351 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10352 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10353 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10354 VariadicCallType CallType);
10355
10356 bool CheckObjCString(Expr *Arg);
10357 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10358
10359 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10360 unsigned BuiltinID, CallExpr *TheCall);
10361
10362 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10363 unsigned MaxWidth);
10364 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10365 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10366
10367 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10368 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10369 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10370 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10371 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10372 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10373 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10374
10375 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
10376 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
10377 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10378 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10379 bool SemaBuiltinVSX(CallExpr *TheCall);
10380 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10381
10382public:
10383 // Used by C++ template instantiation.
10384 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10385 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10386 SourceLocation BuiltinLoc,
10387 SourceLocation RParenLoc);
10388
10389private:
10390 bool SemaBuiltinPrefetch(CallExpr *TheCall);
10391 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10392 bool SemaBuiltinAssume(CallExpr *TheCall);
10393 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10394 bool SemaBuiltinLongjmp(CallExpr *TheCall);
10395 bool SemaBuiltinSetjmp(CallExpr *TheCall);
10396 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10397 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10398 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10399 AtomicExpr::AtomicOp Op);
10400 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
10401 bool IsDelete);
10402 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10403 llvm::APSInt &Result);
10404 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10405 int Low, int High);
10406 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10407 unsigned Multiple);
10408 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10409 int ArgNum, unsigned ExpectedFieldNum,
10410 bool AllowName);
10411public:
10412 enum FormatStringType {
10413 FST_Scanf,
10414 FST_Printf,
10415 FST_NSString,
10416 FST_Strftime,
10417 FST_Strfmon,
10418 FST_Kprintf,
10419 FST_FreeBSDKPrintf,
10420 FST_OSTrace,
10421 FST_OSLog,
10422 FST_Unknown
10423 };
10424 static FormatStringType GetFormatStringType(const FormatAttr *Format);
10425
10426 bool FormatStringHasSArg(const StringLiteral *FExpr);
10427
10428 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10429
10430private:
10431 bool CheckFormatArguments(const FormatAttr *Format,
10432 ArrayRef<const Expr *> Args,
10433 bool IsCXXMember,
10434 VariadicCallType CallType,
10435 SourceLocation Loc, SourceRange Range,
10436 llvm::SmallBitVector &CheckedVarArgs);
10437 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10438 bool HasVAListArg, unsigned format_idx,
10439 unsigned firstDataArg, FormatStringType Type,
10440 VariadicCallType CallType,
10441 SourceLocation Loc, SourceRange range,
10442 llvm::SmallBitVector &CheckedVarArgs);
10443
10444 void CheckAbsoluteValueFunction(const CallExpr *Call,
10445 const FunctionDecl *FDecl);
10446
10447 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10448
10449 void CheckMemaccessArguments(const CallExpr *Call,
10450 unsigned BId,
10451 IdentifierInfo *FnName);
10452
10453 void CheckStrlcpycatArguments(const CallExpr *Call,
10454 IdentifierInfo *FnName);
10455
10456 void CheckStrncatArguments(const CallExpr *Call,
10457 IdentifierInfo *FnName);
10458
10459 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10460 SourceLocation ReturnLoc,
10461 bool isObjCMethod = false,
10462 const AttrVec *Attrs = nullptr,
10463 const FunctionDecl *FD = nullptr);
10464
10465public:
10466 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
10467
10468private:
10469 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10470 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10471 void CheckForIntOverflow(Expr *E);
10472 void CheckUnsequencedOperations(Expr *E);
10473
10474 /// \brief Perform semantic checks on a completed expression. This will either
10475 /// be a full-expression or a default argument expression.
10476 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10477 bool IsConstexpr = false);
10478
10479 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10480 Expr *Init);
10481
10482 /// Check if there is a field shadowing.
10483 void CheckShadowInheritedFields(const SourceLocation &Loc,
10484 DeclarationName FieldName,
10485 const CXXRecordDecl *RD);
10486
10487 /// \brief Check if the given expression contains 'break' or 'continue'
10488 /// statement that produces control flow different from GCC.
10489 void CheckBreakContinueBinding(Expr *E);
10490
10491 /// \brief Check whether receiver is mutable ObjC container which
10492 /// attempts to add itself into the container
10493 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10494
10495 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10496 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10497 bool DeleteWasArrayForm);
10498public:
10499 /// \brief Register a magic integral constant to be used as a type tag.
10500 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10501 uint64_t MagicValue, QualType Type,
10502 bool LayoutCompatible, bool MustBeNull);
10503
10504 struct TypeTagData {
10505 TypeTagData() {}
10506
10507 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10508 Type(Type), LayoutCompatible(LayoutCompatible),
10509 MustBeNull(MustBeNull)
10510 {}
10511
10512 QualType Type;
10513
10514 /// If true, \c Type should be compared with other expression's types for
10515 /// layout-compatibility.
10516 unsigned LayoutCompatible : 1;
10517 unsigned MustBeNull : 1;
10518 };
10519
10520 /// A pair of ArgumentKind identifier and magic value. This uniquely
10521 /// identifies the magic value.
10522 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10523
10524private:
10525 /// \brief A map from magic value to type information.
10526 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10527 TypeTagForDatatypeMagicValues;
10528
10529 /// \brief Peform checks on a call of a function with argument_with_type_tag
10530 /// or pointer_with_type_tag attributes.
10531 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10532 const ArrayRef<const Expr *> ExprArgs,
10533 SourceLocation CallSiteLoc);
10534
10535 /// \brief Check if we are taking the address of a packed field
10536 /// as this may be a problem if the pointer value is dereferenced.
10537 void CheckAddressOfPackedMember(Expr *rhs);
10538
10539 /// \brief The parser's current scope.
10540 ///
10541 /// The parser maintains this state here.
10542 Scope *CurScope;
10543
10544 mutable IdentifierInfo *Ident_super;
10545 mutable IdentifierInfo *Ident___float128;
10546
10547 /// Nullability type specifiers.
10548 IdentifierInfo *Ident__Nonnull = nullptr;
10549 IdentifierInfo *Ident__Nullable = nullptr;
10550 IdentifierInfo *Ident__Null_unspecified = nullptr;
10551
10552 IdentifierInfo *Ident_NSError = nullptr;
10553
10554 /// \brief The handler for the FileChanged preprocessor events.
10555 ///
10556 /// Used for diagnostics that implement custom semantic analysis for #include
10557 /// directives, like -Wpragma-pack.
10558 sema::SemaPPCallbacks *SemaPPCallbackHandler;
10559
10560protected:
10561 friend class Parser;
10562 friend class InitializationSequence;
10563 friend class ASTReader;
10564 friend class ASTDeclReader;
10565 friend class ASTWriter;
10566
10567public:
10568 /// Retrieve the keyword associated
10569 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10570
10571 /// The struct behind the CFErrorRef pointer.
10572 RecordDecl *CFError = nullptr;
10573
10574 /// Retrieve the identifier "NSError".
10575 IdentifierInfo *getNSErrorIdent();
10576
10577 /// \brief Retrieve the parser's current scope.
10578 ///
10579 /// This routine must only be used when it is certain that semantic analysis
10580 /// and the parser are in precisely the same context, which is not the case
10581 /// when, e.g., we are performing any kind of template instantiation.
10582 /// Therefore, the only safe places to use this scope are in the parser
10583 /// itself and in routines directly invoked from the parser and *never* from
10584 /// template substitution or instantiation.
10585 Scope *getCurScope() const { return CurScope; }
10586
10587 void incrementMSManglingNumber() const {
10588 return CurScope->incrementMSManglingNumber();
10589 }
10590
10591 IdentifierInfo *getSuperIdentifier() const;
10592 IdentifierInfo *getFloat128Identifier() const;
10593
10594 Decl *getObjCDeclContext() const;
10595
10596 DeclContext *getCurLexicalContext() const {
10597 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10598 }
10599
10600 const DeclContext *getCurObjCLexicalContext() const {
10601 const DeclContext *DC = getCurLexicalContext();
10602 // A category implicitly has the attribute of the interface.
10603 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10604 DC = CatD->getClassInterface();
10605 return DC;
10606 }
10607
10608 /// \brief To be used for checking whether the arguments being passed to
10609 /// function exceeds the number of parameters expected for it.
10610 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10611 bool PartialOverloading = false) {
10612 // We check whether we're just after a comma in code-completion.
10613 if (NumArgs > 0 && PartialOverloading)
10614 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10615 return NumArgs > NumParams;
10616 }
10617
10618 // Emitting members of dllexported classes is delayed until the class
10619 // (including field initializers) is fully parsed.
10620 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10621
10622private:
10623 class SavePendingParsedClassStateRAII {
10624 public:
10625 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
10626
10627 ~SavePendingParsedClassStateRAII() {
10628 assert(S.DelayedExceptionSpecChecks.empty() &&(static_cast <bool> (S.DelayedExceptionSpecChecks.empty
() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 10629, __extension__ __PRETTY_FUNCTION__))
10629 "there shouldn't be any pending delayed exception spec checks")(static_cast <bool> (S.DelayedExceptionSpecChecks.empty
() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 10629, __extension__ __PRETTY_FUNCTION__))
;
10630 assert(S.DelayedDefaultedMemberExceptionSpecs.empty() &&(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs
.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 10632, __extension__ __PRETTY_FUNCTION__))
10631 "there shouldn't be any pending delayed defaulted member "(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs
.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 10632, __extension__ __PRETTY_FUNCTION__))
10632 "exception specs")(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs
.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 10632, __extension__ __PRETTY_FUNCTION__))
;
10633 assert(S.DelayedDllExportClasses.empty() &&(static_cast <bool> (S.DelayedDllExportClasses.empty() &&
"there shouldn't be any pending delayed DLL export classes")
? void (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 10634, __extension__ __PRETTY_FUNCTION__))
10634 "there shouldn't be any pending delayed DLL export classes")(static_cast <bool> (S.DelayedDllExportClasses.empty() &&
"there shouldn't be any pending delayed DLL export classes")
? void (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 10634, __extension__ __PRETTY_FUNCTION__))
;
10635 swapSavedState();
10636 }
10637
10638 private:
10639 Sema &S;
10640 decltype(DelayedExceptionSpecChecks) SavedExceptionSpecChecks;
10641 decltype(DelayedDefaultedMemberExceptionSpecs)
10642 SavedDefaultedMemberExceptionSpecs;
10643 decltype(DelayedDllExportClasses) SavedDllExportClasses;
10644
10645 void swapSavedState() {
10646 SavedExceptionSpecChecks.swap(S.DelayedExceptionSpecChecks);
10647 SavedDefaultedMemberExceptionSpecs.swap(
10648 S.DelayedDefaultedMemberExceptionSpecs);
10649 SavedDllExportClasses.swap(S.DelayedDllExportClasses);
10650 }
10651 };
10652
10653 /// \brief Helper class that collects misaligned member designations and
10654 /// their location info for delayed diagnostics.
10655 struct MisalignedMember {
10656 Expr *E;
10657 RecordDecl *RD;
10658 ValueDecl *MD;
10659 CharUnits Alignment;
10660
10661 MisalignedMember() : E(), RD(), MD(), Alignment() {}
10662 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10663 CharUnits Alignment)
10664 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10665 explicit MisalignedMember(Expr *E)
10666 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10667
10668 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10669 };
10670 /// \brief Small set of gathered accesses to potentially misaligned members
10671 /// due to the packed attribute.
10672 SmallVector<MisalignedMember, 4> MisalignedMembers;
10673
10674 /// \brief Adds an expression to the set of gathered misaligned members.
10675 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10676 CharUnits Alignment);
10677
10678public:
10679 /// \brief Diagnoses the current set of gathered accesses. This typically
10680 /// happens at full expression level. The set is cleared after emitting the
10681 /// diagnostics.
10682 void DiagnoseMisalignedMembers();
10683
10684 /// \brief This function checks if the expression is in the sef of potentially
10685 /// misaligned members and it is converted to some pointer type T with lower
10686 /// or equal alignment requirements. If so it removes it. This is used when
10687 /// we do not want to diagnose such misaligned access (e.g. in conversions to
10688 /// void*).
10689 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10690
10691 /// \brief This function calls Action when it determines that E designates a
10692 /// misaligned member due to the packed attribute. This is used to emit
10693 /// local diagnostics like in reference binding.
10694 void RefersToMemberWithReducedAlignment(
10695 Expr *E,
10696 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10697 Action);
10698};
10699
10700/// \brief RAII object that enters a new expression evaluation context.
10701class EnterExpressionEvaluationContext {
10702 Sema &Actions;
10703 bool Entered = true;
10704
10705public:
10706
10707 EnterExpressionEvaluationContext(Sema &Actions,
10708 Sema::ExpressionEvaluationContext NewContext,
10709 Decl *LambdaContextDecl = nullptr,
10710 bool IsDecltype = false,
10711 bool ShouldEnter = true)
10712 : Actions(Actions), Entered(ShouldEnter) {
10713 if (Entered)
10714 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10715 IsDecltype);
10716 }
10717 EnterExpressionEvaluationContext(Sema &Actions,
10718 Sema::ExpressionEvaluationContext NewContext,
10719 Sema::ReuseLambdaContextDecl_t,
10720 bool IsDecltype = false)
10721 : Actions(Actions) {
10722 Actions.PushExpressionEvaluationContext(NewContext,
10723 Sema::ReuseLambdaContextDecl,
10724 IsDecltype);
10725 }
10726
10727 enum InitListTag { InitList };
10728 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10729 bool ShouldEnter = true)
10730 : Actions(Actions), Entered(false) {
10731 // In C++11 onwards, narrowing checks are performed on the contents of
10732 // braced-init-lists, even when they occur within unevaluated operands.
10733 // Therefore we still need to instantiate constexpr functions used in such
10734 // a context.
10735 if (ShouldEnter && Actions.isUnevaluatedContext() &&
10736 Actions.getLangOpts().CPlusPlus11) {
10737 Actions.PushExpressionEvaluationContext(
10738 Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10739 Entered = true;
10740 }
10741 }
10742
10743 ~EnterExpressionEvaluationContext() {
10744 if (Entered)
10745 Actions.PopExpressionEvaluationContext();
10746 }
10747};
10748
10749DeductionFailureInfo
10750MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10751 sema::TemplateDeductionInfo &Info);
10752
10753/// \brief Contains a late templated function.
10754/// Will be parsed at the end of the translation unit, used by Sema & Parser.
10755struct LateParsedTemplate {
10756 CachedTokens Toks;
10757 /// \brief The template function declaration to be late parsed.
10758 Decl *D;
10759};
10760
10761} // end namespace clang
10762
10763namespace llvm {
10764// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10765// SourceLocation.
10766template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10767 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10768 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10769
10770 static FunctionDeclAndLoc getEmptyKey() {
10771 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10772 }
10773
10774 static FunctionDeclAndLoc getTombstoneKey() {
10775 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10776 }
10777
10778 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10779 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10780 FDL.Loc.getRawEncoding());
10781 }
10782
10783 static bool isEqual(const FunctionDeclAndLoc &LHS,
10784 const FunctionDeclAndLoc &RHS) {
10785 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10786 }
10787};
10788} // namespace llvm
10789
10790#endif

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h

1//===- Initialization.h - Semantic Analysis for Initializers ----*- C++ -*-===//
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// This file provides supporting data types for initialization of objects.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_INITIALIZATION_H
15#define LLVM_CLANG_SEMA_INITIALIZATION_H
16
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclAccessPair.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/IdentifierTable.h"
25#include "clang/Basic/LLVM.h"
26#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/SourceLocation.h"
28#include "clang/Basic/Specifiers.h"
29#include "clang/Sema/Overload.h"
30#include "clang/Sema/Ownership.h"
31#include "llvm/ADT/ArrayRef.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/StringRef.h"
34#include "llvm/ADT/iterator_range.h"
35#include "llvm/Support/Casting.h"
36#include <cassert>
37#include <cstdint>
38#include <string>
39
40namespace clang {
41
42class APValue;
43class CXXBaseSpecifier;
44class CXXConstructorDecl;
45class ObjCMethodDecl;
46class Sema;
47
48/// \brief Describes an entity that is being initialized.
49class InitializedEntity {
50public:
51 /// \brief Specifies the kind of entity being initialized.
52 enum EntityKind {
53 /// \brief The entity being initialized is a variable.
54 EK_Variable,
55
56 /// \brief The entity being initialized is a function parameter.
57 EK_Parameter,
58
59 /// \brief The entity being initialized is the result of a function call.
60 EK_Result,
61
62 /// \brief The entity being initialized is an exception object that
63 /// is being thrown.
64 EK_Exception,
65
66 /// \brief The entity being initialized is a non-static data member
67 /// subobject.
68 EK_Member,
69
70 /// \brief The entity being initialized is an element of an array.
71 EK_ArrayElement,
72
73 /// \brief The entity being initialized is an object (or array of
74 /// objects) allocated via new.
75 EK_New,
76
77 /// \brief The entity being initialized is a temporary object.
78 EK_Temporary,
79
80 /// \brief The entity being initialized is a base member subobject.
81 EK_Base,
82
83 /// \brief The initialization is being done by a delegating constructor.
84 EK_Delegating,
85
86 /// \brief The entity being initialized is an element of a vector.
87 /// or vector.
88 EK_VectorElement,
89
90 /// \brief The entity being initialized is a field of block descriptor for
91 /// the copied-in c++ object.
92 EK_BlockElement,
93
94 /// The entity being initialized is a field of block descriptor for the
95 /// copied-in lambda object that's used in the lambda to block conversion.
96 EK_LambdaToBlockConversionBlockElement,
97
98 /// \brief The entity being initialized is the real or imaginary part of a
99 /// complex number.
100 EK_ComplexElement,
101
102 /// \brief The entity being initialized is the field that captures a
103 /// variable in a lambda.
104 EK_LambdaCapture,
105
106 /// \brief The entity being initialized is the initializer for a compound
107 /// literal.
108 EK_CompoundLiteralInit,
109
110 /// \brief The entity being implicitly initialized back to the formal
111 /// result type.
112 EK_RelatedResult,
113
114 /// \brief The entity being initialized is a function parameter; function
115 /// is member of group of audited CF APIs.
116 EK_Parameter_CF_Audited,
117
118 /// \brief The entity being initialized is a structured binding of a
119 /// decomposition declaration.
120 EK_Binding,
121
122 // Note: err_init_conversion_failed in DiagnosticSemaKinds.td uses this
123 // enum as an index for its first %select. When modifying this list,
124 // that diagnostic text needs to be updated as well.
125 };
126
127private:
128 /// \brief The kind of entity being initialized.
129 EntityKind Kind;
130
131 /// \brief If non-NULL, the parent entity in which this
132 /// initialization occurs.
133 const InitializedEntity *Parent = nullptr;
134
135 /// \brief The type of the object or reference being initialized.
136 QualType Type;
137
138 /// \brief The mangling number for the next reference temporary to be created.
139 mutable unsigned ManglingNumber = 0;
140
141 struct LN {
142 /// \brief When Kind == EK_Result, EK_Exception, EK_New, the
143 /// location of the 'return', 'throw', or 'new' keyword,
144 /// respectively. When Kind == EK_Temporary, the location where
145 /// the temporary is being created.
146 unsigned Location;
147
148 /// \brief Whether the entity being initialized may end up using the
149 /// named return value optimization (NRVO).
150 bool NRVO;
151 };
152
153 struct VD {
154 /// \brief The VarDecl, FieldDecl, or BindingDecl being initialized.
155 ValueDecl *VariableOrMember;
156
157 /// \brief When Kind == EK_Member, whether this is an implicit member
158 /// initialization in a copy or move constructor. These can perform array
159 /// copies.
160 bool IsImplicitFieldInit;
161 };
162
163 struct C {
164 /// \brief The name of the variable being captured by an EK_LambdaCapture.
165 IdentifierInfo *VarID;
166
167 /// \brief The source location at which the capture occurs.
168 unsigned Location;
169 };
170
171 union {
172 /// \brief When Kind == EK_Variable, EK_Member or EK_Binding, the variable.
173 VD Variable;
174
175 /// \brief When Kind == EK_RelatedResult, the ObjectiveC method where
176 /// result type was implicitly changed to accommodate ARC semantics.
177 ObjCMethodDecl *MethodDecl;
178
179 /// \brief When Kind == EK_Parameter, the ParmVarDecl, with the
180 /// low bit indicating whether the parameter is "consumed".
181 uintptr_t Parameter;
182
183 /// \brief When Kind == EK_Temporary or EK_CompoundLiteralInit, the type
184 /// source information for the temporary.
185 TypeSourceInfo *TypeInfo;
186
187 struct LN LocAndNRVO;
188
189 /// \brief When Kind == EK_Base, the base specifier that provides the
190 /// base class. The lower bit specifies whether the base is an inherited
191 /// virtual base.
192 uintptr_t Base;
193
194 /// \brief When Kind == EK_ArrayElement, EK_VectorElement, or
195 /// EK_ComplexElement, the index of the array or vector element being
196 /// initialized.
197 unsigned Index;
198
199 struct C Capture;
200 };
201
202 InitializedEntity() = default;
203
204 /// \brief Create the initialization entity for a variable.
205 InitializedEntity(VarDecl *Var, EntityKind EK = EK_Variable)
206 : Kind(EK), Type(Var->getType()), Variable{Var, false} {}
207
208 /// \brief Create the initialization entity for the result of a
209 /// function, throwing an object, performing an explicit cast, or
210 /// initializing a parameter for which there is no declaration.
211 InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
212 bool NRVO = false)
213 : Kind(Kind), Type(Type) {
214 LocAndNRVO.Location = Loc.getRawEncoding();
215 LocAndNRVO.NRVO = NRVO;
216 }
217
218 /// \brief Create the initialization entity for a member subobject.
219 InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent,
220 bool Implicit)
221 : Kind(EK_Member), Parent(Parent), Type(Member->getType()),
222 Variable{Member, Implicit} {}
223
224 /// \brief Create the initialization entity for an array element.
225 InitializedEntity(ASTContext &Context, unsigned Index,
226 const InitializedEntity &Parent);
227
228 /// \brief Create the initialization entity for a lambda capture.
229 InitializedEntity(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
230 : Kind(EK_LambdaCapture), Type(FieldType) {
231 Capture.VarID = VarID;
232 Capture.Location = Loc.getRawEncoding();
233 }
234
235public:
236 /// \brief Create the initialization entity for a variable.
237 static InitializedEntity InitializeVariable(VarDecl *Var) {
238 return InitializedEntity(Var);
239 }
240
241 /// \brief Create the initialization entity for a parameter.
242 static InitializedEntity InitializeParameter(ASTContext &Context,
243 const ParmVarDecl *Parm) {
244 return InitializeParameter(Context, Parm, Parm->getType());
245 }
246
247 /// \brief Create the initialization entity for a parameter, but use
248 /// another type.
249 static InitializedEntity InitializeParameter(ASTContext &Context,
250 const ParmVarDecl *Parm,
251 QualType Type) {
252 bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
253 Parm->hasAttr<NSConsumedAttr>());
254
255 InitializedEntity Entity;
256 Entity.Kind = EK_Parameter;
257 Entity.Type =
258 Context.getVariableArrayDecayedType(Type.getUnqualifiedType());
259 Entity.Parent = nullptr;
260 Entity.Parameter
261 = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
262 return Entity;
263 }
264
265 /// \brief Create the initialization entity for a parameter that is
266 /// only known by its type.
267 static InitializedEntity InitializeParameter(ASTContext &Context,
268 QualType Type,
269 bool Consumed) {
270 InitializedEntity Entity;
271 Entity.Kind = EK_Parameter;
272 Entity.Type = Context.getVariableArrayDecayedType(Type);
273 Entity.Parent = nullptr;
274 Entity.Parameter = (Consumed);
275 return Entity;
276 }
277
278 /// \brief Create the initialization entity for the result of a function.
279 static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
280 QualType Type, bool NRVO) {
281 return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
282 }
283
284 static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
285 QualType Type, bool NRVO) {
286 return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
287 }
288
289 static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc,
290 QualType Type, bool NRVO) {
291 return InitializedEntity(EK_LambdaToBlockConversionBlockElement,
292 BlockVarLoc, Type, NRVO);
293 }
294
295 /// \brief Create the initialization entity for an exception object.
296 static InitializedEntity InitializeException(SourceLocation ThrowLoc,
297 QualType Type, bool NRVO) {
298 return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
299 }
300
301 /// \brief Create the initialization entity for an object allocated via new.
302 static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
303 return InitializedEntity(EK_New, NewLoc, Type);
304 }
305
306 /// \brief Create the initialization entity for a temporary.
307 static InitializedEntity InitializeTemporary(QualType Type) {
308 return InitializeTemporary(nullptr, Type);
309 }
310
311 /// \brief Create the initialization entity for a temporary.
312 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
313 return InitializeTemporary(TypeInfo, TypeInfo->getType());
314 }
315
316 /// \brief Create the initialization entity for a temporary.
317 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo,
318 QualType Type) {
319 InitializedEntity Result(EK_Temporary, SourceLocation(), Type);
320 Result.TypeInfo = TypeInfo;
321 return Result;
322 }
323
324 /// \brief Create the initialization entity for a related result.
325 static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD,
326 QualType Type) {
327 InitializedEntity Result(EK_RelatedResult, SourceLocation(), Type);
328 Result.MethodDecl = MD;
329 return Result;
330 }
331
332 /// \brief Create the initialization entity for a base class subobject.
333 static InitializedEntity
334 InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base,
335 bool IsInheritedVirtualBase,
336 const InitializedEntity *Parent = nullptr);
337
338 /// \brief Create the initialization entity for a delegated constructor.
339 static InitializedEntity InitializeDelegation(QualType Type) {
340 return InitializedEntity(EK_Delegating, SourceLocation(), Type);
341 }
342
343 /// \brief Create the initialization entity for a member subobject.
344 static InitializedEntity
345 InitializeMember(FieldDecl *Member,
346 const InitializedEntity *Parent = nullptr,
347 bool Implicit = false) {
348 return InitializedEntity(Member, Parent, Implicit);
349 }
350
351 /// \brief Create the initialization entity for a member subobject.
352 static InitializedEntity
353 InitializeMember(IndirectFieldDecl *Member,
354 const InitializedEntity *Parent = nullptr,
355 bool Implicit = false) {
356 return InitializedEntity(Member->getAnonField(), Parent, Implicit);
357 }
358
359 /// \brief Create the initialization entity for an array element.
360 static InitializedEntity InitializeElement(ASTContext &Context,
361 unsigned Index,
362 const InitializedEntity &Parent) {
363 return InitializedEntity(Context, Index, Parent);
364 }
365
366 /// \brief Create the initialization entity for a structured binding.
367 static InitializedEntity InitializeBinding(VarDecl *Binding) {
368 return InitializedEntity(Binding, EK_Binding);
369 }
370
371 /// \brief Create the initialization entity for a lambda capture.
372 static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID,
373 QualType FieldType,
374 SourceLocation Loc) {
375 return InitializedEntity(VarID, FieldType, Loc);
376 }
377
378 /// \brief Create the entity for a compound literal initializer.
379 static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) {
380 InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(),
381 TSI->getType());
382 Result.TypeInfo = TSI;
383 return Result;
384 }
385
386 /// \brief Determine the kind of initialization.
387 EntityKind getKind() const { return Kind; }
388
389 /// \brief Retrieve the parent of the entity being initialized, when
390 /// the initialization itself is occurring within the context of a
391 /// larger initialization.
392 const InitializedEntity *getParent() const { return Parent; }
393
394 /// \brief Retrieve type being initialized.
395 QualType getType() const { return Type; }
396
397 /// \brief Retrieve complete type-source information for the object being
398 /// constructed, if known.
399 TypeSourceInfo *getTypeSourceInfo() const {
400 if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit)
401 return TypeInfo;
402
403 return nullptr;
404 }
405
406 /// \brief Retrieve the name of the entity being initialized.
407 DeclarationName getName() const;
408
409 /// \brief Retrieve the variable, parameter, or field being
410 /// initialized.
411 ValueDecl *getDecl() const;
412
413 /// \brief Retrieve the ObjectiveC method being initialized.
414 ObjCMethodDecl *getMethodDecl() const { return MethodDecl; }
415
416 /// \brief Determine whether this initialization allows the named return
417 /// value optimization, which also applies to thrown objects.
418 bool allowsNRVO() const;
419
420 bool isParameterKind() const {
421 return (getKind() == EK_Parameter ||
422 getKind() == EK_Parameter_CF_Audited);
423 }
424
425 /// \brief Determine whether this initialization consumes the
426 /// parameter.
427 bool isParameterConsumed() const {
428 assert(isParameterKind() && "Not a parameter")(static_cast <bool> (isParameterKind() && "Not a parameter"
) ? void (0) : __assert_fail ("isParameterKind() && \"Not a parameter\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 428, __extension__ __PRETTY_FUNCTION__))
;
429 return (Parameter & 1);
430 }
431
432 /// \brief Retrieve the base specifier.
433 const CXXBaseSpecifier *getBaseSpecifier() const {
434 assert(getKind() == EK_Base && "Not a base specifier")(static_cast <bool> (getKind() == EK_Base && "Not a base specifier"
) ? void (0) : __assert_fail ("getKind() == EK_Base && \"Not a base specifier\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 434, __extension__ __PRETTY_FUNCTION__))
;
435 return reinterpret_cast<const CXXBaseSpecifier *>(Base & ~0x1);
436 }
437
438 /// \brief Return whether the base is an inherited virtual base.
439 bool isInheritedVirtualBase() const {
440 assert(getKind() == EK_Base && "Not a base specifier")(static_cast <bool> (getKind() == EK_Base && "Not a base specifier"
) ? void (0) : __assert_fail ("getKind() == EK_Base && \"Not a base specifier\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 440, __extension__ __PRETTY_FUNCTION__))
;
441 return Base & 0x1;
442 }
443
444 /// \brief Determine whether this is an array new with an unknown bound.
445 bool isVariableLengthArrayNew() const {
446 return getKind() == EK_New && dyn_cast_or_null<IncompleteArrayType>(
447 getType()->getAsArrayTypeUnsafe());
448 }
449
450 /// \brief Is this the implicit initialization of a member of a class from
451 /// a defaulted constructor?
452 bool isImplicitMemberInitializer() const {
453 return getKind() == EK_Member && Variable.IsImplicitFieldInit;
454 }
455
456 /// \brief Determine the location of the 'return' keyword when initializing
457 /// the result of a function call.
458 SourceLocation getReturnLoc() const {
459 assert(getKind() == EK_Result && "No 'return' location!")(static_cast <bool> (getKind() == EK_Result && "No 'return' location!"
) ? void (0) : __assert_fail ("getKind() == EK_Result && \"No 'return' location!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 459, __extension__ __PRETTY_FUNCTION__))
;
460 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
461 }
462
463 /// \brief Determine the location of the 'throw' keyword when initializing
464 /// an exception object.
465 SourceLocation getThrowLoc() const {
466 assert(getKind() == EK_Exception && "No 'throw' location!")(static_cast <bool> (getKind() == EK_Exception &&
"No 'throw' location!") ? void (0) : __assert_fail ("getKind() == EK_Exception && \"No 'throw' location!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 466, __extension__ __PRETTY_FUNCTION__))
;
467 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
468 }
469
470 /// \brief If this is an array, vector, or complex number element, get the
471 /// element's index.
472 unsigned getElementIndex() const {
473 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||(static_cast <bool> (getKind() == EK_ArrayElement || getKind
() == EK_VectorElement || getKind() == EK_ComplexElement) ? void
(0) : __assert_fail ("getKind() == EK_ArrayElement || getKind() == EK_VectorElement || getKind() == EK_ComplexElement"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 474, __extension__ __PRETTY_FUNCTION__))
474 getKind() == EK_ComplexElement)(static_cast <bool> (getKind() == EK_ArrayElement || getKind
() == EK_VectorElement || getKind() == EK_ComplexElement) ? void
(0) : __assert_fail ("getKind() == EK_ArrayElement || getKind() == EK_VectorElement || getKind() == EK_ComplexElement"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 474, __extension__ __PRETTY_FUNCTION__))
;
475 return Index;
476 }
477
478 /// \brief If this is already the initializer for an array or vector
479 /// element, sets the element index.
480 void setElementIndex(unsigned Index) {
481 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||(static_cast <bool> (getKind() == EK_ArrayElement || getKind
() == EK_VectorElement || getKind() == EK_ComplexElement) ? void
(0) : __assert_fail ("getKind() == EK_ArrayElement || getKind() == EK_VectorElement || getKind() == EK_ComplexElement"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 482, __extension__ __PRETTY_FUNCTION__))
482 getKind() == EK_ComplexElement)(static_cast <bool> (getKind() == EK_ArrayElement || getKind
() == EK_VectorElement || getKind() == EK_ComplexElement) ? void
(0) : __assert_fail ("getKind() == EK_ArrayElement || getKind() == EK_VectorElement || getKind() == EK_ComplexElement"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 482, __extension__ __PRETTY_FUNCTION__))
;
483 this->Index = Index;
484 }
485
486 /// \brief For a lambda capture, return the capture's name.
487 StringRef getCapturedVarName() const {
488 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!")(static_cast <bool> (getKind() == EK_LambdaCapture &&
"Not a lambda capture!") ? void (0) : __assert_fail ("getKind() == EK_LambdaCapture && \"Not a lambda capture!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 488, __extension__ __PRETTY_FUNCTION__))
;
489 return Capture.VarID->getName();
490 }
491
492 /// \brief Determine the location of the capture when initializing
493 /// field from a captured variable in a lambda.
494 SourceLocation getCaptureLoc() const {
495 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!")(static_cast <bool> (getKind() == EK_LambdaCapture &&
"Not a lambda capture!") ? void (0) : __assert_fail ("getKind() == EK_LambdaCapture && \"Not a lambda capture!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 495, __extension__ __PRETTY_FUNCTION__))
;
496 return SourceLocation::getFromRawEncoding(Capture.Location);
497 }
498
499 void setParameterCFAudited() {
500 Kind = EK_Parameter_CF_Audited;
501 }
502
503 unsigned allocateManglingNumber() const { return ++ManglingNumber; }
504
505 /// Dump a representation of the initialized entity to standard error,
506 /// for debugging purposes.
507 void dump() const;
508
509private:
510 unsigned dumpImpl(raw_ostream &OS) const;
511};
512
513/// \brief Describes the kind of initialization being performed, along with
514/// location information for tokens related to the initialization (equal sign,
515/// parentheses).
516class InitializationKind {
517public:
518 /// \brief The kind of initialization being performed.
519 enum InitKind {
520 /// Direct initialization
521 IK_Direct,
522
523 /// Direct list-initialization
524 IK_DirectList,
525
526 /// Copy initialization
527 IK_Copy,
528
529 /// Default initialization
530 IK_Default,
531
532 /// Value initialization
533 IK_Value
534 };
535
536private:
537 /// \brief The context of the initialization.
538 enum InitContext {
539 /// Normal context
540 IC_Normal,
541
542 /// Normal context, but allows explicit conversion functionss
543 IC_ExplicitConvs,
544
545 /// Implicit context (value initialization)
546 IC_Implicit,
547
548 /// Static cast context
549 IC_StaticCast,
550
551 /// C-style cast context
552 IC_CStyleCast,
553
554 /// Functional cast context
555 IC_FunctionalCast
556 };
557
558 /// \brief The kind of initialization being performed.
559 InitKind Kind : 8;
560
561 /// \brief The context of the initialization.
562 InitContext Context : 8;
563
564 /// \brief The source locations involved in the initialization.
565 SourceLocation Locations[3];
566
567 InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
568 SourceLocation Loc2, SourceLocation Loc3)
569 : Kind(Kind), Context(Context) {
570 Locations[0] = Loc1;
571 Locations[1] = Loc2;
572 Locations[2] = Loc3;
573 }
574
575public:
576 /// \brief Create a direct initialization.
577 static InitializationKind CreateDirect(SourceLocation InitLoc,
578 SourceLocation LParenLoc,
579 SourceLocation RParenLoc) {
580 return InitializationKind(IK_Direct, IC_Normal,
581 InitLoc, LParenLoc, RParenLoc);
582 }
583
584 static InitializationKind CreateDirectList(SourceLocation InitLoc) {
585 return InitializationKind(IK_DirectList, IC_Normal, InitLoc, InitLoc,
586 InitLoc);
587 }
588
589 static InitializationKind CreateDirectList(SourceLocation InitLoc,
590 SourceLocation LBraceLoc,
591 SourceLocation RBraceLoc) {
592 return InitializationKind(IK_DirectList, IC_Normal, InitLoc, LBraceLoc,
593 RBraceLoc);
594 }
595
596 /// \brief Create a direct initialization due to a cast that isn't a C-style
597 /// or functional cast.
598 static InitializationKind CreateCast(SourceRange TypeRange) {
599 return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
600 TypeRange.getBegin(), TypeRange.getEnd());
601 }
602
603 /// \brief Create a direct initialization for a C-style cast.
604 static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
605 SourceRange TypeRange,
606 bool InitList) {
607 // C++ cast syntax doesn't permit init lists, but C compound literals are
608 // exactly that.
609 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
610 IC_CStyleCast, StartLoc, TypeRange.getBegin(),
611 TypeRange.getEnd());
612 }
613
614 /// \brief Create a direct initialization for a functional cast.
615 static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
616 bool InitList) {
617 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
618 IC_FunctionalCast, TypeRange.getBegin(),
619 TypeRange.getBegin(), TypeRange.getEnd());
620 }
621
622 /// \brief Create a copy initialization.
623 static InitializationKind CreateCopy(SourceLocation InitLoc,
624 SourceLocation EqualLoc,
625 bool AllowExplicitConvs = false) {
626 return InitializationKind(IK_Copy,
627 AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
628 InitLoc, EqualLoc, EqualLoc);
629 }
630
631 /// \brief Create a default initialization.
632 static InitializationKind CreateDefault(SourceLocation InitLoc) {
633 return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
634 }
635
636 /// \brief Create a value initialization.
637 static InitializationKind CreateValue(SourceLocation InitLoc,
638 SourceLocation LParenLoc,
639 SourceLocation RParenLoc,
640 bool isImplicit = false) {
641 return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
642 InitLoc, LParenLoc, RParenLoc);
643 }
644
645 /// \brief Create an initialization from an initializer (which, for direct
646 /// initialization from a parenthesized list, will be a ParenListExpr).
647 static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit,
648 Expr *Init) {
649 if (!Init) return CreateDefault(Loc);
650 if (!DirectInit) return CreateCopy(Loc, Init->getLocStart());
651 if (isa<InitListExpr>(Init))
652 return CreateDirectList(Loc, Init->getLocStart(), Init->getLocEnd());
653 return CreateDirect(Loc, Init->getLocStart(), Init->getLocEnd());
654 }
655
656 /// \brief Determine the initialization kind.
657 InitKind getKind() const {
658 return Kind;
659 }
660
661 /// \brief Determine whether this initialization is an explicit cast.
662 bool isExplicitCast() const {
663 return Context >= IC_StaticCast;
664 }
665
666 /// \brief Determine whether this initialization is a C-style cast.
667 bool isCStyleOrFunctionalCast() const {
668 return Context >= IC_CStyleCast;
669 }
670
671 /// \brief Determine whether this is a C-style cast.
672 bool isCStyleCast() const {
673 return Context == IC_CStyleCast;
674 }
675
676 /// \brief Determine whether this is a functional-style cast.
677 bool isFunctionalCast() const {
678 return Context == IC_FunctionalCast;
679 }
680
681 /// \brief Determine whether this initialization is an implicit
682 /// value-initialization, e.g., as occurs during aggregate
683 /// initialization.
684 bool isImplicitValueInit() const { return Context == IC_Implicit; }
685
686 /// \brief Retrieve the location at which initialization is occurring.
687 SourceLocation getLocation() const { return Locations[0]; }
688
689 /// \brief Retrieve the source range that covers the initialization.
690 SourceRange getRange() const {
691 return SourceRange(Locations[0], Locations[2]);
692 }
693
694 /// \brief Retrieve the location of the equal sign for copy initialization
695 /// (if present).
696 SourceLocation getEqualLoc() const {
697 assert(Kind == IK_Copy && "Only copy initialization has an '='")(static_cast <bool> (Kind == IK_Copy && "Only copy initialization has an '='"
) ? void (0) : __assert_fail ("Kind == IK_Copy && \"Only copy initialization has an '='\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 697, __extension__ __PRETTY_FUNCTION__))
;
698 return Locations[1];
699 }
700
701 bool isCopyInit() const { return Kind == IK_Copy; }
702
703 /// \brief Retrieve whether this initialization allows the use of explicit
704 /// constructors.
705 bool AllowExplicit() const { return !isCopyInit(); }
706
707 /// \brief Retrieve whether this initialization allows the use of explicit
708 /// conversion functions when binding a reference. If the reference is the
709 /// first parameter in a copy or move constructor, such conversions are
710 /// permitted even though we are performing copy-initialization.
711 bool allowExplicitConversionFunctionsInRefBinding() const {
712 return !isCopyInit() || Context == IC_ExplicitConvs;
713 }
714
715 /// Determine whether this initialization has a source range containing the
716 /// locations of open and closing parentheses or braces.
717 bool hasParenOrBraceRange() const {
718 return Kind == IK_Direct || Kind == IK_Value || Kind == IK_DirectList;
719 }
720
721 /// \brief Retrieve the source range containing the locations of the open
722 /// and closing parentheses or braces for value, direct, and direct list
723 /// initializations.
724 SourceRange getParenOrBraceRange() const {
725 assert(hasParenOrBraceRange() && "Only direct, value, and direct-list "(static_cast <bool> (hasParenOrBraceRange() && "Only direct, value, and direct-list "
"initialization have parentheses or " "braces") ? void (0) :
__assert_fail ("hasParenOrBraceRange() && \"Only direct, value, and direct-list \" \"initialization have parentheses or \" \"braces\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 727, __extension__ __PRETTY_FUNCTION__))
726 "initialization have parentheses or "(static_cast <bool> (hasParenOrBraceRange() && "Only direct, value, and direct-list "
"initialization have parentheses or " "braces") ? void (0) :
__assert_fail ("hasParenOrBraceRange() && \"Only direct, value, and direct-list \" \"initialization have parentheses or \" \"braces\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 727, __extension__ __PRETTY_FUNCTION__))
727 "braces")(static_cast <bool> (hasParenOrBraceRange() && "Only direct, value, and direct-list "
"initialization have parentheses or " "braces") ? void (0) :
__assert_fail ("hasParenOrBraceRange() && \"Only direct, value, and direct-list \" \"initialization have parentheses or \" \"braces\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 727, __extension__ __PRETTY_FUNCTION__))
;
728 return SourceRange(Locations[1], Locations[2]);
729 }
730};
731
732/// \brief Describes the sequence of initializations required to initialize
733/// a given object or reference with a set of arguments.
734class InitializationSequence {
735public:
736 /// \brief Describes the kind of initialization sequence computed.
737 enum SequenceKind {
738 /// \brief A failed initialization sequence. The failure kind tells what
739 /// happened.
740 FailedSequence = 0,
741
742 /// \brief A dependent initialization, which could not be
743 /// type-checked due to the presence of dependent types or
744 /// dependently-typed expressions.
745 DependentSequence,
746
747 /// \brief A normal sequence.
748 NormalSequence
749 };
750
751 /// \brief Describes the kind of a particular step in an initialization
752 /// sequence.
753 enum StepKind {
754 /// \brief Resolve the address of an overloaded function to a specific
755 /// function declaration.
756 SK_ResolveAddressOfOverloadedFunction,
757
758 /// \brief Perform a derived-to-base cast, producing an rvalue.
759 SK_CastDerivedToBaseRValue,
760
761 /// \brief Perform a derived-to-base cast, producing an xvalue.
762 SK_CastDerivedToBaseXValue,
763
764 /// \brief Perform a derived-to-base cast, producing an lvalue.
765 SK_CastDerivedToBaseLValue,
766
767 /// \brief Reference binding to an lvalue.
768 SK_BindReference,
769
770 /// \brief Reference binding to a temporary.
771 SK_BindReferenceToTemporary,
772
773 /// \brief An optional copy of a temporary object to another
774 /// temporary object, which is permitted (but not required) by
775 /// C++98/03 but not C++0x.
776 SK_ExtraneousCopyToTemporary,
777
778 /// \brief Direct-initialization from a reference-related object in the
779 /// final stage of class copy-initialization.
780 SK_FinalCopy,
781
782 /// \brief Perform a user-defined conversion, either via a conversion
783 /// function or via a constructor.
784 SK_UserConversion,
785
786 /// \brief Perform a qualification conversion, producing an rvalue.
787 SK_QualificationConversionRValue,
788
789 /// \brief Perform a qualification conversion, producing an xvalue.
790 SK_QualificationConversionXValue,
791
792 /// \brief Perform a qualification conversion, producing an lvalue.
793 SK_QualificationConversionLValue,
794
795 /// \brief Perform a conversion adding _Atomic to a type.
796 SK_AtomicConversion,
797
798 /// \brief Perform a load from a glvalue, producing an rvalue.
799 SK_LValueToRValue,
800
801 /// \brief Perform an implicit conversion sequence.
802 SK_ConversionSequence,
803
804 /// \brief Perform an implicit conversion sequence without narrowing.
805 SK_ConversionSequenceNoNarrowing,
806
807 /// \brief Perform list-initialization without a constructor.
808 SK_ListInitialization,
809
810 /// \brief Unwrap the single-element initializer list for a reference.
811 SK_UnwrapInitList,
812
813 /// \brief Rewrap the single-element initializer list for a reference.
814 SK_RewrapInitList,
815
816 /// \brief Perform initialization via a constructor.
817 SK_ConstructorInitialization,
818
819 /// \brief Perform initialization via a constructor, taking arguments from
820 /// a single InitListExpr.
821 SK_ConstructorInitializationFromList,
822
823 /// \brief Zero-initialize the object
824 SK_ZeroInitialization,
825
826 /// \brief C assignment
827 SK_CAssignment,
828
829 /// \brief Initialization by string
830 SK_StringInit,
831
832 /// \brief An initialization that "converts" an Objective-C object
833 /// (not a point to an object) to another Objective-C object type.
834 SK_ObjCObjectConversion,
835
836 /// \brief Array indexing for initialization by elementwise copy.
837 SK_ArrayLoopIndex,
838
839 /// \brief Array initialization by elementwise copy.
840 SK_ArrayLoopInit,
841
842 /// \brief Array initialization (from an array rvalue).
843 SK_ArrayInit,
844
845 /// \brief Array initialization (from an array rvalue) as a GNU extension.
846 SK_GNUArrayInit,
847
848 /// \brief Array initialization from a parenthesized initializer list.
849 /// This is a GNU C++ extension.
850 SK_ParenthesizedArrayInit,
851
852 /// \brief Pass an object by indirect copy-and-restore.
853 SK_PassByIndirectCopyRestore,
854
855 /// \brief Pass an object by indirect restore.
856 SK_PassByIndirectRestore,
857
858 /// \brief Produce an Objective-C object pointer.
859 SK_ProduceObjCObject,
860
861 /// \brief Construct a std::initializer_list from an initializer list.
862 SK_StdInitializerList,
863
864 /// \brief Perform initialization via a constructor taking a single
865 /// std::initializer_list argument.
866 SK_StdInitializerListConstructorCall,
867
868 /// \brief Initialize an OpenCL sampler from an integer.
869 SK_OCLSamplerInit,
870
871 /// \brief Initialize queue_t from 0.
872 SK_OCLZeroQueue,
873
874 /// \brief Passing zero to a function where OpenCL event_t is expected.
875 SK_OCLZeroEvent
876 };
877
878 /// \brief A single step in the initialization sequence.
879 class Step {
880 public:
881 /// \brief The kind of conversion or initialization step we are taking.
882 StepKind Kind;
883
884 // \brief The type that results from this initialization.
885 QualType Type;
886
887 struct F {
888 bool HadMultipleCandidates;
889 FunctionDecl *Function;
890 DeclAccessPair FoundDecl;
891 };
892
893 union {
894 /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
895 /// SK_UserConversion, the function that the expression should be
896 /// resolved to or the conversion function to call, respectively.
897 /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
898 /// the constructor to be called.
899 ///
900 /// Always a FunctionDecl, plus a Boolean flag telling if it was
901 /// selected from an overloaded set having size greater than 1.
902 /// For conversion decls, the naming class is the source type.
903 /// For construct decls, the naming class is the target type.
904 struct F Function;
905
906 /// \brief When Kind = SK_ConversionSequence, the implicit conversion
907 /// sequence.
908 ImplicitConversionSequence *ICS;
909
910 /// \brief When Kind = SK_RewrapInitList, the syntactic form of the
911 /// wrapping list.
912 InitListExpr *WrappingSyntacticList;
913 };
914
915 void Destroy();
916 };
917
918private:
919 /// \brief The kind of initialization sequence computed.
920 enum SequenceKind SequenceKind;
921
922 /// \brief Steps taken by this initialization.
923 SmallVector<Step, 4> Steps;
924
925public:
926 /// \brief Describes why initialization failed.
927 enum FailureKind {
928 /// \brief Too many initializers provided for a reference.
929 FK_TooManyInitsForReference,
930
931 /// \brief Reference initialized from a parenthesized initializer list.
932 FK_ParenthesizedListInitForReference,
933
934 /// \brief Array must be initialized with an initializer list.
935 FK_ArrayNeedsInitList,
936
937 /// \brief Array must be initialized with an initializer list or a
938 /// string literal.
939 FK_ArrayNeedsInitListOrStringLiteral,
940
941 /// \brief Array must be initialized with an initializer list or a
942 /// wide string literal.
943 FK_ArrayNeedsInitListOrWideStringLiteral,
944
945 /// \brief Initializing a wide char array with narrow string literal.
946 FK_NarrowStringIntoWideCharArray,
947
948 /// \brief Initializing char array with wide string literal.
949 FK_WideStringIntoCharArray,
950
951 /// \brief Initializing wide char array with incompatible wide string
952 /// literal.
953 FK_IncompatWideStringIntoWideChar,
954
955 /// \brief Array type mismatch.
956 FK_ArrayTypeMismatch,
957
958 /// \brief Non-constant array initializer
959 FK_NonConstantArrayInit,
960
961 /// \brief Cannot resolve the address of an overloaded function.
962 FK_AddressOfOverloadFailed,
963
964 /// \brief Overloading due to reference initialization failed.
965 FK_ReferenceInitOverloadFailed,
966
967 /// \brief Non-const lvalue reference binding to a temporary.
968 FK_NonConstLValueReferenceBindingToTemporary,
969
970 /// \brief Non-const lvalue reference binding to a bit-field.
971 FK_NonConstLValueReferenceBindingToBitfield,
972
973 /// \brief Non-const lvalue reference binding to a vector element.
974 FK_NonConstLValueReferenceBindingToVectorElement,
975
976 /// \brief Non-const lvalue reference binding to an lvalue of unrelated
977 /// type.
978 FK_NonConstLValueReferenceBindingToUnrelated,
979
980 /// \brief Rvalue reference binding to an lvalue.
981 FK_RValueReferenceBindingToLValue,
982
983 /// \brief Reference binding drops qualifiers.
984 FK_ReferenceInitDropsQualifiers,
985
986 /// \brief Reference binding failed.
987 FK_ReferenceInitFailed,
988
989 /// \brief Implicit conversion failed.
990 FK_ConversionFailed,
991
992 /// \brief Implicit conversion failed.
993 FK_ConversionFromPropertyFailed,
994
995 /// \brief Too many initializers for scalar
996 FK_TooManyInitsForScalar,
997
998 /// \brief Scalar initialized from a parenthesized initializer list.
999 FK_ParenthesizedListInitForScalar,
1000
1001 /// \brief Reference initialization from an initializer list
1002 FK_ReferenceBindingToInitList,
1003
1004 /// \brief Initialization of some unused destination type with an
1005 /// initializer list.
1006 FK_InitListBadDestinationType,
1007
1008 /// \brief Overloading for a user-defined conversion failed.
1009 FK_UserConversionOverloadFailed,
1010
1011 /// \brief Overloading for initialization by constructor failed.
1012 FK_ConstructorOverloadFailed,
1013
1014 /// \brief Overloading for list-initialization by constructor failed.
1015 FK_ListConstructorOverloadFailed,
1016
1017 /// \brief Default-initialization of a 'const' object.
1018 FK_DefaultInitOfConst,
1019
1020 /// \brief Initialization of an incomplete type.
1021 FK_Incomplete,
1022
1023 /// \brief Variable-length array must not have an initializer.
1024 FK_VariableLengthArrayHasInitializer,
1025
1026 /// \brief List initialization failed at some point.
1027 FK_ListInitializationFailed,
1028
1029 /// \brief Initializer has a placeholder type which cannot be
1030 /// resolved by initialization.
1031 FK_PlaceholderType,
1032
1033 /// \brief Trying to take the address of a function that doesn't support
1034 /// having its address taken.
1035 FK_AddressOfUnaddressableFunction,
1036
1037 /// \brief List-copy-initialization chose an explicit constructor.
1038 FK_ExplicitConstructor,
1039 };
1040
1041private:
1042 /// \brief The reason why initialization failed.
1043 FailureKind Failure;
1044
1045 /// \brief The failed result of overload resolution.
1046 OverloadingResult FailedOverloadResult;
1047
1048 /// \brief The candidate set created when initialization failed.
1049 OverloadCandidateSet FailedCandidateSet;
1050
1051 /// \brief The incomplete type that caused a failure.
1052 QualType FailedIncompleteType;
1053
1054 /// \brief The fixit that needs to be applied to make this initialization
1055 /// succeed.
1056 std::string ZeroInitializationFixit;
1057 SourceLocation ZeroInitializationFixitLoc;
1058
1059public:
1060 /// \brief Call for initializations are invalid but that would be valid
1061 /// zero initialzations if Fixit was applied.
1062 void SetZeroInitializationFixit(const std::string& Fixit, SourceLocation L) {
1063 ZeroInitializationFixit = Fixit;
1064 ZeroInitializationFixitLoc = L;
1065 }
1066
1067private:
1068 /// \brief Prints a follow-up note that highlights the location of
1069 /// the initialized entity, if it's remote.
1070 void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
1071
1072public:
1073 /// \brief Try to perform initialization of the given entity, creating a
1074 /// record of the steps required to perform the initialization.
1075 ///
1076 /// The generated initialization sequence will either contain enough
1077 /// information to diagnose
1078 ///
1079 /// \param S the semantic analysis object.
1080 ///
1081 /// \param Entity the entity being initialized.
1082 ///
1083 /// \param Kind the kind of initialization being performed.
1084 ///
1085 /// \param Args the argument(s) provided for initialization.
1086 ///
1087 /// \param TopLevelOfInitList true if we are initializing from an expression
1088 /// at the top level inside an initializer list. This disallows
1089 /// narrowing conversions in C++11 onwards.
1090 /// \param TreatUnavailableAsInvalid true if we want to treat unavailable
1091 /// as invalid.
1092 InitializationSequence(Sema &S,
1093 const InitializedEntity &Entity,
1094 const InitializationKind &Kind,
1095 MultiExprArg Args,
1096 bool TopLevelOfInitList = false,
1097 bool TreatUnavailableAsInvalid = true);
1098 void InitializeFrom(Sema &S, const InitializedEntity &Entity,
1099 const InitializationKind &Kind, MultiExprArg Args,
1100 bool TopLevelOfInitList, bool TreatUnavailableAsInvalid);
1101
1102 ~InitializationSequence();
1103
1104 /// \brief Perform the actual initialization of the given entity based on
1105 /// the computed initialization sequence.
1106 ///
1107 /// \param S the semantic analysis object.
1108 ///
1109 /// \param Entity the entity being initialized.
1110 ///
1111 /// \param Kind the kind of initialization being performed.
1112 ///
1113 /// \param Args the argument(s) provided for initialization, ownership of
1114 /// which is transferred into the routine.
1115 ///
1116 /// \param ResultType if non-NULL, will be set to the type of the
1117 /// initialized object, which is the type of the declaration in most
1118 /// cases. However, when the initialized object is a variable of
1119 /// incomplete array type and the initializer is an initializer
1120 /// list, this type will be set to the completed array type.
1121 ///
1122 /// \returns an expression that performs the actual object initialization, if
1123 /// the initialization is well-formed. Otherwise, emits diagnostics
1124 /// and returns an invalid expression.
1125 ExprResult Perform(Sema &S,
1126 const InitializedEntity &Entity,
1127 const InitializationKind &Kind,
1128 MultiExprArg Args,
1129 QualType *ResultType = nullptr);
1130
1131 /// \brief Diagnose an potentially-invalid initialization sequence.
1132 ///
1133 /// \returns true if the initialization sequence was ill-formed,
1134 /// false otherwise.
1135 bool Diagnose(Sema &S,
1136 const InitializedEntity &Entity,
1137 const InitializationKind &Kind,
1138 ArrayRef<Expr *> Args);
1139
1140 /// \brief Determine the kind of initialization sequence computed.
1141 enum SequenceKind getKind() const { return SequenceKind; }
1142
1143 /// \brief Set the kind of sequence computed.
1144 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
1145
1146 /// \brief Determine whether the initialization sequence is valid.
1147 explicit operator bool() const { return !Failed(); }
23
Calling 'InitializationSequence::Failed'
1148
1149 /// \brief Determine whether the initialization sequence is invalid.
1150 bool Failed() const { return SequenceKind == FailedSequence; }
24
The left operand of '==' is a garbage value
1151
1152 using step_iterator = SmallVectorImpl<Step>::const_iterator;
1153
1154 step_iterator step_begin() const { return Steps.begin(); }
1155 step_iterator step_end() const { return Steps.end(); }
1156
1157 using step_range = llvm::iterator_range<step_iterator>;
1158
1159 step_range steps() const { return {step_begin(), step_end()}; }
1160
1161 /// \brief Determine whether this initialization is a direct reference
1162 /// binding (C++ [dcl.init.ref]).
1163 bool isDirectReferenceBinding() const;
1164
1165 /// \brief Determine whether this initialization failed due to an ambiguity.
1166 bool isAmbiguous() const;
1167
1168 /// \brief Determine whether this initialization is direct call to a
1169 /// constructor.
1170 bool isConstructorInitialization() const;
1171
1172 /// \brief Returns whether the last step in this initialization sequence is a
1173 /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
1174 ///
1175 /// If this function returns true, *isInitializerConstant will be set to
1176 /// describe whether *Initializer was a constant expression. If
1177 /// *isInitializerConstant is set to true, *ConstantValue will be set to the
1178 /// evaluated value of *Initializer.
1179 bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
1180 bool *isInitializerConstant,
1181 APValue *ConstantValue) const;
1182
1183 /// \brief Add a new step in the initialization that resolves the address
1184 /// of an overloaded function to a specific function declaration.
1185 ///
1186 /// \param Function the function to which the overloaded function reference
1187 /// resolves.
1188 void AddAddressOverloadResolutionStep(FunctionDecl *Function,
1189 DeclAccessPair Found,
1190 bool HadMultipleCandidates);
1191
1192 /// \brief Add a new step in the initialization that performs a derived-to-
1193 /// base cast.
1194 ///
1195 /// \param BaseType the base type to which we will be casting.
1196 ///
1197 /// \param Category Indicates whether the result will be treated as an
1198 /// rvalue, an xvalue, or an lvalue.
1199 void AddDerivedToBaseCastStep(QualType BaseType,
1200 ExprValueKind Category);
1201
1202 /// \brief Add a new step binding a reference to an object.
1203 ///
1204 /// \param BindingTemporary True if we are binding a reference to a temporary
1205 /// object (thereby extending its lifetime); false if we are binding to an
1206 /// lvalue or an lvalue treated as an rvalue.
1207 void AddReferenceBindingStep(QualType T, bool BindingTemporary);
1208
1209 /// \brief Add a new step that makes an extraneous copy of the input
1210 /// to a temporary of the same class type.
1211 ///
1212 /// This extraneous copy only occurs during reference binding in
1213 /// C++98/03, where we are permitted (but not required) to introduce
1214 /// an extra copy. At a bare minimum, we must check that we could
1215 /// call the copy constructor, and produce a diagnostic if the copy
1216 /// constructor is inaccessible or no copy constructor matches.
1217 //
1218 /// \param T The type of the temporary being created.
1219 void AddExtraneousCopyToTemporary(QualType T);
1220
1221 /// \brief Add a new step that makes a copy of the input to an object of
1222 /// the given type, as the final step in class copy-initialization.
1223 void AddFinalCopy(QualType T);
1224
1225 /// \brief Add a new step invoking a conversion function, which is either
1226 /// a constructor or a conversion function.
1227 void AddUserConversionStep(FunctionDecl *Function,
1228 DeclAccessPair FoundDecl,
1229 QualType T,
1230 bool HadMultipleCandidates);
1231
1232 /// \brief Add a new step that performs a qualification conversion to the
1233 /// given type.
1234 void AddQualificationConversionStep(QualType Ty,
1235 ExprValueKind Category);
1236
1237 /// \brief Add a new step that performs conversion from non-atomic to atomic
1238 /// type.
1239 void AddAtomicConversionStep(QualType Ty);
1240
1241 /// \brief Add a new step that performs a load of the given type.
1242 ///
1243 /// Although the term "LValueToRValue" is conventional, this applies to both
1244 /// lvalues and xvalues.
1245 void AddLValueToRValueStep(QualType Ty);
1246
1247 /// \brief Add a new step that applies an implicit conversion sequence.
1248 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
1249 QualType T, bool TopLevelOfInitList = false);
1250
1251 /// \brief Add a list-initialization step.
1252 void AddListInitializationStep(QualType T);
1253
1254 /// \brief Add a constructor-initialization step.
1255 ///
1256 /// \param FromInitList The constructor call is syntactically an initializer
1257 /// list.
1258 /// \param AsInitList The constructor is called as an init list constructor.
1259 void AddConstructorInitializationStep(DeclAccessPair FoundDecl,
1260 CXXConstructorDecl *Constructor,
1261 QualType T,
1262 bool HadMultipleCandidates,
1263 bool FromInitList, bool AsInitList);
1264
1265 /// \brief Add a zero-initialization step.
1266 void AddZeroInitializationStep(QualType T);
1267
1268 /// \brief Add a C assignment step.
1269 //
1270 // FIXME: It isn't clear whether this should ever be needed;
1271 // ideally, we would handle everything needed in C in the common
1272 // path. However, that isn't the case yet.
1273 void AddCAssignmentStep(QualType T);
1274
1275 /// \brief Add a string init step.
1276 void AddStringInitStep(QualType T);
1277
1278 /// \brief Add an Objective-C object conversion step, which is
1279 /// always a no-op.
1280 void AddObjCObjectConversionStep(QualType T);
1281
1282 /// \brief Add an array initialization loop step.
1283 void AddArrayInitLoopStep(QualType T, QualType EltTy);
1284
1285 /// \brief Add an array initialization step.
1286 void AddArrayInitStep(QualType T, bool IsGNUExtension);
1287
1288 /// \brief Add a parenthesized array initialization step.
1289 void AddParenthesizedArrayInitStep(QualType T);
1290
1291 /// \brief Add a step to pass an object by indirect copy-restore.
1292 void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
1293
1294 /// \brief Add a step to "produce" an Objective-C object (by
1295 /// retaining it).
1296 void AddProduceObjCObjectStep(QualType T);
1297
1298 /// \brief Add a step to construct a std::initializer_list object from an
1299 /// initializer list.
1300 void AddStdInitializerListConstructionStep(QualType T);
1301
1302 /// \brief Add a step to initialize an OpenCL sampler from an integer
1303 /// constant.
1304 void AddOCLSamplerInitStep(QualType T);
1305
1306 /// \brief Add a step to initialize an OpenCL event_t from a NULL
1307 /// constant.
1308 void AddOCLZeroEventStep(QualType T);
1309
1310 /// \brief Add a step to initialize an OpenCL queue_t from 0.
1311 void AddOCLZeroQueueStep(QualType T);
1312
1313 /// \brief Add steps to unwrap a initializer list for a reference around a
1314 /// single element and rewrap it at the end.
1315 void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
1316
1317 /// \brief Note that this initialization sequence failed.
1318 void SetFailed(FailureKind Failure) {
1319 SequenceKind = FailedSequence;
1320 this->Failure = Failure;
1321 assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&(static_cast <bool> ((Failure != FK_Incomplete || !FailedIncompleteType
.isNull()) && "Incomplete type failure requires a type!"
) ? void (0) : __assert_fail ("(Failure != FK_Incomplete || !FailedIncompleteType.isNull()) && \"Incomplete type failure requires a type!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 1322, __extension__ __PRETTY_FUNCTION__))
1322 "Incomplete type failure requires a type!")(static_cast <bool> ((Failure != FK_Incomplete || !FailedIncompleteType
.isNull()) && "Incomplete type failure requires a type!"
) ? void (0) : __assert_fail ("(Failure != FK_Incomplete || !FailedIncompleteType.isNull()) && \"Incomplete type failure requires a type!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 1322, __extension__ __PRETTY_FUNCTION__))
;
1323 }
1324
1325 /// \brief Note that this initialization sequence failed due to failed
1326 /// overload resolution.
1327 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
1328
1329 /// \brief Retrieve a reference to the candidate set when overload
1330 /// resolution fails.
1331 OverloadCandidateSet &getFailedCandidateSet() {
1332 return FailedCandidateSet;
1333 }
1334
1335 /// \brief Get the overloading result, for when the initialization
1336 /// sequence failed due to a bad overload.
1337 OverloadingResult getFailedOverloadResult() const {
1338 return FailedOverloadResult;
1339 }
1340
1341 /// \brief Note that this initialization sequence failed due to an
1342 /// incomplete type.
1343 void setIncompleteTypeFailure(QualType IncompleteType) {
1344 FailedIncompleteType = IncompleteType;
1345 SetFailed(FK_Incomplete);
1346 }
1347
1348 /// \brief Determine why initialization failed.
1349 FailureKind getFailureKind() const {
1350 assert(Failed() && "Not an initialization failure!")(static_cast <bool> (Failed() && "Not an initialization failure!"
) ? void (0) : __assert_fail ("Failed() && \"Not an initialization failure!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Initialization.h"
, 1350, __extension__ __PRETTY_FUNCTION__))
;
1351 return Failure;
1352 }
1353
1354 /// \brief Dump a representation of this initialization sequence to
1355 /// the given stream, for debugging purposes.
1356 void dump(raw_ostream &OS) const;
1357
1358 /// \brief Dump a representation of this initialization sequence to
1359 /// standard error, for debugging purposes.
1360 void dump() const;
1361};
1362
1363} // namespace clang
1364
1365#endif // LLVM_CLANG_SEMA_INITIALIZATION_H