Bug Summary

File:tools/clang/lib/Sema/SemaDeclObjC.cpp
Warning:line 4879, column 15
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDeclObjC.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.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++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp

/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp

1//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for Objective C declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/RecursiveASTVisitor.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Sema/DeclSpec.h"
23#include "clang/Sema/Lookup.h"
24#include "clang/Sema/Scope.h"
25#include "clang/Sema/ScopeInfo.h"
26#include "clang/Sema/SemaInternal.h"
27#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31
32/// Check whether the given method, which must be in the 'init'
33/// family, is a valid member of that family.
34///
35/// \param receiverTypeIfCall - if null, check this as if declaring it;
36/// if non-null, check this as if making a call to it with the given
37/// receiver type
38///
39/// \return true to indicate that there was an error and appropriate
40/// actions were taken
41bool Sema::checkInitMethod(ObjCMethodDecl *method,
42 QualType receiverTypeIfCall) {
43 if (method->isInvalidDecl()) return true;
44
45 // This castAs is safe: methods that don't return an object
46 // pointer won't be inferred as inits and will reject an explicit
47 // objc_method_family(init).
48
49 // We ignore protocols here. Should we? What about Class?
50
51 const ObjCObjectType *result =
52 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
53
54 if (result->isObjCId()) {
55 return false;
56 } else if (result->isObjCClass()) {
57 // fall through: always an error
58 } else {
59 ObjCInterfaceDecl *resultClass = result->getInterface();
60 assert(resultClass && "unexpected object type!")((resultClass && "unexpected object type!") ? static_cast
<void> (0) : __assert_fail ("resultClass && \"unexpected object type!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 60, __PRETTY_FUNCTION__))
;
61
62 // It's okay for the result type to still be a forward declaration
63 // if we're checking an interface declaration.
64 if (!resultClass->hasDefinition()) {
65 if (receiverTypeIfCall.isNull() &&
66 !isa<ObjCImplementationDecl>(method->getDeclContext()))
67 return false;
68
69 // Otherwise, we try to compare class types.
70 } else {
71 // If this method was declared in a protocol, we can't check
72 // anything unless we have a receiver type that's an interface.
73 const ObjCInterfaceDecl *receiverClass = nullptr;
74 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
75 if (receiverTypeIfCall.isNull())
76 return false;
77
78 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
79 ->getInterfaceDecl();
80
81 // This can be null for calls to e.g. id<Foo>.
82 if (!receiverClass) return false;
83 } else {
84 receiverClass = method->getClassInterface();
85 assert(receiverClass && "method not associated with a class!")((receiverClass && "method not associated with a class!"
) ? static_cast<void> (0) : __assert_fail ("receiverClass && \"method not associated with a class!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 85, __PRETTY_FUNCTION__))
;
86 }
87
88 // If either class is a subclass of the other, it's fine.
89 if (receiverClass->isSuperClassOf(resultClass) ||
90 resultClass->isSuperClassOf(receiverClass))
91 return false;
92 }
93 }
94
95 SourceLocation loc = method->getLocation();
96
97 // If we're in a system header, and this is not a call, just make
98 // the method unusable.
99 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
100 method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
101 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
102 return true;
103 }
104
105 // Otherwise, it's an error.
106 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
107 method->setInvalidDecl();
108 return true;
109}
110
111/// Issue a warning if the parameter of the overridden method is non-escaping
112/// but the parameter of the overriding method is not.
113static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
114 Sema &S) {
115 if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) {
116 S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape);
117 S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape);
118 return false;
119 }
120
121 return true;
122}
123
124/// Produce additional diagnostics if a category conforms to a protocol that
125/// defines a method taking a non-escaping parameter.
126static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
127 const ObjCCategoryDecl *CD,
128 const ObjCProtocolDecl *PD, Sema &S) {
129 if (!diagnoseNoescape(NewD, OldD, S))
130 S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot)
131 << CD->IsClassExtension() << PD
132 << cast<ObjCMethodDecl>(NewD->getDeclContext());
133}
134
135void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
136 const ObjCMethodDecl *Overridden) {
137 if (Overridden->hasRelatedResultType() &&
138 !NewMethod->hasRelatedResultType()) {
139 // This can only happen when the method follows a naming convention that
140 // implies a related result type, and the original (overridden) method has
141 // a suitable return type, but the new (overriding) method does not have
142 // a suitable return type.
143 QualType ResultType = NewMethod->getReturnType();
144 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
145
146 // Figure out which class this method is part of, if any.
147 ObjCInterfaceDecl *CurrentClass
148 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
149 if (!CurrentClass) {
150 DeclContext *DC = NewMethod->getDeclContext();
151 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
152 CurrentClass = Cat->getClassInterface();
153 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
154 CurrentClass = Impl->getClassInterface();
155 else if (ObjCCategoryImplDecl *CatImpl
156 = dyn_cast<ObjCCategoryImplDecl>(DC))
157 CurrentClass = CatImpl->getClassInterface();
158 }
159
160 if (CurrentClass) {
161 Diag(NewMethod->getLocation(),
162 diag::warn_related_result_type_compatibility_class)
163 << Context.getObjCInterfaceType(CurrentClass)
164 << ResultType
165 << ResultTypeRange;
166 } else {
167 Diag(NewMethod->getLocation(),
168 diag::warn_related_result_type_compatibility_protocol)
169 << ResultType
170 << ResultTypeRange;
171 }
172
173 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
174 Diag(Overridden->getLocation(),
175 diag::note_related_result_type_family)
176 << /*overridden method*/ 0
177 << Family;
178 else
179 Diag(Overridden->getLocation(),
180 diag::note_related_result_type_overridden);
181 }
182
183 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
184 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
185 Diag(NewMethod->getLocation(),
186 getLangOpts().ObjCAutoRefCount
187 ? diag::err_nsreturns_retained_attribute_mismatch
188 : diag::warn_nsreturns_retained_attribute_mismatch)
189 << 1;
190 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
191 }
192 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
193 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
194 Diag(NewMethod->getLocation(),
195 getLangOpts().ObjCAutoRefCount
196 ? diag::err_nsreturns_retained_attribute_mismatch
197 : diag::warn_nsreturns_retained_attribute_mismatch)
198 << 0;
199 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
200 }
201
202 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
203 oe = Overridden->param_end();
204 for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
205 ne = NewMethod->param_end();
206 ni != ne && oi != oe; ++ni, ++oi) {
207 const ParmVarDecl *oldDecl = (*oi);
208 ParmVarDecl *newDecl = (*ni);
209 if (newDecl->hasAttr<NSConsumedAttr>() !=
210 oldDecl->hasAttr<NSConsumedAttr>()) {
211 Diag(newDecl->getLocation(),
212 getLangOpts().ObjCAutoRefCount
213 ? diag::err_nsconsumed_attribute_mismatch
214 : diag::warn_nsconsumed_attribute_mismatch);
215 Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
216 }
217
218 diagnoseNoescape(newDecl, oldDecl, *this);
219 }
220}
221
222/// Check a method declaration for compatibility with the Objective-C
223/// ARC conventions.
224bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
225 ObjCMethodFamily family = method->getMethodFamily();
226 switch (family) {
227 case OMF_None:
228 case OMF_finalize:
229 case OMF_retain:
230 case OMF_release:
231 case OMF_autorelease:
232 case OMF_retainCount:
233 case OMF_self:
234 case OMF_initialize:
235 case OMF_performSelector:
236 return false;
237
238 case OMF_dealloc:
239 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
240 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
241 if (ResultTypeRange.isInvalid())
242 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
243 << method->getReturnType()
244 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
245 else
246 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
247 << method->getReturnType()
248 << FixItHint::CreateReplacement(ResultTypeRange, "void");
249 return true;
250 }
251 return false;
252
253 case OMF_init:
254 // If the method doesn't obey the init rules, don't bother annotating it.
255 if (checkInitMethod(method, QualType()))
256 return true;
257
258 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
259
260 // Don't add a second copy of this attribute, but otherwise don't
261 // let it be suppressed.
262 if (method->hasAttr<NSReturnsRetainedAttr>())
263 return false;
264 break;
265
266 case OMF_alloc:
267 case OMF_copy:
268 case OMF_mutableCopy:
269 case OMF_new:
270 if (method->hasAttr<NSReturnsRetainedAttr>() ||
271 method->hasAttr<NSReturnsNotRetainedAttr>() ||
272 method->hasAttr<NSReturnsAutoreleasedAttr>())
273 return false;
274 break;
275 }
276
277 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
278 return false;
279}
280
281static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
282 SourceLocation ImplLoc) {
283 if (!ND)
284 return;
285 bool IsCategory = false;
286 StringRef RealizedPlatform;
287 AvailabilityResult Availability = ND->getAvailability(
288 /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(),
289 &RealizedPlatform);
290 if (Availability != AR_Deprecated) {
291 if (isa<ObjCMethodDecl>(ND)) {
292 if (Availability != AR_Unavailable)
293 return;
294 if (RealizedPlatform.empty())
295 RealizedPlatform = S.Context.getTargetInfo().getPlatformName();
296 // Warn about implementing unavailable methods, unless the unavailable
297 // is for an app extension.
298 if (RealizedPlatform.endswith("_app_extension"))
299 return;
300 S.Diag(ImplLoc, diag::warn_unavailable_def);
301 S.Diag(ND->getLocation(), diag::note_method_declared_at)
302 << ND->getDeclName();
303 return;
304 }
305 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
306 if (!CD->getClassInterface()->isDeprecated())
307 return;
308 ND = CD->getClassInterface();
309 IsCategory = true;
310 } else
311 return;
312 }
313 S.Diag(ImplLoc, diag::warn_deprecated_def)
314 << (isa<ObjCMethodDecl>(ND)
315 ? /*Method*/ 0
316 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
317 : /*Class*/ 1);
318 if (isa<ObjCMethodDecl>(ND))
319 S.Diag(ND->getLocation(), diag::note_method_declared_at)
320 << ND->getDeclName();
321 else
322 S.Diag(ND->getLocation(), diag::note_previous_decl)
323 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
324}
325
326/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
327/// pool.
328void Sema::AddAnyMethodToGlobalPool(Decl *D) {
329 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
330
331 // If we don't have a valid method decl, simply return.
332 if (!MDecl)
333 return;
334 if (MDecl->isInstanceMethod())
335 AddInstanceMethodToGlobalPool(MDecl, true);
336 else
337 AddFactoryMethodToGlobalPool(MDecl, true);
338}
339
340/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
341/// has explicit ownership attribute; false otherwise.
342static bool
343HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
344 QualType T = Param->getType();
345
346 if (const PointerType *PT = T->getAs<PointerType>()) {
347 T = PT->getPointeeType();
348 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
349 T = RT->getPointeeType();
350 } else {
351 return true;
352 }
353
354 // If we have a lifetime qualifier, but it's local, we must have
355 // inferred it. So, it is implicit.
356 return !T.getLocalQualifiers().hasObjCLifetime();
357}
358
359/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
360/// and user declared, in the method definition's AST.
361void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
362 ImplicitlyRetainedSelfLocs.clear();
363 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused")(((getCurMethodDecl() == nullptr) && "Methodparsing confused"
) ? static_cast<void> (0) : __assert_fail ("(getCurMethodDecl() == nullptr) && \"Methodparsing confused\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 363, __PRETTY_FUNCTION__))
;
364 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
365
366 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
367
368 // If we don't have a valid method decl, simply return.
369 if (!MDecl)
370 return;
371
372 QualType ResultType = MDecl->getReturnType();
373 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
374 !MDecl->isInvalidDecl() &&
375 RequireCompleteType(MDecl->getLocation(), ResultType,
376 diag::err_func_def_incomplete_result))
377 MDecl->setInvalidDecl();
378
379 // Allow all of Sema to see that we are entering a method definition.
380 PushDeclContext(FnBodyScope, MDecl);
381 PushFunctionScope();
382
383 // Create Decl objects for each parameter, entrring them in the scope for
384 // binding to their use.
385
386 // Insert the invisible arguments, self and _cmd!
387 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
388
389 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
390 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
391
392 // The ObjC parser requires parameter names so there's no need to check.
393 CheckParmsForFunctionDef(MDecl->parameters(),
394 /*CheckParameterNames=*/false);
395
396 // Introduce all of the other parameters into this scope.
397 for (auto *Param : MDecl->parameters()) {
398 if (!Param->isInvalidDecl() &&
399 getLangOpts().ObjCAutoRefCount &&
400 !HasExplicitOwnershipAttr(*this, Param))
401 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
402 Param->getType();
403
404 if (Param->getIdentifier())
405 PushOnScopeChains(Param, FnBodyScope);
406 }
407
408 // In ARC, disallow definition of retain/release/autorelease/retainCount
409 if (getLangOpts().ObjCAutoRefCount) {
410 switch (MDecl->getMethodFamily()) {
411 case OMF_retain:
412 case OMF_retainCount:
413 case OMF_release:
414 case OMF_autorelease:
415 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
416 << 0 << MDecl->getSelector();
417 break;
418
419 case OMF_None:
420 case OMF_dealloc:
421 case OMF_finalize:
422 case OMF_alloc:
423 case OMF_init:
424 case OMF_mutableCopy:
425 case OMF_copy:
426 case OMF_new:
427 case OMF_self:
428 case OMF_initialize:
429 case OMF_performSelector:
430 break;
431 }
432 }
433
434 // Warn on deprecated methods under -Wdeprecated-implementations,
435 // and prepare for warning on missing super calls.
436 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
437 ObjCMethodDecl *IMD =
438 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
439
440 if (IMD) {
441 ObjCImplDecl *ImplDeclOfMethodDef =
442 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
443 ObjCContainerDecl *ContDeclOfMethodDecl =
444 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
445 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
446 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
447 ImplDeclOfMethodDecl = OID->getImplementation();
448 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
449 if (CD->IsClassExtension()) {
450 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
451 ImplDeclOfMethodDecl = OID->getImplementation();
452 } else
453 ImplDeclOfMethodDecl = CD->getImplementation();
454 }
455 // No need to issue deprecated warning if deprecated mehod in class/category
456 // is being implemented in its own implementation (no overriding is involved).
457 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
458 DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation());
459 }
460
461 if (MDecl->getMethodFamily() == OMF_init) {
462 if (MDecl->isDesignatedInitializerForTheInterface()) {
463 getCurFunction()->ObjCIsDesignatedInit = true;
464 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
465 IC->getSuperClass() != nullptr;
466 } else if (IC->hasDesignatedInitializers()) {
467 getCurFunction()->ObjCIsSecondaryInit = true;
468 getCurFunction()->ObjCWarnForNoInitDelegation = true;
469 }
470 }
471
472 // If this is "dealloc" or "finalize", set some bit here.
473 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
474 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
475 // Only do this if the current class actually has a superclass.
476 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
477 ObjCMethodFamily Family = MDecl->getMethodFamily();
478 if (Family == OMF_dealloc) {
479 if (!(getLangOpts().ObjCAutoRefCount ||
480 getLangOpts().getGC() == LangOptions::GCOnly))
481 getCurFunction()->ObjCShouldCallSuper = true;
482
483 } else if (Family == OMF_finalize) {
484 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
485 getCurFunction()->ObjCShouldCallSuper = true;
486
487 } else {
488 const ObjCMethodDecl *SuperMethod =
489 SuperClass->lookupMethod(MDecl->getSelector(),
490 MDecl->isInstanceMethod());
491 getCurFunction()->ObjCShouldCallSuper =
492 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
493 }
494 }
495 }
496}
497
498namespace {
499
500// Callback to only accept typo corrections that are Objective-C classes.
501// If an ObjCInterfaceDecl* is given to the constructor, then the validation
502// function will reject corrections to that class.
503class ObjCInterfaceValidatorCCC final : public CorrectionCandidateCallback {
504 public:
505 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
506 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
507 : CurrentIDecl(IDecl) {}
508
509 bool ValidateCandidate(const TypoCorrection &candidate) override {
510 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
511 return ID && !declaresSameEntity(ID, CurrentIDecl);
512 }
513
514 std::unique_ptr<CorrectionCandidateCallback> clone() override {
515 return std::make_unique<ObjCInterfaceValidatorCCC>(*this);
516 }
517
518 private:
519 ObjCInterfaceDecl *CurrentIDecl;
520};
521
522} // end anonymous namespace
523
524static void diagnoseUseOfProtocols(Sema &TheSema,
525 ObjCContainerDecl *CD,
526 ObjCProtocolDecl *const *ProtoRefs,
527 unsigned NumProtoRefs,
528 const SourceLocation *ProtoLocs) {
529 assert(ProtoRefs)((ProtoRefs) ? static_cast<void> (0) : __assert_fail ("ProtoRefs"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 529, __PRETTY_FUNCTION__))
;
530 // Diagnose availability in the context of the ObjC container.
531 Sema::ContextRAII SavedContext(TheSema, CD);
532 for (unsigned i = 0; i < NumProtoRefs; ++i) {
533 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
534 /*UnknownObjCClass=*/nullptr,
535 /*ObjCPropertyAccess=*/false,
536 /*AvoidPartialAvailabilityChecks=*/true);
537 }
538}
539
540void Sema::
541ActOnSuperClassOfClassInterface(Scope *S,
542 SourceLocation AtInterfaceLoc,
543 ObjCInterfaceDecl *IDecl,
544 IdentifierInfo *ClassName,
545 SourceLocation ClassLoc,
546 IdentifierInfo *SuperName,
547 SourceLocation SuperLoc,
548 ArrayRef<ParsedType> SuperTypeArgs,
549 SourceRange SuperTypeArgsRange) {
550 // Check if a different kind of symbol declared in this scope.
551 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
552 LookupOrdinaryName);
553
554 if (!PrevDecl) {
555 // Try to correct for a typo in the superclass name without correcting
556 // to the class we're defining.
557 ObjCInterfaceValidatorCCC CCC(IDecl);
558 if (TypoCorrection Corrected = CorrectTypo(
559 DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName,
560 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
561 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
562 << SuperName << ClassName);
563 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
564 }
565 }
566
567 if (declaresSameEntity(PrevDecl, IDecl)) {
568 Diag(SuperLoc, diag::err_recursive_superclass)
569 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
570 IDecl->setEndOfDefinitionLoc(ClassLoc);
571 } else {
572 ObjCInterfaceDecl *SuperClassDecl =
573 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
574 QualType SuperClassType;
575
576 // Diagnose classes that inherit from deprecated classes.
577 if (SuperClassDecl) {
578 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
579 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
580 }
581
582 if (PrevDecl && !SuperClassDecl) {
583 // The previous declaration was not a class decl. Check if we have a
584 // typedef. If we do, get the underlying class type.
585 if (const TypedefNameDecl *TDecl =
586 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
587 QualType T = TDecl->getUnderlyingType();
588 if (T->isObjCObjectType()) {
589 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
590 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
591 SuperClassType = Context.getTypeDeclType(TDecl);
592
593 // This handles the following case:
594 // @interface NewI @end
595 // typedef NewI DeprI __attribute__((deprecated("blah")))
596 // @interface SI : DeprI /* warn here */ @end
597 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
598 }
599 }
600 }
601
602 // This handles the following case:
603 //
604 // typedef int SuperClass;
605 // @interface MyClass : SuperClass {} @end
606 //
607 if (!SuperClassDecl) {
608 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
609 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
610 }
611 }
612
613 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
614 if (!SuperClassDecl)
615 Diag(SuperLoc, diag::err_undef_superclass)
616 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
617 else if (RequireCompleteType(SuperLoc,
618 SuperClassType,
619 diag::err_forward_superclass,
620 SuperClassDecl->getDeclName(),
621 ClassName,
622 SourceRange(AtInterfaceLoc, ClassLoc))) {
623 SuperClassDecl = nullptr;
624 SuperClassType = QualType();
625 }
626 }
627
628 if (SuperClassType.isNull()) {
629 assert(!SuperClassDecl && "Failed to set SuperClassType?")((!SuperClassDecl && "Failed to set SuperClassType?")
? static_cast<void> (0) : __assert_fail ("!SuperClassDecl && \"Failed to set SuperClassType?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 629, __PRETTY_FUNCTION__))
;
630 return;
631 }
632
633 // Handle type arguments on the superclass.
634 TypeSourceInfo *SuperClassTInfo = nullptr;
635 if (!SuperTypeArgs.empty()) {
636 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
637 S,
638 SuperLoc,
639 CreateParsedType(SuperClassType,
640 nullptr),
641 SuperTypeArgsRange.getBegin(),
642 SuperTypeArgs,
643 SuperTypeArgsRange.getEnd(),
644 SourceLocation(),
645 { },
646 { },
647 SourceLocation());
648 if (!fullSuperClassType.isUsable())
649 return;
650
651 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
652 &SuperClassTInfo);
653 }
654
655 if (!SuperClassTInfo) {
656 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
657 SuperLoc);
658 }
659
660 IDecl->setSuperClass(SuperClassTInfo);
661 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getEndLoc());
662 }
663}
664
665DeclResult Sema::actOnObjCTypeParam(Scope *S,
666 ObjCTypeParamVariance variance,
667 SourceLocation varianceLoc,
668 unsigned index,
669 IdentifierInfo *paramName,
670 SourceLocation paramLoc,
671 SourceLocation colonLoc,
672 ParsedType parsedTypeBound) {
673 // If there was an explicitly-provided type bound, check it.
674 TypeSourceInfo *typeBoundInfo = nullptr;
675 if (parsedTypeBound) {
676 // The type bound can be any Objective-C pointer type.
677 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
678 if (typeBound->isObjCObjectPointerType()) {
679 // okay
680 } else if (typeBound->isObjCObjectType()) {
681 // The user forgot the * on an Objective-C pointer type, e.g.,
682 // "T : NSView".
683 SourceLocation starLoc = getLocForEndOfToken(
684 typeBoundInfo->getTypeLoc().getEndLoc());
685 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
686 diag::err_objc_type_param_bound_missing_pointer)
687 << typeBound << paramName
688 << FixItHint::CreateInsertion(starLoc, " *");
689
690 // Create a new type location builder so we can update the type
691 // location information we have.
692 TypeLocBuilder builder;
693 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
694
695 // Create the Objective-C pointer type.
696 typeBound = Context.getObjCObjectPointerType(typeBound);
697 ObjCObjectPointerTypeLoc newT
698 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
699 newT.setStarLoc(starLoc);
700
701 // Form the new type source information.
702 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
703 } else {
704 // Not a valid type bound.
705 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
706 diag::err_objc_type_param_bound_nonobject)
707 << typeBound << paramName;
708
709 // Forget the bound; we'll default to id later.
710 typeBoundInfo = nullptr;
711 }
712
713 // Type bounds cannot have qualifiers (even indirectly) or explicit
714 // nullability.
715 if (typeBoundInfo) {
716 QualType typeBound = typeBoundInfo->getType();
717 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
718 if (qual || typeBound.hasQualifiers()) {
719 bool diagnosed = false;
720 SourceRange rangeToRemove;
721 if (qual) {
722 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
723 rangeToRemove = attr.getLocalSourceRange();
724 if (attr.getTypePtr()->getImmediateNullability()) {
725 Diag(attr.getBeginLoc(),
726 diag::err_objc_type_param_bound_explicit_nullability)
727 << paramName << typeBound
728 << FixItHint::CreateRemoval(rangeToRemove);
729 diagnosed = true;
730 }
731 }
732 }
733
734 if (!diagnosed) {
735 Diag(qual ? qual.getBeginLoc()
736 : typeBoundInfo->getTypeLoc().getBeginLoc(),
737 diag::err_objc_type_param_bound_qualified)
738 << paramName << typeBound
739 << typeBound.getQualifiers().getAsString()
740 << FixItHint::CreateRemoval(rangeToRemove);
741 }
742
743 // If the type bound has qualifiers other than CVR, we need to strip
744 // them or we'll probably assert later when trying to apply new
745 // qualifiers.
746 Qualifiers quals = typeBound.getQualifiers();
747 quals.removeCVRQualifiers();
748 if (!quals.empty()) {
749 typeBoundInfo =
750 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
751 }
752 }
753 }
754 }
755
756 // If there was no explicit type bound (or we removed it due to an error),
757 // use 'id' instead.
758 if (!typeBoundInfo) {
759 colonLoc = SourceLocation();
760 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
761 }
762
763 // Create the type parameter.
764 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
765 index, paramLoc, paramName, colonLoc,
766 typeBoundInfo);
767}
768
769ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
770 SourceLocation lAngleLoc,
771 ArrayRef<Decl *> typeParamsIn,
772 SourceLocation rAngleLoc) {
773 // We know that the array only contains Objective-C type parameters.
774 ArrayRef<ObjCTypeParamDecl *>
775 typeParams(
776 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
777 typeParamsIn.size());
778
779 // Diagnose redeclarations of type parameters.
780 // We do this now because Objective-C type parameters aren't pushed into
781 // scope until later (after the instance variable block), but we want the
782 // diagnostics to occur right after we parse the type parameter list.
783 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
784 for (auto typeParam : typeParams) {
785 auto known = knownParams.find(typeParam->getIdentifier());
786 if (known != knownParams.end()) {
787 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
788 << typeParam->getIdentifier()
789 << SourceRange(known->second->getLocation());
790
791 typeParam->setInvalidDecl();
792 } else {
793 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
794
795 // Push the type parameter into scope.
796 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
797 }
798 }
799
800 // Create the parameter list.
801 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
802}
803
804void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
805 for (auto typeParam : *typeParamList) {
806 if (!typeParam->isInvalidDecl()) {
807 S->RemoveDecl(typeParam);
808 IdResolver.RemoveDecl(typeParam);
809 }
810 }
811}
812
813namespace {
814 /// The context in which an Objective-C type parameter list occurs, for use
815 /// in diagnostics.
816 enum class TypeParamListContext {
817 ForwardDeclaration,
818 Definition,
819 Category,
820 Extension
821 };
822} // end anonymous namespace
823
824/// Check consistency between two Objective-C type parameter lists, e.g.,
825/// between a category/extension and an \@interface or between an \@class and an
826/// \@interface.
827static bool checkTypeParamListConsistency(Sema &S,
828 ObjCTypeParamList *prevTypeParams,
829 ObjCTypeParamList *newTypeParams,
830 TypeParamListContext newContext) {
831 // If the sizes don't match, complain about that.
832 if (prevTypeParams->size() != newTypeParams->size()) {
833 SourceLocation diagLoc;
834 if (newTypeParams->size() > prevTypeParams->size()) {
835 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
836 } else {
837 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getEndLoc());
838 }
839
840 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
841 << static_cast<unsigned>(newContext)
842 << (newTypeParams->size() > prevTypeParams->size())
843 << prevTypeParams->size()
844 << newTypeParams->size();
845
846 return true;
847 }
848
849 // Match up the type parameters.
850 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
851 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
852 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
853
854 // Check for consistency of the variance.
855 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
856 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
857 newContext != TypeParamListContext::Definition) {
858 // When the new type parameter is invariant and is not part
859 // of the definition, just propagate the variance.
860 newTypeParam->setVariance(prevTypeParam->getVariance());
861 } else if (prevTypeParam->getVariance()
862 == ObjCTypeParamVariance::Invariant &&
863 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
864 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
865 ->getDefinition() == prevTypeParam->getDeclContext())) {
866 // When the old parameter is invariant and was not part of the
867 // definition, just ignore the difference because it doesn't
868 // matter.
869 } else {
870 {
871 // Diagnose the conflict and update the second declaration.
872 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
873 if (diagLoc.isInvalid())
874 diagLoc = newTypeParam->getBeginLoc();
875
876 auto diag = S.Diag(diagLoc,
877 diag::err_objc_type_param_variance_conflict)
878 << static_cast<unsigned>(newTypeParam->getVariance())
879 << newTypeParam->getDeclName()
880 << static_cast<unsigned>(prevTypeParam->getVariance())
881 << prevTypeParam->getDeclName();
882 switch (prevTypeParam->getVariance()) {
883 case ObjCTypeParamVariance::Invariant:
884 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
885 break;
886
887 case ObjCTypeParamVariance::Covariant:
888 case ObjCTypeParamVariance::Contravariant: {
889 StringRef newVarianceStr
890 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
891 ? "__covariant"
892 : "__contravariant";
893 if (newTypeParam->getVariance()
894 == ObjCTypeParamVariance::Invariant) {
895 diag << FixItHint::CreateInsertion(newTypeParam->getBeginLoc(),
896 (newVarianceStr + " ").str());
897 } else {
898 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
899 newVarianceStr);
900 }
901 }
902 }
903 }
904
905 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
906 << prevTypeParam->getDeclName();
907
908 // Override the variance.
909 newTypeParam->setVariance(prevTypeParam->getVariance());
910 }
911 }
912
913 // If the bound types match, there's nothing to do.
914 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
915 newTypeParam->getUnderlyingType()))
916 continue;
917
918 // If the new type parameter's bound was explicit, complain about it being
919 // different from the original.
920 if (newTypeParam->hasExplicitBound()) {
921 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
922 ->getTypeLoc().getSourceRange();
923 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
924 << newTypeParam->getUnderlyingType()
925 << newTypeParam->getDeclName()
926 << prevTypeParam->hasExplicitBound()
927 << prevTypeParam->getUnderlyingType()
928 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
929 << prevTypeParam->getDeclName()
930 << FixItHint::CreateReplacement(
931 newBoundRange,
932 prevTypeParam->getUnderlyingType().getAsString(
933 S.Context.getPrintingPolicy()));
934
935 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
936 << prevTypeParam->getDeclName();
937
938 // Override the new type parameter's bound type with the previous type,
939 // so that it's consistent.
940 newTypeParam->setTypeSourceInfo(
941 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
942 continue;
943 }
944
945 // The new type parameter got the implicit bound of 'id'. That's okay for
946 // categories and extensions (overwrite it later), but not for forward
947 // declarations and @interfaces, because those must be standalone.
948 if (newContext == TypeParamListContext::ForwardDeclaration ||
949 newContext == TypeParamListContext::Definition) {
950 // Diagnose this problem for forward declarations and definitions.
951 SourceLocation insertionLoc
952 = S.getLocForEndOfToken(newTypeParam->getLocation());
953 std::string newCode
954 = " : " + prevTypeParam->getUnderlyingType().getAsString(
955 S.Context.getPrintingPolicy());
956 S.Diag(newTypeParam->getLocation(),
957 diag::err_objc_type_param_bound_missing)
958 << prevTypeParam->getUnderlyingType()
959 << newTypeParam->getDeclName()
960 << (newContext == TypeParamListContext::ForwardDeclaration)
961 << FixItHint::CreateInsertion(insertionLoc, newCode);
962
963 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
964 << prevTypeParam->getDeclName();
965 }
966
967 // Update the new type parameter's bound to match the previous one.
968 newTypeParam->setTypeSourceInfo(
969 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
970 }
971
972 return false;
973}
974
975Decl *Sema::ActOnStartClassInterface(
976 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
977 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
978 IdentifierInfo *SuperName, SourceLocation SuperLoc,
979 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
980 Decl *const *ProtoRefs, unsigned NumProtoRefs,
981 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
982 const ParsedAttributesView &AttrList) {
983 assert(ClassName && "Missing class identifier")((ClassName && "Missing class identifier") ? static_cast
<void> (0) : __assert_fail ("ClassName && \"Missing class identifier\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 983, __PRETTY_FUNCTION__))
;
984
985 // Check for another declaration kind with the same name.
986 NamedDecl *PrevDecl =
987 LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
988 forRedeclarationInCurContext());
989
990 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
991 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
992 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
993 }
994
995 // Create a declaration to describe this @interface.
996 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
997
998 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
999 // A previous decl with a different name is because of
1000 // @compatibility_alias, for example:
1001 // \code
1002 // @class NewImage;
1003 // @compatibility_alias OldImage NewImage;
1004 // \endcode
1005 // A lookup for 'OldImage' will return the 'NewImage' decl.
1006 //
1007 // In such a case use the real declaration name, instead of the alias one,
1008 // otherwise we will break IdentifierResolver and redecls-chain invariants.
1009 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
1010 // has been aliased.
1011 ClassName = PrevIDecl->getIdentifier();
1012 }
1013
1014 // If there was a forward declaration with type parameters, check
1015 // for consistency.
1016 if (PrevIDecl) {
1017 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
1018 if (typeParamList) {
1019 // Both have type parameter lists; check for consistency.
1020 if (checkTypeParamListConsistency(*this, prevTypeParamList,
1021 typeParamList,
1022 TypeParamListContext::Definition)) {
1023 typeParamList = nullptr;
1024 }
1025 } else {
1026 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
1027 << ClassName;
1028 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
1029 << ClassName;
1030
1031 // Clone the type parameter list.
1032 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
1033 for (auto typeParam : *prevTypeParamList) {
1034 clonedTypeParams.push_back(
1035 ObjCTypeParamDecl::Create(
1036 Context,
1037 CurContext,
1038 typeParam->getVariance(),
1039 SourceLocation(),
1040 typeParam->getIndex(),
1041 SourceLocation(),
1042 typeParam->getIdentifier(),
1043 SourceLocation(),
1044 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
1045 }
1046
1047 typeParamList = ObjCTypeParamList::create(Context,
1048 SourceLocation(),
1049 clonedTypeParams,
1050 SourceLocation());
1051 }
1052 }
1053 }
1054
1055 ObjCInterfaceDecl *IDecl
1056 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
1057 typeParamList, PrevIDecl, ClassLoc);
1058 if (PrevIDecl) {
1059 // Class already seen. Was it a definition?
1060 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1061 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1062 << PrevIDecl->getDeclName();
1063 Diag(Def->getLocation(), diag::note_previous_definition);
1064 IDecl->setInvalidDecl();
1065 }
1066 }
1067
1068 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
1069 AddPragmaAttributes(TUScope, IDecl);
1070 PushOnScopeChains(IDecl, TUScope);
1071
1072 // Start the definition of this class. If we're in a redefinition case, there
1073 // may already be a definition, so we'll end up adding to it.
1074 if (!IDecl->hasDefinition())
1075 IDecl->startDefinition();
1076
1077 if (SuperName) {
1078 // Diagnose availability in the context of the @interface.
1079 ContextRAII SavedContext(*this, IDecl);
1080
1081 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1082 ClassName, ClassLoc,
1083 SuperName, SuperLoc, SuperTypeArgs,
1084 SuperTypeArgsRange);
1085 } else { // we have a root class.
1086 IDecl->setEndOfDefinitionLoc(ClassLoc);
1087 }
1088
1089 // Check then save referenced protocols.
1090 if (NumProtoRefs) {
1091 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1092 NumProtoRefs, ProtoLocs);
1093 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1094 ProtoLocs, Context);
1095 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
1096 }
1097
1098 CheckObjCDeclScope(IDecl);
1099 return ActOnObjCContainerStartDefinition(IDecl);
1100}
1101
1102/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1103/// typedef'ed use for a qualified super class and adds them to the list
1104/// of the protocols.
1105void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
1106 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1107 IdentifierInfo *SuperName,
1108 SourceLocation SuperLoc) {
1109 if (!SuperName)
1110 return;
1111 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1112 LookupOrdinaryName);
1113 if (!IDecl)
1114 return;
1115
1116 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1117 QualType T = TDecl->getUnderlyingType();
1118 if (T->isObjCObjectType())
1119 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
1120 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
1121 // FIXME: Consider whether this should be an invalid loc since the loc
1122 // is not actually pointing to a protocol name reference but to the
1123 // typedef reference. Note that the base class name loc is also pointing
1124 // at the typedef.
1125 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1126 }
1127 }
1128}
1129
1130/// ActOnCompatibilityAlias - this action is called after complete parsing of
1131/// a \@compatibility_alias declaration. It sets up the alias relationships.
1132Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1133 IdentifierInfo *AliasName,
1134 SourceLocation AliasLocation,
1135 IdentifierInfo *ClassName,
1136 SourceLocation ClassLocation) {
1137 // Look for previous declaration of alias name
1138 NamedDecl *ADecl =
1139 LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
1140 forRedeclarationInCurContext());
1141 if (ADecl) {
1142 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
1143 Diag(ADecl->getLocation(), diag::note_previous_declaration);
1144 return nullptr;
1145 }
1146 // Check for class declaration
1147 NamedDecl *CDeclU =
1148 LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
1149 forRedeclarationInCurContext());
1150 if (const TypedefNameDecl *TDecl =
1151 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
1152 QualType T = TDecl->getUnderlyingType();
1153 if (T->isObjCObjectType()) {
1154 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
1155 ClassName = IDecl->getIdentifier();
1156 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
1157 LookupOrdinaryName,
1158 forRedeclarationInCurContext());
1159 }
1160 }
1161 }
1162 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
1163 if (!CDecl) {
1164 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
1165 if (CDeclU)
1166 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
1167 return nullptr;
1168 }
1169
1170 // Everything checked out, instantiate a new alias declaration AST.
1171 ObjCCompatibleAliasDecl *AliasDecl =
1172 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
1173
1174 if (!CheckObjCDeclScope(AliasDecl))
1175 PushOnScopeChains(AliasDecl, TUScope);
1176
1177 return AliasDecl;
1178}
1179
1180bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
1181 IdentifierInfo *PName,
1182 SourceLocation &Ploc, SourceLocation PrevLoc,
1183 const ObjCList<ObjCProtocolDecl> &PList) {
1184
1185 bool res = false;
1186 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1187 E = PList.end(); I != E; ++I) {
1188 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1189 Ploc)) {
1190 if (PDecl->getIdentifier() == PName) {
1191 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1192 Diag(PrevLoc, diag::note_previous_definition);
1193 res = true;
1194 }
1195
1196 if (!PDecl->hasDefinition())
1197 continue;
1198
1199 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1200 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1201 res = true;
1202 }
1203 }
1204 return res;
1205}
1206
1207Decl *Sema::ActOnStartProtocolInterface(
1208 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
1209 SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
1210 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1211 const ParsedAttributesView &AttrList) {
1212 bool err = false;
1213 // FIXME: Deal with AttrList.
1214 assert(ProtocolName && "Missing protocol identifier")((ProtocolName && "Missing protocol identifier") ? static_cast
<void> (0) : __assert_fail ("ProtocolName && \"Missing protocol identifier\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 1214, __PRETTY_FUNCTION__))
;
1215 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
1216 forRedeclarationInCurContext());
1217 ObjCProtocolDecl *PDecl = nullptr;
1218 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
1219 // If we already have a definition, complain.
1220 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1221 Diag(Def->getLocation(), diag::note_previous_definition);
1222
1223 // Create a new protocol that is completely distinct from previous
1224 // declarations, and do not make this protocol available for name lookup.
1225 // That way, we'll end up completely ignoring the duplicate.
1226 // FIXME: Can we turn this into an error?
1227 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1228 ProtocolLoc, AtProtoInterfaceLoc,
1229 /*PrevDecl=*/nullptr);
1230
1231 // If we are using modules, add the decl to the context in order to
1232 // serialize something meaningful.
1233 if (getLangOpts().Modules)
1234 PushOnScopeChains(PDecl, TUScope);
1235 PDecl->startDefinition();
1236 } else {
1237 if (PrevDecl) {
1238 // Check for circular dependencies among protocol declarations. This can
1239 // only happen if this protocol was forward-declared.
1240 ObjCList<ObjCProtocolDecl> PList;
1241 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1242 err = CheckForwardProtocolDeclarationForCircularDependency(
1243 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
1244 }
1245
1246 // Create the new declaration.
1247 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1248 ProtocolLoc, AtProtoInterfaceLoc,
1249 /*PrevDecl=*/PrevDecl);
1250
1251 PushOnScopeChains(PDecl, TUScope);
1252 PDecl->startDefinition();
1253 }
1254
1255 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
1256 AddPragmaAttributes(TUScope, PDecl);
1257
1258 // Merge attributes from previous declarations.
1259 if (PrevDecl)
1260 mergeDeclAttributes(PDecl, PrevDecl);
1261
1262 if (!err && NumProtoRefs ) {
1263 /// Check then save referenced protocols.
1264 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1265 NumProtoRefs, ProtoLocs);
1266 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1267 ProtoLocs, Context);
1268 }
1269
1270 CheckObjCDeclScope(PDecl);
1271 return ActOnObjCContainerStartDefinition(PDecl);
1272}
1273
1274static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1275 ObjCProtocolDecl *&UndefinedProtocol) {
1276 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1277 UndefinedProtocol = PDecl;
1278 return true;
1279 }
1280
1281 for (auto *PI : PDecl->protocols())
1282 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1283 UndefinedProtocol = PI;
1284 return true;
1285 }
1286 return false;
1287}
1288
1289/// FindProtocolDeclaration - This routine looks up protocols and
1290/// issues an error if they are not declared. It returns list of
1291/// protocol declarations in its 'Protocols' argument.
1292void
1293Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
1294 ArrayRef<IdentifierLocPair> ProtocolId,
1295 SmallVectorImpl<Decl *> &Protocols) {
1296 for (const IdentifierLocPair &Pair : ProtocolId) {
1297 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
1298 if (!PDecl) {
1299 DeclFilterCCC<ObjCProtocolDecl> CCC{};
1300 TypoCorrection Corrected = CorrectTypo(
1301 DeclarationNameInfo(Pair.first, Pair.second), LookupObjCProtocolName,
1302 TUScope, nullptr, CCC, CTK_ErrorRecovery);
1303 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1304 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
1305 << Pair.first);
1306 }
1307
1308 if (!PDecl) {
1309 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
1310 continue;
1311 }
1312 // If this is a forward protocol declaration, get its definition.
1313 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1314 PDecl = PDecl->getDefinition();
1315
1316 // For an objc container, delay protocol reference checking until after we
1317 // can set the objc decl as the availability context, otherwise check now.
1318 if (!ForObjCContainer) {
1319 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
1320 }
1321
1322 // If this is a forward declaration and we are supposed to warn in this
1323 // case, do it.
1324 // FIXME: Recover nicely in the hidden case.
1325 ObjCProtocolDecl *UndefinedProtocol;
1326
1327 if (WarnOnDeclarations &&
1328 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
1329 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
1330 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1331 << UndefinedProtocol;
1332 }
1333 Protocols.push_back(PDecl);
1334 }
1335}
1336
1337namespace {
1338// Callback to only accept typo corrections that are either
1339// Objective-C protocols or valid Objective-C type arguments.
1340class ObjCTypeArgOrProtocolValidatorCCC final
1341 : public CorrectionCandidateCallback {
1342 ASTContext &Context;
1343 Sema::LookupNameKind LookupKind;
1344 public:
1345 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1346 Sema::LookupNameKind lookupKind)
1347 : Context(context), LookupKind(lookupKind) { }
1348
1349 bool ValidateCandidate(const TypoCorrection &candidate) override {
1350 // If we're allowed to find protocols and we have a protocol, accept it.
1351 if (LookupKind != Sema::LookupOrdinaryName) {
1352 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1353 return true;
1354 }
1355
1356 // If we're allowed to find type names and we have one, accept it.
1357 if (LookupKind != Sema::LookupObjCProtocolName) {
1358 // If we have a type declaration, we might accept this result.
1359 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1360 // If we found a tag declaration outside of C++, skip it. This
1361 // can happy because we look for any name when there is no
1362 // bias to protocol or type names.
1363 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1364 return false;
1365
1366 // Make sure the type is something we would accept as a type
1367 // argument.
1368 auto type = Context.getTypeDeclType(typeDecl);
1369 if (type->isObjCObjectPointerType() ||
1370 type->isBlockPointerType() ||
1371 type->isDependentType() ||
1372 type->isObjCObjectType())
1373 return true;
1374
1375 return false;
1376 }
1377
1378 // If we have an Objective-C class type, accept it; there will
1379 // be another fix to add the '*'.
1380 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1381 return true;
1382
1383 return false;
1384 }
1385
1386 return false;
1387 }
1388
1389 std::unique_ptr<CorrectionCandidateCallback> clone() override {
1390 return std::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(*this);
1391 }
1392};
1393} // end anonymous namespace
1394
1395void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1396 SourceLocation ProtocolLoc,
1397 IdentifierInfo *TypeArgId,
1398 SourceLocation TypeArgLoc,
1399 bool SelectProtocolFirst) {
1400 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1401 << SelectProtocolFirst << TypeArgId << ProtocolId
1402 << SourceRange(ProtocolLoc);
1403}
1404
1405void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1406 Scope *S,
1407 ParsedType baseType,
1408 SourceLocation lAngleLoc,
1409 ArrayRef<IdentifierInfo *> identifiers,
1410 ArrayRef<SourceLocation> identifierLocs,
1411 SourceLocation rAngleLoc,
1412 SourceLocation &typeArgsLAngleLoc,
1413 SmallVectorImpl<ParsedType> &typeArgs,
1414 SourceLocation &typeArgsRAngleLoc,
1415 SourceLocation &protocolLAngleLoc,
1416 SmallVectorImpl<Decl *> &protocols,
1417 SourceLocation &protocolRAngleLoc,
1418 bool warnOnIncompleteProtocols) {
1419 // Local function that updates the declaration specifiers with
1420 // protocol information.
1421 unsigned numProtocolsResolved = 0;
1422 auto resolvedAsProtocols = [&] {
1423 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols")((numProtocolsResolved == identifiers.size() && "Unresolved protocols"
) ? static_cast<void> (0) : __assert_fail ("numProtocolsResolved == identifiers.size() && \"Unresolved protocols\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 1423, __PRETTY_FUNCTION__))
;
1424
1425 // Determine whether the base type is a parameterized class, in
1426 // which case we want to warn about typos such as
1427 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1428 ObjCInterfaceDecl *baseClass = nullptr;
1429 QualType base = GetTypeFromParser(baseType, nullptr);
1430 bool allAreTypeNames = false;
1431 SourceLocation firstClassNameLoc;
1432 if (!base.isNull()) {
1433 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1434 baseClass = objcObjectType->getInterface();
1435 if (baseClass) {
1436 if (auto typeParams = baseClass->getTypeParamList()) {
1437 if (typeParams->size() == numProtocolsResolved) {
1438 // Note that we should be looking for type names, too.
1439 allAreTypeNames = true;
1440 }
1441 }
1442 }
1443 }
1444 }
1445
1446 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
1447 ObjCProtocolDecl *&proto
1448 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
1449 // For an objc container, delay protocol reference checking until after we
1450 // can set the objc decl as the availability context, otherwise check now.
1451 if (!warnOnIncompleteProtocols) {
1452 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1453 }
1454
1455 // If this is a forward protocol declaration, get its definition.
1456 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1457 proto = proto->getDefinition();
1458
1459 // If this is a forward declaration and we are supposed to warn in this
1460 // case, do it.
1461 // FIXME: Recover nicely in the hidden case.
1462 ObjCProtocolDecl *forwardDecl = nullptr;
1463 if (warnOnIncompleteProtocols &&
1464 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1465 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1466 << proto->getDeclName();
1467 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1468 << forwardDecl;
1469 }
1470
1471 // If everything this far has been a type name (and we care
1472 // about such things), check whether this name refers to a type
1473 // as well.
1474 if (allAreTypeNames) {
1475 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1476 LookupOrdinaryName)) {
1477 if (isa<ObjCInterfaceDecl>(decl)) {
1478 if (firstClassNameLoc.isInvalid())
1479 firstClassNameLoc = identifierLocs[i];
1480 } else if (!isa<TypeDecl>(decl)) {
1481 // Not a type.
1482 allAreTypeNames = false;
1483 }
1484 } else {
1485 allAreTypeNames = false;
1486 }
1487 }
1488 }
1489
1490 // All of the protocols listed also have type names, and at least
1491 // one is an Objective-C class name. Check whether all of the
1492 // protocol conformances are declared by the base class itself, in
1493 // which case we warn.
1494 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1495 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1496 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1497 bool allProtocolsDeclared = true;
1498 for (auto proto : protocols) {
1499 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1500 allProtocolsDeclared = false;
1501 break;
1502 }
1503 }
1504
1505 if (allProtocolsDeclared) {
1506 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1507 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
1508 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1509 " *");
1510 }
1511 }
1512
1513 protocolLAngleLoc = lAngleLoc;
1514 protocolRAngleLoc = rAngleLoc;
1515 assert(protocols.size() == identifierLocs.size())((protocols.size() == identifierLocs.size()) ? static_cast<
void> (0) : __assert_fail ("protocols.size() == identifierLocs.size()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 1515, __PRETTY_FUNCTION__))
;
1516 };
1517
1518 // Attempt to resolve all of the identifiers as protocols.
1519 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1520 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1521 protocols.push_back(proto);
1522 if (proto)
1523 ++numProtocolsResolved;
1524 }
1525
1526 // If all of the names were protocols, these were protocol qualifiers.
1527 if (numProtocolsResolved == identifiers.size())
1528 return resolvedAsProtocols();
1529
1530 // Attempt to resolve all of the identifiers as type names or
1531 // Objective-C class names. The latter is technically ill-formed,
1532 // but is probably something like \c NSArray<NSView *> missing the
1533 // \c*.
1534 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1535 SmallVector<TypeOrClassDecl, 4> typeDecls;
1536 unsigned numTypeDeclsResolved = 0;
1537 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1538 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1539 LookupOrdinaryName);
1540 if (!decl) {
1541 typeDecls.push_back(TypeOrClassDecl());
1542 continue;
1543 }
1544
1545 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1546 typeDecls.push_back(typeDecl);
1547 ++numTypeDeclsResolved;
1548 continue;
1549 }
1550
1551 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1552 typeDecls.push_back(objcClass);
1553 ++numTypeDeclsResolved;
1554 continue;
1555 }
1556
1557 typeDecls.push_back(TypeOrClassDecl());
1558 }
1559
1560 AttributeFactory attrFactory;
1561
1562 // Local function that forms a reference to the given type or
1563 // Objective-C class declaration.
1564 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1565 -> TypeResult {
1566 // Form declaration specifiers. They simply refer to the type.
1567 DeclSpec DS(attrFactory);
1568 const char* prevSpec; // unused
1569 unsigned diagID; // unused
1570 QualType type;
1571 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1572 type = Context.getTypeDeclType(actualTypeDecl);
1573 else
1574 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1575 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1576 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1577 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1578 parsedType, Context.getPrintingPolicy());
1579 // Use the identifier location for the type source range.
1580 DS.SetRangeStart(loc);
1581 DS.SetRangeEnd(loc);
1582
1583 // Form the declarator.
1584 Declarator D(DS, DeclaratorContext::TypeNameContext);
1585
1586 // If we have a typedef of an Objective-C class type that is missing a '*',
1587 // add the '*'.
1588 if (type->getAs<ObjCInterfaceType>()) {
1589 SourceLocation starLoc = getLocForEndOfToken(loc);
1590 D.AddTypeInfo(DeclaratorChunk::getPointer(/*TypeQuals=*/0, starLoc,
1591 SourceLocation(),
1592 SourceLocation(),
1593 SourceLocation(),
1594 SourceLocation(),
1595 SourceLocation()),
1596 starLoc);
1597
1598 // Diagnose the missing '*'.
1599 Diag(loc, diag::err_objc_type_arg_missing_star)
1600 << type
1601 << FixItHint::CreateInsertion(starLoc, " *");
1602 }
1603
1604 // Convert this to a type.
1605 return ActOnTypeName(S, D);
1606 };
1607
1608 // Local function that updates the declaration specifiers with
1609 // type argument information.
1610 auto resolvedAsTypeDecls = [&] {
1611 // We did not resolve these as protocols.
1612 protocols.clear();
1613
1614 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl")((numTypeDeclsResolved == identifiers.size() && "Unresolved type decl"
) ? static_cast<void> (0) : __assert_fail ("numTypeDeclsResolved == identifiers.size() && \"Unresolved type decl\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 1614, __PRETTY_FUNCTION__))
;
1615 // Map type declarations to type arguments.
1616 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1617 // Map type reference to a type.
1618 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
1619 if (!type.isUsable()) {
1620 typeArgs.clear();
1621 return;
1622 }
1623
1624 typeArgs.push_back(type.get());
1625 }
1626
1627 typeArgsLAngleLoc = lAngleLoc;
1628 typeArgsRAngleLoc = rAngleLoc;
1629 };
1630
1631 // If all of the identifiers can be resolved as type names or
1632 // Objective-C class names, we have type arguments.
1633 if (numTypeDeclsResolved == identifiers.size())
1634 return resolvedAsTypeDecls();
1635
1636 // Error recovery: some names weren't found, or we have a mix of
1637 // type and protocol names. Go resolve all of the unresolved names
1638 // and complain if we can't find a consistent answer.
1639 LookupNameKind lookupKind = LookupAnyName;
1640 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1641 // If we already have a protocol or type. Check whether it is the
1642 // right thing.
1643 if (protocols[i] || typeDecls[i]) {
1644 // If we haven't figured out whether we want types or protocols
1645 // yet, try to figure it out from this name.
1646 if (lookupKind == LookupAnyName) {
1647 // If this name refers to both a protocol and a type (e.g., \c
1648 // NSObject), don't conclude anything yet.
1649 if (protocols[i] && typeDecls[i])
1650 continue;
1651
1652 // Otherwise, let this name decide whether we'll be correcting
1653 // toward types or protocols.
1654 lookupKind = protocols[i] ? LookupObjCProtocolName
1655 : LookupOrdinaryName;
1656 continue;
1657 }
1658
1659 // If we want protocols and we have a protocol, there's nothing
1660 // more to do.
1661 if (lookupKind == LookupObjCProtocolName && protocols[i])
1662 continue;
1663
1664 // If we want types and we have a type declaration, there's
1665 // nothing more to do.
1666 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1667 continue;
1668
1669 // We have a conflict: some names refer to protocols and others
1670 // refer to types.
1671 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1672 identifiers[i], identifierLocs[i],
1673 protocols[i] != nullptr);
1674
1675 protocols.clear();
1676 typeArgs.clear();
1677 return;
1678 }
1679
1680 // Perform typo correction on the name.
1681 ObjCTypeArgOrProtocolValidatorCCC CCC(Context, lookupKind);
1682 TypoCorrection corrected =
1683 CorrectTypo(DeclarationNameInfo(identifiers[i], identifierLocs[i]),
1684 lookupKind, S, nullptr, CCC, CTK_ErrorRecovery);
1685 if (corrected) {
1686 // Did we find a protocol?
1687 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1688 diagnoseTypo(corrected,
1689 PDiag(diag::err_undeclared_protocol_suggest)
1690 << identifiers[i]);
1691 lookupKind = LookupObjCProtocolName;
1692 protocols[i] = proto;
1693 ++numProtocolsResolved;
1694 continue;
1695 }
1696
1697 // Did we find a type?
1698 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1699 diagnoseTypo(corrected,
1700 PDiag(diag::err_unknown_typename_suggest)
1701 << identifiers[i]);
1702 lookupKind = LookupOrdinaryName;
1703 typeDecls[i] = typeDecl;
1704 ++numTypeDeclsResolved;
1705 continue;
1706 }
1707
1708 // Did we find an Objective-C class?
1709 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1710 diagnoseTypo(corrected,
1711 PDiag(diag::err_unknown_type_or_class_name_suggest)
1712 << identifiers[i] << true);
1713 lookupKind = LookupOrdinaryName;
1714 typeDecls[i] = objcClass;
1715 ++numTypeDeclsResolved;
1716 continue;
1717 }
1718 }
1719
1720 // We couldn't find anything.
1721 Diag(identifierLocs[i],
1722 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1723 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1724 : diag::err_unknown_typename))
1725 << identifiers[i];
1726 protocols.clear();
1727 typeArgs.clear();
1728 return;
1729 }
1730
1731 // If all of the names were (corrected to) protocols, these were
1732 // protocol qualifiers.
1733 if (numProtocolsResolved == identifiers.size())
1734 return resolvedAsProtocols();
1735
1736 // Otherwise, all of the names were (corrected to) types.
1737 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?")((numTypeDeclsResolved == identifiers.size() && "Not all types?"
) ? static_cast<void> (0) : __assert_fail ("numTypeDeclsResolved == identifiers.size() && \"Not all types?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 1737, __PRETTY_FUNCTION__))
;
1738 return resolvedAsTypeDecls();
1739}
1740
1741/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
1742/// a class method in its extension.
1743///
1744void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
1745 ObjCInterfaceDecl *ID) {
1746 if (!ID)
1747 return; // Possibly due to previous error
1748
1749 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
1750 for (auto *MD : ID->methods())
1751 MethodMap[MD->getSelector()] = MD;
1752
1753 if (MethodMap.empty())
1754 return;
1755 for (const auto *Method : CAT->methods()) {
1756 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
1757 if (PrevMethod &&
1758 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1759 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1760 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1761 << Method->getDeclName();
1762 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1763 }
1764 }
1765}
1766
1767/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
1768Sema::DeclGroupPtrTy
1769Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
1770 ArrayRef<IdentifierLocPair> IdentList,
1771 const ParsedAttributesView &attrList) {
1772 SmallVector<Decl *, 8> DeclsInGroup;
1773 for (const IdentifierLocPair &IdentPair : IdentList) {
1774 IdentifierInfo *Ident = IdentPair.first;
1775 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
1776 forRedeclarationInCurContext());
1777 ObjCProtocolDecl *PDecl
1778 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
1779 IdentPair.second, AtProtocolLoc,
1780 PrevDecl);
1781
1782 PushOnScopeChains(PDecl, TUScope);
1783 CheckObjCDeclScope(PDecl);
1784
1785 ProcessDeclAttributeList(TUScope, PDecl, attrList);
1786 AddPragmaAttributes(TUScope, PDecl);
1787
1788 if (PrevDecl)
1789 mergeDeclAttributes(PDecl, PrevDecl);
1790
1791 DeclsInGroup.push_back(PDecl);
1792 }
1793
1794 return BuildDeclaratorGroup(DeclsInGroup);
1795}
1796
1797Decl *Sema::ActOnStartCategoryInterface(
1798 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
1799 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
1800 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1801 Decl *const *ProtoRefs, unsigned NumProtoRefs,
1802 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1803 const ParsedAttributesView &AttrList) {
1804 ObjCCategoryDecl *CDecl;
1805 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1806
1807 /// Check that class of this category is already completely declared.
1808
1809 if (!IDecl
1810 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1811 diag::err_category_forward_interface,
1812 CategoryName == nullptr)) {
1813 // Create an invalid ObjCCategoryDecl to serve as context for
1814 // the enclosing method declarations. We mark the decl invalid
1815 // to make it clear that this isn't a valid AST.
1816 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1817 ClassLoc, CategoryLoc, CategoryName,
1818 IDecl, typeParamList);
1819 CDecl->setInvalidDecl();
1820 CurContext->addDecl(CDecl);
1821
1822 if (!IDecl)
1823 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1824 return ActOnObjCContainerStartDefinition(CDecl);
1825 }
1826
1827 if (!CategoryName && IDecl->getImplementation()) {
1828 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1829 Diag(IDecl->getImplementation()->getLocation(),
1830 diag::note_implementation_declared);
1831 }
1832
1833 if (CategoryName) {
1834 /// Check for duplicate interface declaration for this category
1835 if (ObjCCategoryDecl *Previous
1836 = IDecl->FindCategoryDeclaration(CategoryName)) {
1837 // Class extensions can be declared multiple times, categories cannot.
1838 Diag(CategoryLoc, diag::warn_dup_category_def)
1839 << ClassName << CategoryName;
1840 Diag(Previous->getLocation(), diag::note_previous_definition);
1841 }
1842 }
1843
1844 // If we have a type parameter list, check it.
1845 if (typeParamList) {
1846 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1847 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1848 CategoryName
1849 ? TypeParamListContext::Category
1850 : TypeParamListContext::Extension))
1851 typeParamList = nullptr;
1852 } else {
1853 Diag(typeParamList->getLAngleLoc(),
1854 diag::err_objc_parameterized_category_nonclass)
1855 << (CategoryName != nullptr)
1856 << ClassName
1857 << typeParamList->getSourceRange();
1858
1859 typeParamList = nullptr;
1860 }
1861 }
1862
1863 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1864 ClassLoc, CategoryLoc, CategoryName, IDecl,
1865 typeParamList);
1866 // FIXME: PushOnScopeChains?
1867 CurContext->addDecl(CDecl);
1868
1869 // Process the attributes before looking at protocols to ensure that the
1870 // availability attribute is attached to the category to provide availability
1871 // checking for protocol uses.
1872 ProcessDeclAttributeList(TUScope, CDecl, AttrList);
1873 AddPragmaAttributes(TUScope, CDecl);
1874
1875 if (NumProtoRefs) {
1876 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1877 NumProtoRefs, ProtoLocs);
1878 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1879 ProtoLocs, Context);
1880 // Protocols in the class extension belong to the class.
1881 if (CDecl->IsClassExtension())
1882 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
1883 NumProtoRefs, Context);
1884 }
1885
1886 CheckObjCDeclScope(CDecl);
1887 return ActOnObjCContainerStartDefinition(CDecl);
1888}
1889
1890/// ActOnStartCategoryImplementation - Perform semantic checks on the
1891/// category implementation declaration and build an ObjCCategoryImplDecl
1892/// object.
1893Decl *Sema::ActOnStartCategoryImplementation(
1894 SourceLocation AtCatImplLoc,
1895 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1896 IdentifierInfo *CatName, SourceLocation CatLoc,
1897 const ParsedAttributesView &Attrs) {
1898 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1899 ObjCCategoryDecl *CatIDecl = nullptr;
1900 if (IDecl && IDecl->hasDefinition()) {
1901 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1902 if (!CatIDecl) {
1903 // Category @implementation with no corresponding @interface.
1904 // Create and install one.
1905 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1906 ClassLoc, CatLoc,
1907 CatName, IDecl,
1908 /*typeParamList=*/nullptr);
1909 CatIDecl->setImplicit();
1910 }
1911 }
1912
1913 ObjCCategoryImplDecl *CDecl =
1914 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
1915 ClassLoc, AtCatImplLoc, CatLoc);
1916 /// Check that class of this category is already completely declared.
1917 if (!IDecl) {
1918 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1919 CDecl->setInvalidDecl();
1920 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1921 diag::err_undef_interface)) {
1922 CDecl->setInvalidDecl();
1923 }
1924
1925 ProcessDeclAttributeList(TUScope, CDecl, Attrs);
1926 AddPragmaAttributes(TUScope, CDecl);
1927
1928 // FIXME: PushOnScopeChains?
1929 CurContext->addDecl(CDecl);
1930
1931 // If the interface has the objc_runtime_visible attribute, we
1932 // cannot implement a category for it.
1933 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1934 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1935 << IDecl->getDeclName();
1936 }
1937
1938 /// Check that CatName, category name, is not used in another implementation.
1939 if (CatIDecl) {
1940 if (CatIDecl->getImplementation()) {
1941 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1942 << CatName;
1943 Diag(CatIDecl->getImplementation()->getLocation(),
1944 diag::note_previous_definition);
1945 CDecl->setInvalidDecl();
1946 } else {
1947 CatIDecl->setImplementation(CDecl);
1948 // Warn on implementating category of deprecated class under
1949 // -Wdeprecated-implementations flag.
1950 DiagnoseObjCImplementedDeprecations(*this, CatIDecl,
1951 CDecl->getLocation());
1952 }
1953 }
1954
1955 CheckObjCDeclScope(CDecl);
1956 return ActOnObjCContainerStartDefinition(CDecl);
1957}
1958
1959Decl *Sema::ActOnStartClassImplementation(
1960 SourceLocation AtClassImplLoc,
1961 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1962 IdentifierInfo *SuperClassname,
1963 SourceLocation SuperClassLoc,
1964 const ParsedAttributesView &Attrs) {
1965 ObjCInterfaceDecl *IDecl = nullptr;
1966 // Check for another declaration kind with the same name.
1967 NamedDecl *PrevDecl
1968 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1969 forRedeclarationInCurContext());
1970 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1971 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1972 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1973 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1974 // FIXME: This will produce an error if the definition of the interface has
1975 // been imported from a module but is not visible.
1976 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1977 diag::warn_undef_interface);
1978 } else {
1979 // We did not find anything with the name ClassName; try to correct for
1980 // typos in the class name.
1981 ObjCInterfaceValidatorCCC CCC{};
1982 TypoCorrection Corrected =
1983 CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc),
1984 LookupOrdinaryName, TUScope, nullptr, CCC, CTK_NonError);
1985 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1986 // Suggest the (potentially) correct interface name. Don't provide a
1987 // code-modification hint or use the typo name for recovery, because
1988 // this is just a warning. The program may actually be correct.
1989 diagnoseTypo(Corrected,
1990 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1991 /*ErrorRecovery*/false);
1992 } else {
1993 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1994 }
1995 }
1996
1997 // Check that super class name is valid class name
1998 ObjCInterfaceDecl *SDecl = nullptr;
1999 if (SuperClassname) {
2000 // Check if a different kind of symbol declared in this scope.
2001 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
2002 LookupOrdinaryName);
2003 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2004 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
2005 << SuperClassname;
2006 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2007 } else {
2008 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
2009 if (SDecl && !SDecl->hasDefinition())
2010 SDecl = nullptr;
2011 if (!SDecl)
2012 Diag(SuperClassLoc, diag::err_undef_superclass)
2013 << SuperClassname << ClassName;
2014 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
2015 // This implementation and its interface do not have the same
2016 // super class.
2017 Diag(SuperClassLoc, diag::err_conflicting_super_class)
2018 << SDecl->getDeclName();
2019 Diag(SDecl->getLocation(), diag::note_previous_definition);
2020 }
2021 }
2022 }
2023
2024 if (!IDecl) {
2025 // Legacy case of @implementation with no corresponding @interface.
2026 // Build, chain & install the interface decl into the identifier.
2027
2028 // FIXME: Do we support attributes on the @implementation? If so we should
2029 // copy them over.
2030 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
2031 ClassName, /*typeParamList=*/nullptr,
2032 /*PrevDecl=*/nullptr, ClassLoc,
2033 true);
2034 AddPragmaAttributes(TUScope, IDecl);
2035 IDecl->startDefinition();
2036 if (SDecl) {
2037 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
2038 Context.getObjCInterfaceType(SDecl),
2039 SuperClassLoc));
2040 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2041 } else {
2042 IDecl->setEndOfDefinitionLoc(ClassLoc);
2043 }
2044
2045 PushOnScopeChains(IDecl, TUScope);
2046 } else {
2047 // Mark the interface as being completed, even if it was just as
2048 // @class ....;
2049 // declaration; the user cannot reopen it.
2050 if (!IDecl->hasDefinition())
2051 IDecl->startDefinition();
2052 }
2053
2054 ObjCImplementationDecl* IMPDecl =
2055 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
2056 ClassLoc, AtClassImplLoc, SuperClassLoc);
2057
2058 ProcessDeclAttributeList(TUScope, IMPDecl, Attrs);
2059 AddPragmaAttributes(TUScope, IMPDecl);
2060
2061 if (CheckObjCDeclScope(IMPDecl))
2062 return ActOnObjCContainerStartDefinition(IMPDecl);
2063
2064 // Check that there is no duplicate implementation of this class.
2065 if (IDecl->getImplementation()) {
2066 // FIXME: Don't leak everything!
2067 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
2068 Diag(IDecl->getImplementation()->getLocation(),
2069 diag::note_previous_definition);
2070 IMPDecl->setInvalidDecl();
2071 } else { // add it to the list.
2072 IDecl->setImplementation(IMPDecl);
2073 PushOnScopeChains(IMPDecl, TUScope);
2074 // Warn on implementating deprecated class under
2075 // -Wdeprecated-implementations flag.
2076 DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
2077 }
2078
2079 // If the superclass has the objc_runtime_visible attribute, we
2080 // cannot implement a subclass of it.
2081 if (IDecl->getSuperClass() &&
2082 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2083 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2084 << IDecl->getDeclName()
2085 << IDecl->getSuperClass()->getDeclName();
2086 }
2087
2088 return ActOnObjCContainerStartDefinition(IMPDecl);
2089}
2090
2091Sema::DeclGroupPtrTy
2092Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2093 SmallVector<Decl *, 64> DeclsInGroup;
2094 DeclsInGroup.reserve(Decls.size() + 1);
2095
2096 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2097 Decl *Dcl = Decls[i];
2098 if (!Dcl)
2099 continue;
2100 if (Dcl->getDeclContext()->isFileContext())
2101 Dcl->setTopLevelDeclInObjCContainer();
2102 DeclsInGroup.push_back(Dcl);
2103 }
2104
2105 DeclsInGroup.push_back(ObjCImpDecl);
2106
2107 return BuildDeclaratorGroup(DeclsInGroup);
2108}
2109
2110void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2111 ObjCIvarDecl **ivars, unsigned numIvars,
2112 SourceLocation RBrace) {
2113 assert(ImpDecl && "missing implementation decl")((ImpDecl && "missing implementation decl") ? static_cast
<void> (0) : __assert_fail ("ImpDecl && \"missing implementation decl\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 2113, __PRETTY_FUNCTION__))
;
2114 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
2115 if (!IDecl)
2116 return;
2117 /// Check case of non-existing \@interface decl.
2118 /// (legacy objective-c \@implementation decl without an \@interface decl).
2119 /// Add implementations's ivar to the synthesize class's ivar list.
2120 if (IDecl->isImplicitInterfaceDecl()) {
2121 IDecl->setEndOfDefinitionLoc(RBrace);
2122 // Add ivar's to class's DeclContext.
2123 for (unsigned i = 0, e = numIvars; i != e; ++i) {
2124 ivars[i]->setLexicalDeclContext(ImpDecl);
2125 IDecl->makeDeclVisibleInContext(ivars[i]);
2126 ImpDecl->addDecl(ivars[i]);
2127 }
2128
2129 return;
2130 }
2131 // If implementation has empty ivar list, just return.
2132 if (numIvars == 0)
2133 return;
2134
2135 assert(ivars && "missing @implementation ivars")((ivars && "missing @implementation ivars") ? static_cast
<void> (0) : __assert_fail ("ivars && \"missing @implementation ivars\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 2135, __PRETTY_FUNCTION__))
;
2136 if (LangOpts.ObjCRuntime.isNonFragile()) {
2137 if (ImpDecl->getSuperClass())
2138 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2139 for (unsigned i = 0; i < numIvars; i++) {
2140 ObjCIvarDecl* ImplIvar = ivars[i];
2141 if (const ObjCIvarDecl *ClsIvar =
2142 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2143 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2144 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2145 continue;
2146 }
2147 // Check class extensions (unnamed categories) for duplicate ivars.
2148 for (const auto *CDecl : IDecl->visible_extensions()) {
2149 if (const ObjCIvarDecl *ClsExtIvar =
2150 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2151 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2152 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2153 continue;
2154 }
2155 }
2156 // Instance ivar to Implementation's DeclContext.
2157 ImplIvar->setLexicalDeclContext(ImpDecl);
2158 IDecl->makeDeclVisibleInContext(ImplIvar);
2159 ImpDecl->addDecl(ImplIvar);
2160 }
2161 return;
2162 }
2163 // Check interface's Ivar list against those in the implementation.
2164 // names and types must match.
2165 //
2166 unsigned j = 0;
2167 ObjCInterfaceDecl::ivar_iterator
2168 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2169 for (; numIvars > 0 && IVI != IVE; ++IVI) {
2170 ObjCIvarDecl* ImplIvar = ivars[j++];
2171 ObjCIvarDecl* ClsIvar = *IVI;
2172 assert (ImplIvar && "missing implementation ivar")((ImplIvar && "missing implementation ivar") ? static_cast
<void> (0) : __assert_fail ("ImplIvar && \"missing implementation ivar\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 2172, __PRETTY_FUNCTION__))
;
2173 assert (ClsIvar && "missing class ivar")((ClsIvar && "missing class ivar") ? static_cast<void
> (0) : __assert_fail ("ClsIvar && \"missing class ivar\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 2173, __PRETTY_FUNCTION__))
;
2174
2175 // First, make sure the types match.
2176 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
2177 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
2178 << ImplIvar->getIdentifier()
2179 << ImplIvar->getType() << ClsIvar->getType();
2180 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2181 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2182 ImplIvar->getBitWidthValue(Context) !=
2183 ClsIvar->getBitWidthValue(Context)) {
2184 Diag(ImplIvar->getBitWidth()->getBeginLoc(),
2185 diag::err_conflicting_ivar_bitwidth)
2186 << ImplIvar->getIdentifier();
2187 Diag(ClsIvar->getBitWidth()->getBeginLoc(),
2188 diag::note_previous_definition);
2189 }
2190 // Make sure the names are identical.
2191 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
2192 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
2193 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
2194 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2195 }
2196 --numIvars;
2197 }
2198
2199 if (numIvars > 0)
2200 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
2201 else if (IVI != IVE)
2202 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
2203}
2204
2205static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2206 ObjCMethodDecl *method,
2207 bool &IncompleteImpl,
2208 unsigned DiagID,
2209 NamedDecl *NeededFor = nullptr) {
2210 // No point warning no definition of method which is 'unavailable'.
2211 if (method->getAvailability() == AR_Unavailable)
2212 return;
2213
2214 // FIXME: For now ignore 'IncompleteImpl'.
2215 // Previously we grouped all unimplemented methods under a single
2216 // warning, but some users strongly voiced that they would prefer
2217 // separate warnings. We will give that approach a try, as that
2218 // matches what we do with protocols.
2219 {
2220 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2221 B << method;
2222 if (NeededFor)
2223 B << NeededFor;
2224 }
2225
2226 // Issue a note to the original declaration.
2227 SourceLocation MethodLoc = method->getBeginLoc();
2228 if (MethodLoc.isValid())
2229 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
2230}
2231
2232/// Determines if type B can be substituted for type A. Returns true if we can
2233/// guarantee that anything that the user will do to an object of type A can
2234/// also be done to an object of type B. This is trivially true if the two
2235/// types are the same, or if B is a subclass of A. It becomes more complex
2236/// in cases where protocols are involved.
2237///
2238/// Object types in Objective-C describe the minimum requirements for an
2239/// object, rather than providing a complete description of a type. For
2240/// example, if A is a subclass of B, then B* may refer to an instance of A.
2241/// The principle of substitutability means that we may use an instance of A
2242/// anywhere that we may use an instance of B - it will implement all of the
2243/// ivars of B and all of the methods of B.
2244///
2245/// This substitutability is important when type checking methods, because
2246/// the implementation may have stricter type definitions than the interface.
2247/// The interface specifies minimum requirements, but the implementation may
2248/// have more accurate ones. For example, a method may privately accept
2249/// instances of B, but only publish that it accepts instances of A. Any
2250/// object passed to it will be type checked against B, and so will implicitly
2251/// by a valid A*. Similarly, a method may return a subclass of the class that
2252/// it is declared as returning.
2253///
2254/// This is most important when considering subclassing. A method in a
2255/// subclass must accept any object as an argument that its superclass's
2256/// implementation accepts. It may, however, accept a more general type
2257/// without breaking substitutability (i.e. you can still use the subclass
2258/// anywhere that you can use the superclass, but not vice versa). The
2259/// converse requirement applies to return types: the return type for a
2260/// subclass method must be a valid object of the kind that the superclass
2261/// advertises, but it may be specified more accurately. This avoids the need
2262/// for explicit down-casting by callers.
2263///
2264/// Note: This is a stricter requirement than for assignment.
2265static bool isObjCTypeSubstitutable(ASTContext &Context,
2266 const ObjCObjectPointerType *A,
2267 const ObjCObjectPointerType *B,
2268 bool rejectId) {
2269 // Reject a protocol-unqualified id.
2270 if (rejectId && B->isObjCIdType()) return false;
2271
2272 // If B is a qualified id, then A must also be a qualified id and it must
2273 // implement all of the protocols in B. It may not be a qualified class.
2274 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2275 // stricter definition so it is not substitutable for id<A>.
2276 if (B->isObjCQualifiedIdType()) {
2277 return A->isObjCQualifiedIdType() &&
2278 Context.ObjCQualifiedIdTypesAreCompatible(A, B, false);
2279 }
2280
2281 /*
2282 // id is a special type that bypasses type checking completely. We want a
2283 // warning when it is used in one place but not another.
2284 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2285
2286
2287 // If B is a qualified id, then A must also be a qualified id (which it isn't
2288 // if we've got this far)
2289 if (B->isObjCQualifiedIdType()) return false;
2290 */
2291
2292 // Now we know that A and B are (potentially-qualified) class types. The
2293 // normal rules for assignment apply.
2294 return Context.canAssignObjCInterfaces(A, B);
2295}
2296
2297static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2298 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2299}
2300
2301/// Determine whether two set of Objective-C declaration qualifiers conflict.
2302static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2303 Decl::ObjCDeclQualifier y) {
2304 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2305 (y & ~Decl::OBJC_TQ_CSNullability);
2306}
2307
2308static bool CheckMethodOverrideReturn(Sema &S,
2309 ObjCMethodDecl *MethodImpl,
2310 ObjCMethodDecl *MethodDecl,
2311 bool IsProtocolMethodDecl,
2312 bool IsOverridingMode,
2313 bool Warn) {
2314 if (IsProtocolMethodDecl &&
2315 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2316 MethodImpl->getObjCDeclQualifier())) {
2317 if (Warn) {
2318 S.Diag(MethodImpl->getLocation(),
2319 (IsOverridingMode
2320 ? diag::warn_conflicting_overriding_ret_type_modifiers
2321 : diag::warn_conflicting_ret_type_modifiers))
2322 << MethodImpl->getDeclName()
2323 << MethodImpl->getReturnTypeSourceRange();
2324 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
2325 << MethodDecl->getReturnTypeSourceRange();
2326 }
2327 else
2328 return false;
2329 }
2330 if (Warn && IsOverridingMode &&
2331 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2332 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2333 MethodDecl->getReturnType(),
2334 false)) {
2335 auto nullabilityMethodImpl =
2336 *MethodImpl->getReturnType()->getNullability(S.Context);
2337 auto nullabilityMethodDecl =
2338 *MethodDecl->getReturnType()->getNullability(S.Context);
2339 S.Diag(MethodImpl->getLocation(),
2340 diag::warn_conflicting_nullability_attr_overriding_ret_types)
2341 << DiagNullabilityKind(
2342 nullabilityMethodImpl,
2343 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2344 != 0))
2345 << DiagNullabilityKind(
2346 nullabilityMethodDecl,
2347 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2348 != 0));
2349 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2350 }
2351
2352 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2353 MethodDecl->getReturnType()))
2354 return true;
2355 if (!Warn)
2356 return false;
2357
2358 unsigned DiagID =
2359 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2360 : diag::warn_conflicting_ret_types;
2361
2362 // Mismatches between ObjC pointers go into a different warning
2363 // category, and sometimes they're even completely whitelisted.
2364 if (const ObjCObjectPointerType *ImplPtrTy =
2365 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2366 if (const ObjCObjectPointerType *IfacePtrTy =
2367 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2368 // Allow non-matching return types as long as they don't violate
2369 // the principle of substitutability. Specifically, we permit
2370 // return types that are subclasses of the declared return type,
2371 // or that are more-qualified versions of the declared type.
2372 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
2373 return false;
2374
2375 DiagID =
2376 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
2377 : diag::warn_non_covariant_ret_types;
2378 }
2379 }
2380
2381 S.Diag(MethodImpl->getLocation(), DiagID)
2382 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2383 << MethodImpl->getReturnType()
2384 << MethodImpl->getReturnTypeSourceRange();
2385 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2386 ? diag::note_previous_declaration
2387 : diag::note_previous_definition)
2388 << MethodDecl->getReturnTypeSourceRange();
2389 return false;
2390}
2391
2392static bool CheckMethodOverrideParam(Sema &S,
2393 ObjCMethodDecl *MethodImpl,
2394 ObjCMethodDecl *MethodDecl,
2395 ParmVarDecl *ImplVar,
2396 ParmVarDecl *IfaceVar,
2397 bool IsProtocolMethodDecl,
2398 bool IsOverridingMode,
2399 bool Warn) {
2400 if (IsProtocolMethodDecl &&
2401 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2402 IfaceVar->getObjCDeclQualifier())) {
2403 if (Warn) {
2404 if (IsOverridingMode)
2405 S.Diag(ImplVar->getLocation(),
2406 diag::warn_conflicting_overriding_param_modifiers)
2407 << getTypeRange(ImplVar->getTypeSourceInfo())
2408 << MethodImpl->getDeclName();
2409 else S.Diag(ImplVar->getLocation(),
2410 diag::warn_conflicting_param_modifiers)
2411 << getTypeRange(ImplVar->getTypeSourceInfo())
2412 << MethodImpl->getDeclName();
2413 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2414 << getTypeRange(IfaceVar->getTypeSourceInfo());
2415 }
2416 else
2417 return false;
2418 }
2419
2420 QualType ImplTy = ImplVar->getType();
2421 QualType IfaceTy = IfaceVar->getType();
2422 if (Warn && IsOverridingMode &&
2423 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2424 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
2425 S.Diag(ImplVar->getLocation(),
2426 diag::warn_conflicting_nullability_attr_overriding_param_types)
2427 << DiagNullabilityKind(
2428 *ImplTy->getNullability(S.Context),
2429 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2430 != 0))
2431 << DiagNullabilityKind(
2432 *IfaceTy->getNullability(S.Context),
2433 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2434 != 0));
2435 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
2436 }
2437 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
2438 return true;
2439
2440 if (!Warn)
2441 return false;
2442 unsigned DiagID =
2443 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2444 : diag::warn_conflicting_param_types;
2445
2446 // Mismatches between ObjC pointers go into a different warning
2447 // category, and sometimes they're even completely whitelisted.
2448 if (const ObjCObjectPointerType *ImplPtrTy =
2449 ImplTy->getAs<ObjCObjectPointerType>()) {
2450 if (const ObjCObjectPointerType *IfacePtrTy =
2451 IfaceTy->getAs<ObjCObjectPointerType>()) {
2452 // Allow non-matching argument types as long as they don't
2453 // violate the principle of substitutability. Specifically, the
2454 // implementation must accept any objects that the superclass
2455 // accepts, however it may also accept others.
2456 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
2457 return false;
2458
2459 DiagID =
2460 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
2461 : diag::warn_non_contravariant_param_types;
2462 }
2463 }
2464
2465 S.Diag(ImplVar->getLocation(), DiagID)
2466 << getTypeRange(ImplVar->getTypeSourceInfo())
2467 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2468 S.Diag(IfaceVar->getLocation(),
2469 (IsOverridingMode ? diag::note_previous_declaration
2470 : diag::note_previous_definition))
2471 << getTypeRange(IfaceVar->getTypeSourceInfo());
2472 return false;
2473}
2474
2475/// In ARC, check whether the conventional meanings of the two methods
2476/// match. If they don't, it's a hard error.
2477static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2478 ObjCMethodDecl *decl) {
2479 ObjCMethodFamily implFamily = impl->getMethodFamily();
2480 ObjCMethodFamily declFamily = decl->getMethodFamily();
2481 if (implFamily == declFamily) return false;
2482
2483 // Since conventions are sorted by selector, the only possibility is
2484 // that the types differ enough to cause one selector or the other
2485 // to fall out of the family.
2486 assert(implFamily == OMF_None || declFamily == OMF_None)((implFamily == OMF_None || declFamily == OMF_None) ? static_cast
<void> (0) : __assert_fail ("implFamily == OMF_None || declFamily == OMF_None"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 2486, __PRETTY_FUNCTION__))
;
2487
2488 // No further diagnostics required on invalid declarations.
2489 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2490
2491 const ObjCMethodDecl *unmatched = impl;
2492 ObjCMethodFamily family = declFamily;
2493 unsigned errorID = diag::err_arc_lost_method_convention;
2494 unsigned noteID = diag::note_arc_lost_method_convention;
2495 if (declFamily == OMF_None) {
2496 unmatched = decl;
2497 family = implFamily;
2498 errorID = diag::err_arc_gained_method_convention;
2499 noteID = diag::note_arc_gained_method_convention;
2500 }
2501
2502 // Indexes into a %select clause in the diagnostic.
2503 enum FamilySelector {
2504 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2505 };
2506 FamilySelector familySelector = FamilySelector();
2507
2508 switch (family) {
2509 case OMF_None: llvm_unreachable("logic error, no method convention")::llvm::llvm_unreachable_internal("logic error, no method convention"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 2509)
;
2510 case OMF_retain:
2511 case OMF_release:
2512 case OMF_autorelease:
2513 case OMF_dealloc:
2514 case OMF_finalize:
2515 case OMF_retainCount:
2516 case OMF_self:
2517 case OMF_initialize:
2518 case OMF_performSelector:
2519 // Mismatches for these methods don't change ownership
2520 // conventions, so we don't care.
2521 return false;
2522
2523 case OMF_init: familySelector = F_init; break;
2524 case OMF_alloc: familySelector = F_alloc; break;
2525 case OMF_copy: familySelector = F_copy; break;
2526 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2527 case OMF_new: familySelector = F_new; break;
2528 }
2529
2530 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2531 ReasonSelector reasonSelector;
2532
2533 // The only reason these methods don't fall within their families is
2534 // due to unusual result types.
2535 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
2536 reasonSelector = R_UnrelatedReturn;
2537 } else {
2538 reasonSelector = R_NonObjectReturn;
2539 }
2540
2541 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2542 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
2543
2544 return true;
2545}
2546
2547void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2548 ObjCMethodDecl *MethodDecl,
2549 bool IsProtocolMethodDecl) {
2550 if (getLangOpts().ObjCAutoRefCount &&
2551 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2552 return;
2553
2554 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2555 IsProtocolMethodDecl, false,
2556 true);
2557
2558 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2559 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2560 EF = MethodDecl->param_end();
2561 IM != EM && IF != EF; ++IM, ++IF) {
2562 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
2563 IsProtocolMethodDecl, false, true);
2564 }
2565
2566 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
2567 Diag(ImpMethodDecl->getLocation(),
2568 diag::warn_conflicting_variadic);
2569 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2570 }
2571}
2572
2573void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2574 ObjCMethodDecl *Overridden,
2575 bool IsProtocolMethodDecl) {
2576
2577 CheckMethodOverrideReturn(*this, Method, Overridden,
2578 IsProtocolMethodDecl, true,
2579 true);
2580
2581 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
2582 IF = Overridden->param_begin(), EM = Method->param_end(),
2583 EF = Overridden->param_end();
2584 IM != EM && IF != EF; ++IM, ++IF) {
2585 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2586 IsProtocolMethodDecl, true, true);
2587 }
2588
2589 if (Method->isVariadic() != Overridden->isVariadic()) {
2590 Diag(Method->getLocation(),
2591 diag::warn_conflicting_overriding_variadic);
2592 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2593 }
2594}
2595
2596/// WarnExactTypedMethods - This routine issues a warning if method
2597/// implementation declaration matches exactly that of its declaration.
2598void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2599 ObjCMethodDecl *MethodDecl,
2600 bool IsProtocolMethodDecl) {
2601 // don't issue warning when protocol method is optional because primary
2602 // class is not required to implement it and it is safe for protocol
2603 // to implement it.
2604 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2605 return;
2606 // don't issue warning when primary class's method is
2607 // depecated/unavailable.
2608 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2609 MethodDecl->hasAttr<DeprecatedAttr>())
2610 return;
2611
2612 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2613 IsProtocolMethodDecl, false, false);
2614 if (match)
2615 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2616 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2617 EF = MethodDecl->param_end();
2618 IM != EM && IF != EF; ++IM, ++IF) {
2619 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2620 *IM, *IF,
2621 IsProtocolMethodDecl, false, false);
2622 if (!match)
2623 break;
2624 }
2625 if (match)
2626 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
2627 if (match)
2628 match = !(MethodDecl->isClassMethod() &&
2629 MethodDecl->getSelector() == GetNullarySelector("load", Context));
2630
2631 if (match) {
2632 Diag(ImpMethodDecl->getLocation(),
2633 diag::warn_category_method_impl_match);
2634 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2635 << MethodDecl->getDeclName();
2636 }
2637}
2638
2639/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2640/// improve the efficiency of selector lookups and type checking by associating
2641/// with each protocol / interface / category the flattened instance tables. If
2642/// we used an immutable set to keep the table then it wouldn't add significant
2643/// memory cost and it would be handy for lookups.
2644
2645typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
2646typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
2647
2648static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2649 ProtocolNameSet &PNS) {
2650 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2651 PNS.insert(PDecl->getIdentifier());
2652 for (const auto *PI : PDecl->protocols())
2653 findProtocolsWithExplicitImpls(PI, PNS);
2654}
2655
2656/// Recursively populates a set with all conformed protocols in a class
2657/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2658/// attribute.
2659static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2660 ProtocolNameSet &PNS) {
2661 if (!Super)
2662 return;
2663
2664 for (const auto *I : Super->all_referenced_protocols())
2665 findProtocolsWithExplicitImpls(I, PNS);
2666
2667 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
2668}
2669
2670/// CheckProtocolMethodDefs - This routine checks unimplemented methods
2671/// Declared in protocol, and those referenced by it.
2672static void CheckProtocolMethodDefs(Sema &S,
2673 SourceLocation ImpLoc,
2674 ObjCProtocolDecl *PDecl,
2675 bool& IncompleteImpl,
2676 const Sema::SelectorSet &InsMap,
2677 const Sema::SelectorSet &ClsMap,
2678 ObjCContainerDecl *CDecl,
2679 LazyProtocolNameSet &ProtocolsExplictImpl) {
2680 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2681 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2682 : dyn_cast<ObjCInterfaceDecl>(CDecl);
2683 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null")((IDecl && "CheckProtocolMethodDefs - IDecl is null")
? static_cast<void> (0) : __assert_fail ("IDecl && \"CheckProtocolMethodDefs - IDecl is null\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 2683, __PRETTY_FUNCTION__))
;
2684
2685 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
2686 ObjCInterfaceDecl *NSIDecl = nullptr;
2687
2688 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2689 // then we should check if any class in the super class hierarchy also
2690 // conforms to this protocol, either directly or via protocol inheritance.
2691 // If so, we can skip checking this protocol completely because we
2692 // know that a parent class already satisfies this protocol.
2693 //
2694 // Note: we could generalize this logic for all protocols, and merely
2695 // add the limit on looking at the super class chain for just
2696 // specially marked protocols. This may be a good optimization. This
2697 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2698 // protocols for now for controlled evaluation.
2699 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
2700 if (!ProtocolsExplictImpl) {
2701 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2702 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2703 }
2704 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2705 ProtocolsExplictImpl->end())
2706 return;
2707
2708 // If no super class conforms to the protocol, we should not search
2709 // for methods in the super class to implicitly satisfy the protocol.
2710 Super = nullptr;
2711 }
2712
2713 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
2714 // check to see if class implements forwardInvocation method and objects
2715 // of this class are derived from 'NSProxy' so that to forward requests
2716 // from one object to another.
2717 // Under such conditions, which means that every method possible is
2718 // implemented in the class, we should not issue "Method definition not
2719 // found" warnings.
2720 // FIXME: Use a general GetUnarySelector method for this.
2721 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2722 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
2723 if (InsMap.count(fISelector))
2724 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2725 // need be implemented in the implementation.
2726 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
2727 }
2728
2729 // If this is a forward protocol declaration, get its definition.
2730 if (!PDecl->isThisDeclarationADefinition() &&
2731 PDecl->getDefinition())
2732 PDecl = PDecl->getDefinition();
2733
2734 // If a method lookup fails locally we still need to look and see if
2735 // the method was implemented by a base class or an inherited
2736 // protocol. This lookup is slow, but occurs rarely in correct code
2737 // and otherwise would terminate in a warning.
2738
2739 // check unimplemented instance methods.
2740 if (!NSIDecl)
2741 for (auto *method : PDecl->instance_methods()) {
2742 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2743 !method->isPropertyAccessor() &&
2744 !InsMap.count(method->getSelector()) &&
2745 (!Super || !Super->lookupMethod(method->getSelector(),
2746 true /* instance */,
2747 false /* shallowCategory */,
2748 true /* followsSuper */,
2749 nullptr /* category */))) {
2750 // If a method is not implemented in the category implementation but
2751 // has been declared in its primary class, superclass,
2752 // or in one of their protocols, no need to issue the warning.
2753 // This is because method will be implemented in the primary class
2754 // or one of its super class implementation.
2755
2756 // Ugly, but necessary. Method declared in protocol might have
2757 // have been synthesized due to a property declared in the class which
2758 // uses the protocol.
2759 if (ObjCMethodDecl *MethodInClass =
2760 IDecl->lookupMethod(method->getSelector(),
2761 true /* instance */,
2762 true /* shallowCategoryLookup */,
2763 false /* followSuper */))
2764 if (C || MethodInClass->isPropertyAccessor())
2765 continue;
2766 unsigned DIAG = diag::warn_unimplemented_protocol_method;
2767 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
2768 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
2769 PDecl);
2770 }
2771 }
2772 }
2773 // check unimplemented class methods
2774 for (auto *method : PDecl->class_methods()) {
2775 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2776 !ClsMap.count(method->getSelector()) &&
2777 (!Super || !Super->lookupMethod(method->getSelector(),
2778 false /* class method */,
2779 false /* shallowCategoryLookup */,
2780 true /* followSuper */,
2781 nullptr /* category */))) {
2782 // See above comment for instance method lookups.
2783 if (C && IDecl->lookupMethod(method->getSelector(),
2784 false /* class */,
2785 true /* shallowCategoryLookup */,
2786 false /* followSuper */))
2787 continue;
2788
2789 unsigned DIAG = diag::warn_unimplemented_protocol_method;
2790 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
2791 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
2792 }
2793 }
2794 }
2795 // Check on this protocols's referenced protocols, recursively.
2796 for (auto *PI : PDecl->protocols())
2797 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
2798 CDecl, ProtocolsExplictImpl);
2799}
2800
2801/// MatchAllMethodDeclarations - Check methods declared in interface
2802/// or protocol against those declared in their implementations.
2803///
2804void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2805 const SelectorSet &ClsMap,
2806 SelectorSet &InsMapSeen,
2807 SelectorSet &ClsMapSeen,
2808 ObjCImplDecl* IMPDecl,
2809 ObjCContainerDecl* CDecl,
2810 bool &IncompleteImpl,
2811 bool ImmediateClass,
2812 bool WarnCategoryMethodImpl) {
2813 // Check and see if instance methods in class interface have been
2814 // implemented in the implementation class. If so, their types match.
2815 for (auto *I : CDecl->instance_methods()) {
2816 if (!InsMapSeen.insert(I->getSelector()).second)
2817 continue;
2818 if (!I->isPropertyAccessor() &&
2819 !InsMap.count(I->getSelector())) {
2820 if (ImmediateClass)
2821 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
2822 diag::warn_undef_method_impl);
2823 continue;
2824 } else {
2825 ObjCMethodDecl *ImpMethodDecl =
2826 IMPDecl->getInstanceMethod(I->getSelector());
2827 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&((CDecl->getInstanceMethod(I->getSelector(), true ) &&
"Expected to find the method through lookup as well") ? static_cast
<void> (0) : __assert_fail ("CDecl->getInstanceMethod(I->getSelector(), true ) && \"Expected to find the method through lookup as well\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 2828, __PRETTY_FUNCTION__))
2828 "Expected to find the method through lookup as well")((CDecl->getInstanceMethod(I->getSelector(), true ) &&
"Expected to find the method through lookup as well") ? static_cast
<void> (0) : __assert_fail ("CDecl->getInstanceMethod(I->getSelector(), true ) && \"Expected to find the method through lookup as well\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 2828, __PRETTY_FUNCTION__))
;
2829 // ImpMethodDecl may be null as in a @dynamic property.
2830 if (ImpMethodDecl) {
2831 if (!WarnCategoryMethodImpl)
2832 WarnConflictingTypedMethods(ImpMethodDecl, I,
2833 isa<ObjCProtocolDecl>(CDecl));
2834 else if (!I->isPropertyAccessor())
2835 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2836 }
2837 }
2838 }
2839
2840 // Check and see if class methods in class interface have been
2841 // implemented in the implementation class. If so, their types match.
2842 for (auto *I : CDecl->class_methods()) {
2843 if (!ClsMapSeen.insert(I->getSelector()).second)
2844 continue;
2845 if (!I->isPropertyAccessor() &&
2846 !ClsMap.count(I->getSelector())) {
2847 if (ImmediateClass)
2848 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
2849 diag::warn_undef_method_impl);
2850 } else {
2851 ObjCMethodDecl *ImpMethodDecl =
2852 IMPDecl->getClassMethod(I->getSelector());
2853 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&((CDecl->getClassMethod(I->getSelector(), true ) &&
"Expected to find the method through lookup as well") ? static_cast
<void> (0) : __assert_fail ("CDecl->getClassMethod(I->getSelector(), true ) && \"Expected to find the method through lookup as well\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 2854, __PRETTY_FUNCTION__))
2854 "Expected to find the method through lookup as well")((CDecl->getClassMethod(I->getSelector(), true ) &&
"Expected to find the method through lookup as well") ? static_cast
<void> (0) : __assert_fail ("CDecl->getClassMethod(I->getSelector(), true ) && \"Expected to find the method through lookup as well\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 2854, __PRETTY_FUNCTION__))
;
2855 // ImpMethodDecl may be null as in a @dynamic property.
2856 if (ImpMethodDecl) {
2857 if (!WarnCategoryMethodImpl)
2858 WarnConflictingTypedMethods(ImpMethodDecl, I,
2859 isa<ObjCProtocolDecl>(CDecl));
2860 else if (!I->isPropertyAccessor())
2861 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2862 }
2863 }
2864 }
2865
2866 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2867 // Also, check for methods declared in protocols inherited by
2868 // this protocol.
2869 for (auto *PI : PD->protocols())
2870 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2871 IMPDecl, PI, IncompleteImpl, false,
2872 WarnCategoryMethodImpl);
2873 }
2874
2875 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2876 // when checking that methods in implementation match their declaration,
2877 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2878 // extension; as well as those in categories.
2879 if (!WarnCategoryMethodImpl) {
2880 for (auto *Cat : I->visible_categories())
2881 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2882 IMPDecl, Cat, IncompleteImpl,
2883 ImmediateClass && Cat->IsClassExtension(),
2884 WarnCategoryMethodImpl);
2885 } else {
2886 // Also methods in class extensions need be looked at next.
2887 for (auto *Ext : I->visible_extensions())
2888 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2889 IMPDecl, Ext, IncompleteImpl, false,
2890 WarnCategoryMethodImpl);
2891 }
2892
2893 // Check for any implementation of a methods declared in protocol.
2894 for (auto *PI : I->all_referenced_protocols())
2895 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2896 IMPDecl, PI, IncompleteImpl, false,
2897 WarnCategoryMethodImpl);
2898
2899 // FIXME. For now, we are not checking for exact match of methods
2900 // in category implementation and its primary class's super class.
2901 if (!WarnCategoryMethodImpl && I->getSuperClass())
2902 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2903 IMPDecl,
2904 I->getSuperClass(), IncompleteImpl, false);
2905 }
2906}
2907
2908/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2909/// category matches with those implemented in its primary class and
2910/// warns each time an exact match is found.
2911void Sema::CheckCategoryVsClassMethodMatches(
2912 ObjCCategoryImplDecl *CatIMPDecl) {
2913 // Get category's primary class.
2914 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2915 if (!CatDecl)
2916 return;
2917 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2918 if (!IDecl)
2919 return;
2920 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2921 SelectorSet InsMap, ClsMap;
2922
2923 for (const auto *I : CatIMPDecl->instance_methods()) {
2924 Selector Sel = I->getSelector();
2925 // When checking for methods implemented in the category, skip over
2926 // those declared in category class's super class. This is because
2927 // the super class must implement the method.
2928 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2929 continue;
2930 InsMap.insert(Sel);
2931 }
2932
2933 for (const auto *I : CatIMPDecl->class_methods()) {
2934 Selector Sel = I->getSelector();
2935 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2936 continue;
2937 ClsMap.insert(Sel);
2938 }
2939 if (InsMap.empty() && ClsMap.empty())
2940 return;
2941
2942 SelectorSet InsMapSeen, ClsMapSeen;
2943 bool IncompleteImpl = false;
2944 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2945 CatIMPDecl, IDecl,
2946 IncompleteImpl, false,
2947 true /*WarnCategoryMethodImpl*/);
2948}
2949
2950void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2951 ObjCContainerDecl* CDecl,
2952 bool IncompleteImpl) {
2953 SelectorSet InsMap;
2954 // Check and see if instance methods in class interface have been
2955 // implemented in the implementation class.
2956 for (const auto *I : IMPDecl->instance_methods())
2957 InsMap.insert(I->getSelector());
2958
2959 // Add the selectors for getters/setters of @dynamic properties.
2960 for (const auto *PImpl : IMPDecl->property_impls()) {
2961 // We only care about @dynamic implementations.
2962 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2963 continue;
2964
2965 const auto *P = PImpl->getPropertyDecl();
2966 if (!P) continue;
2967
2968 InsMap.insert(P->getGetterName());
2969 if (!P->getSetterName().isNull())
2970 InsMap.insert(P->getSetterName());
2971 }
2972
2973 // Check and see if properties declared in the interface have either 1)
2974 // an implementation or 2) there is a @synthesize/@dynamic implementation
2975 // of the property in the @implementation.
2976 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2977 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2978 LangOpts.ObjCRuntime.isNonFragile() &&
2979 !IDecl->isObjCRequiresPropertyDefs();
2980 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2981 }
2982
2983 // Diagnose null-resettable synthesized setters.
2984 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2985
2986 SelectorSet ClsMap;
2987 for (const auto *I : IMPDecl->class_methods())
2988 ClsMap.insert(I->getSelector());
2989
2990 // Check for type conflict of methods declared in a class/protocol and
2991 // its implementation; if any.
2992 SelectorSet InsMapSeen, ClsMapSeen;
2993 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2994 IMPDecl, CDecl,
2995 IncompleteImpl, true);
2996
2997 // check all methods implemented in category against those declared
2998 // in its primary class.
2999 if (ObjCCategoryImplDecl *CatDecl =
3000 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
3001 CheckCategoryVsClassMethodMatches(CatDecl);
3002
3003 // Check the protocol list for unimplemented methods in the @implementation
3004 // class.
3005 // Check and see if class methods in class interface have been
3006 // implemented in the implementation class.
3007
3008 LazyProtocolNameSet ExplicitImplProtocols;
3009
3010 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
3011 for (auto *PI : I->all_referenced_protocols())
3012 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
3013 InsMap, ClsMap, I, ExplicitImplProtocols);
3014 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
3015 // For extended class, unimplemented methods in its protocols will
3016 // be reported in the primary class.
3017 if (!C->IsClassExtension()) {
3018 for (auto *P : C->protocols())
3019 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
3020 IncompleteImpl, InsMap, ClsMap, CDecl,
3021 ExplicitImplProtocols);
3022 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
3023 /*SynthesizeProperties=*/false);
3024 }
3025 } else
3026 llvm_unreachable("invalid ObjCContainerDecl type.")::llvm::llvm_unreachable_internal("invalid ObjCContainerDecl type."
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 3026)
;
3027}
3028
3029Sema::DeclGroupPtrTy
3030Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
3031 IdentifierInfo **IdentList,
3032 SourceLocation *IdentLocs,
3033 ArrayRef<ObjCTypeParamList *> TypeParamLists,
3034 unsigned NumElts) {
3035 SmallVector<Decl *, 8> DeclsInGroup;
3036 for (unsigned i = 0; i != NumElts; ++i) {
3037 // Check for another declaration kind with the same name.
3038 NamedDecl *PrevDecl
3039 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
3040 LookupOrdinaryName, forRedeclarationInCurContext());
3041 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
3042 // GCC apparently allows the following idiom:
3043 //
3044 // typedef NSObject < XCElementTogglerP > XCElementToggler;
3045 // @class XCElementToggler;
3046 //
3047 // Here we have chosen to ignore the forward class declaration
3048 // with a warning. Since this is the implied behavior.
3049 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
3050 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
3051 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
3052 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3053 } else {
3054 // a forward class declaration matching a typedef name of a class refers
3055 // to the underlying class. Just ignore the forward class with a warning
3056 // as this will force the intended behavior which is to lookup the
3057 // typedef name.
3058 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
3059 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3060 << IdentList[i];
3061 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3062 continue;
3063 }
3064 }
3065 }
3066
3067 // Create a declaration to describe this forward declaration.
3068 ObjCInterfaceDecl *PrevIDecl
3069 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
3070
3071 IdentifierInfo *ClassName = IdentList[i];
3072 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3073 // A previous decl with a different name is because of
3074 // @compatibility_alias, for example:
3075 // \code
3076 // @class NewImage;
3077 // @compatibility_alias OldImage NewImage;
3078 // \endcode
3079 // A lookup for 'OldImage' will return the 'NewImage' decl.
3080 //
3081 // In such a case use the real declaration name, instead of the alias one,
3082 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3083 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3084 // has been aliased.
3085 ClassName = PrevIDecl->getIdentifier();
3086 }
3087
3088 // If this forward declaration has type parameters, compare them with the
3089 // type parameters of the previous declaration.
3090 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3091 if (PrevIDecl && TypeParams) {
3092 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3093 // Check for consistency with the previous declaration.
3094 if (checkTypeParamListConsistency(
3095 *this, PrevTypeParams, TypeParams,
3096 TypeParamListContext::ForwardDeclaration)) {
3097 TypeParams = nullptr;
3098 }
3099 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3100 // The @interface does not have type parameters. Complain.
3101 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3102 << ClassName
3103 << TypeParams->getSourceRange();
3104 Diag(Def->getLocation(), diag::note_defined_here)
3105 << ClassName;
3106
3107 TypeParams = nullptr;
3108 }
3109 }
3110
3111 ObjCInterfaceDecl *IDecl
3112 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
3113 ClassName, TypeParams, PrevIDecl,
3114 IdentLocs[i]);
3115 IDecl->setAtEndRange(IdentLocs[i]);
3116
3117 PushOnScopeChains(IDecl, TUScope);
3118 CheckObjCDeclScope(IDecl);
3119 DeclsInGroup.push_back(IDecl);
3120 }
3121
3122 return BuildDeclaratorGroup(DeclsInGroup);
3123}
3124
3125static bool tryMatchRecordTypes(ASTContext &Context,
3126 Sema::MethodMatchStrategy strategy,
3127 const Type *left, const Type *right);
3128
3129static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3130 QualType leftQT, QualType rightQT) {
3131 const Type *left =
3132 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3133 const Type *right =
3134 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3135
3136 if (left == right) return true;
3137
3138 // If we're doing a strict match, the types have to match exactly.
3139 if (strategy == Sema::MMS_strict) return false;
3140
3141 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3142
3143 // Otherwise, use this absurdly complicated algorithm to try to
3144 // validate the basic, low-level compatibility of the two types.
3145
3146 // As a minimum, require the sizes and alignments to match.
3147 TypeInfo LeftTI = Context.getTypeInfo(left);
3148 TypeInfo RightTI = Context.getTypeInfo(right);
3149 if (LeftTI.Width != RightTI.Width)
3150 return false;
3151
3152 if (LeftTI.Align != RightTI.Align)
3153 return false;
3154
3155 // Consider all the kinds of non-dependent canonical types:
3156 // - functions and arrays aren't possible as return and parameter types
3157
3158 // - vector types of equal size can be arbitrarily mixed
3159 if (isa<VectorType>(left)) return isa<VectorType>(right);
3160 if (isa<VectorType>(right)) return false;
3161
3162 // - references should only match references of identical type
3163 // - structs, unions, and Objective-C objects must match more-or-less
3164 // exactly
3165 // - everything else should be a scalar
3166 if (!left->isScalarType() || !right->isScalarType())
3167 return tryMatchRecordTypes(Context, strategy, left, right);
3168
3169 // Make scalars agree in kind, except count bools as chars, and group
3170 // all non-member pointers together.
3171 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3172 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3173 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3174 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
3175 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3176 leftSK = Type::STK_ObjCObjectPointer;
3177 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3178 rightSK = Type::STK_ObjCObjectPointer;
3179
3180 // Note that data member pointers and function member pointers don't
3181 // intermix because of the size differences.
3182
3183 return (leftSK == rightSK);
3184}
3185
3186static bool tryMatchRecordTypes(ASTContext &Context,
3187 Sema::MethodMatchStrategy strategy,
3188 const Type *lt, const Type *rt) {
3189 assert(lt && rt && lt != rt)((lt && rt && lt != rt) ? static_cast<void
> (0) : __assert_fail ("lt && rt && lt != rt"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 3189, __PRETTY_FUNCTION__))
;
3190
3191 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3192 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3193 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3194
3195 // Require union-hood to match.
3196 if (left->isUnion() != right->isUnion()) return false;
3197
3198 // Require an exact match if either is non-POD.
3199 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3200 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3201 return false;
3202
3203 // Require size and alignment to match.
3204 TypeInfo LeftTI = Context.getTypeInfo(lt);
3205 TypeInfo RightTI = Context.getTypeInfo(rt);
3206 if (LeftTI.Width != RightTI.Width)
3207 return false;
3208
3209 if (LeftTI.Align != RightTI.Align)
3210 return false;
3211
3212 // Require fields to match.
3213 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3214 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3215 for (; li != le && ri != re; ++li, ++ri) {
3216 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3217 return false;
3218 }
3219 return (li == le && ri == re);
3220}
3221
3222/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3223/// returns true, or false, accordingly.
3224/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
3225bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3226 const ObjCMethodDecl *right,
3227 MethodMatchStrategy strategy) {
3228 if (!matchTypes(Context, strategy, left->getReturnType(),
3229 right->getReturnType()))
3230 return false;
3231
3232 // If either is hidden, it is not considered to match.
3233 if (left->isHidden() || right->isHidden())
3234 return false;
3235
3236 if (getLangOpts().ObjCAutoRefCount &&
3237 (left->hasAttr<NSReturnsRetainedAttr>()
3238 != right->hasAttr<NSReturnsRetainedAttr>() ||
3239 left->hasAttr<NSConsumesSelfAttr>()
3240 != right->hasAttr<NSConsumesSelfAttr>()))
3241 return false;
3242
3243 ObjCMethodDecl::param_const_iterator
3244 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3245 re = right->param_end();
3246
3247 for (; li != le && ri != re; ++li, ++ri) {
3248 assert(ri != right->param_end() && "Param mismatch")((ri != right->param_end() && "Param mismatch") ? static_cast
<void> (0) : __assert_fail ("ri != right->param_end() && \"Param mismatch\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 3248, __PRETTY_FUNCTION__))
;
3249 const ParmVarDecl *lparm = *li, *rparm = *ri;
3250
3251 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3252 return false;
3253
3254 if (getLangOpts().ObjCAutoRefCount &&
3255 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3256 return false;
3257 }
3258 return true;
3259}
3260
3261static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3262 ObjCMethodDecl *MethodInList) {
3263 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3264 auto *MethodInListProtocol =
3265 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3266 // If this method belongs to a protocol but the method in list does not, or
3267 // vice versa, we say the context is not the same.
3268 if ((MethodProtocol && !MethodInListProtocol) ||
3269 (!MethodProtocol && MethodInListProtocol))
3270 return false;
3271
3272 if (MethodProtocol && MethodInListProtocol)
3273 return true;
3274
3275 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3276 ObjCInterfaceDecl *MethodInListInterface =
3277 MethodInList->getClassInterface();
3278 return MethodInterface == MethodInListInterface;
3279}
3280
3281void Sema::addMethodToGlobalList(ObjCMethodList *List,
3282 ObjCMethodDecl *Method) {
3283 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3284 // inside categories.
3285 if (ObjCCategoryDecl *CD =
3286 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
3287 if (!CD->IsClassExtension() && List->getBits() < 2)
3288 List->setBits(List->getBits() + 1);
3289
3290 // If the list is empty, make it a singleton list.
3291 if (List->getMethod() == nullptr) {
3292 List->setMethod(Method);
3293 List->setNext(nullptr);
3294 return;
3295 }
3296
3297 // We've seen a method with this name, see if we have already seen this type
3298 // signature.
3299 ObjCMethodList *Previous = List;
3300 ObjCMethodList *ListWithSameDeclaration = nullptr;
3301 for (; List; Previous = List, List = List->getNext()) {
3302 // If we are building a module, keep all of the methods.
3303 if (getLangOpts().isCompilingModule())
3304 continue;
3305
3306 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3307 List->getMethod());
3308 // Looking for method with a type bound requires the correct context exists.
3309 // We need to insert a method into the list if the context is different.
3310 // If the method's declaration matches the list
3311 // a> the method belongs to a different context: we need to insert it, in
3312 // order to emit the availability message, we need to prioritize over
3313 // availability among the methods with the same declaration.
3314 // b> the method belongs to the same context: there is no need to insert a
3315 // new entry.
3316 // If the method's declaration does not match the list, we insert it to the
3317 // end.
3318 if (!SameDeclaration ||
3319 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
3320 // Even if two method types do not match, we would like to say
3321 // there is more than one declaration so unavailability/deprecated
3322 // warning is not too noisy.
3323 if (!Method->isDefined())
3324 List->setHasMoreThanOneDecl(true);
3325
3326 // For methods with the same declaration, the one that is deprecated
3327 // should be put in the front for better diagnostics.
3328 if (Method->isDeprecated() && SameDeclaration &&
3329 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3330 ListWithSameDeclaration = List;
3331
3332 if (Method->isUnavailable() && SameDeclaration &&
3333 !ListWithSameDeclaration &&
3334 List->getMethod()->getAvailability() < AR_Deprecated)
3335 ListWithSameDeclaration = List;
3336 continue;
3337 }
3338
3339 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
3340
3341 // Propagate the 'defined' bit.
3342 if (Method->isDefined())
3343 PrevObjCMethod->setDefined(true);
3344 else {
3345 // Objective-C doesn't allow an @interface for a class after its
3346 // @implementation. So if Method is not defined and there already is
3347 // an entry for this type signature, Method has to be for a different
3348 // class than PrevObjCMethod.
3349 List->setHasMoreThanOneDecl(true);
3350 }
3351
3352 // If a method is deprecated, push it in the global pool.
3353 // This is used for better diagnostics.
3354 if (Method->isDeprecated()) {
3355 if (!PrevObjCMethod->isDeprecated())
3356 List->setMethod(Method);
3357 }
3358 // If the new method is unavailable, push it into global pool
3359 // unless previous one is deprecated.
3360 if (Method->isUnavailable()) {
3361 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
3362 List->setMethod(Method);
3363 }
3364
3365 return;
3366 }
3367
3368 // We have a new signature for an existing method - add it.
3369 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
3370 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
3371
3372 // We insert it right before ListWithSameDeclaration.
3373 if (ListWithSameDeclaration) {
3374 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3375 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3376 ListWithSameDeclaration->setMethod(Method);
3377 ListWithSameDeclaration->setNext(List);
3378 return;
3379 }
3380
3381 Previous->setNext(new (Mem) ObjCMethodList(Method));
3382}
3383
3384/// Read the contents of the method pool for a given selector from
3385/// external storage.
3386void Sema::ReadMethodPool(Selector Sel) {
3387 assert(ExternalSource && "We need an external AST source")((ExternalSource && "We need an external AST source")
? static_cast<void> (0) : __assert_fail ("ExternalSource && \"We need an external AST source\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 3387, __PRETTY_FUNCTION__))
;
3388 ExternalSource->ReadMethodPool(Sel);
3389}
3390
3391void Sema::updateOutOfDateSelector(Selector Sel) {
3392 if (!ExternalSource)
3393 return;
3394 ExternalSource->updateOutOfDateSelector(Sel);
3395}
3396
3397void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
3398 bool instance) {
3399 // Ignore methods of invalid containers.
3400 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
3401 return;
3402
3403 if (ExternalSource)
3404 ReadMethodPool(Method->getSelector());
3405
3406 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
3407 if (Pos == MethodPool.end())
3408 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3409 GlobalMethods())).first;
3410
3411 Method->setDefined(impl);
3412
3413 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
3414 addMethodToGlobalList(&Entry, Method);
3415}
3416
3417/// Determines if this is an "acceptable" loose mismatch in the global
3418/// method pool. This exists mostly as a hack to get around certain
3419/// global mismatches which we can't afford to make warnings / errors.
3420/// Really, what we want is a way to take a method out of the global
3421/// method pool.
3422static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3423 ObjCMethodDecl *other) {
3424 if (!chosen->isInstanceMethod())
3425 return false;
3426
3427 Selector sel = chosen->getSelector();
3428 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3429 return false;
3430
3431 // Don't complain about mismatches for -length if the method we
3432 // chose has an integral result type.
3433 return (chosen->getReturnType()->isIntegerType());
3434}
3435
3436/// Return true if the given method is wthin the type bound.
3437static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3438 const ObjCObjectType *TypeBound) {
3439 if (!TypeBound)
3440 return true;
3441
3442 if (TypeBound->isObjCId())
3443 // FIXME: should we handle the case of bounding to id<A, B> differently?
3444 return true;
3445
3446 auto *BoundInterface = TypeBound->getInterface();
3447 assert(BoundInterface && "unexpected object type!")((BoundInterface && "unexpected object type!") ? static_cast
<void> (0) : __assert_fail ("BoundInterface && \"unexpected object type!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 3447, __PRETTY_FUNCTION__))
;
3448
3449 // Check if the Method belongs to a protocol. We should allow any method
3450 // defined in any protocol, because any subclass could adopt the protocol.
3451 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3452 if (MethodProtocol) {
3453 return true;
3454 }
3455
3456 // If the Method belongs to a class, check if it belongs to the class
3457 // hierarchy of the class bound.
3458 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3459 // We allow methods declared within classes that are part of the hierarchy
3460 // of the class bound (superclass of, subclass of, or the same as the class
3461 // bound).
3462 return MethodInterface == BoundInterface ||
3463 MethodInterface->isSuperClassOf(BoundInterface) ||
3464 BoundInterface->isSuperClassOf(MethodInterface);
3465 }
3466 llvm_unreachable("unknown method context")::llvm::llvm_unreachable_internal("unknown method context", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 3466)
;
3467}
3468
3469/// We first select the type of the method: Instance or Factory, then collect
3470/// all methods with that type.
3471bool Sema::CollectMultipleMethodsInGlobalPool(
3472 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
3473 bool InstanceFirst, bool CheckTheOther,
3474 const ObjCObjectType *TypeBound) {
3475 if (ExternalSource)
3476 ReadMethodPool(Sel);
3477
3478 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3479 if (Pos == MethodPool.end())
3480 return false;
3481
3482 // Gather the non-hidden methods.
3483 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3484 Pos->second.second;
3485 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
3486 if (M->getMethod() && !M->getMethod()->isHidden()) {
3487 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3488 Methods.push_back(M->getMethod());
3489 }
3490
3491 // Return if we find any method with the desired kind.
3492 if (!Methods.empty())
3493 return Methods.size() > 1;
3494
3495 if (!CheckTheOther)
3496 return false;
3497
3498 // Gather the other kind.
3499 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3500 Pos->second.first;
3501 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
3502 if (M->getMethod() && !M->getMethod()->isHidden()) {
3503 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3504 Methods.push_back(M->getMethod());
3505 }
3506
3507 return Methods.size() > 1;
3508}
3509
3510bool Sema::AreMultipleMethodsInGlobalPool(
3511 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3512 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3513 // Diagnose finding more than one method in global pool.
3514 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3515 FilteredMethods.push_back(BestMethod);
3516
3517 for (auto *M : Methods)
3518 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3519 FilteredMethods.push_back(M);
3520
3521 if (FilteredMethods.size() > 1)
3522 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3523 receiverIdOrClass);
3524
3525 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3526 // Test for no method in the pool which should not trigger any warning by
3527 // caller.
3528 if (Pos == MethodPool.end())
3529 return true;
3530 ObjCMethodList &MethList =
3531 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
3532 return MethList.hasMoreThanOneDecl();
3533}
3534
3535ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3536 bool receiverIdOrClass,
3537 bool instance) {
3538 if (ExternalSource)
3539 ReadMethodPool(Sel);
3540
3541 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3542 if (Pos == MethodPool.end())
3543 return nullptr;
3544
3545 // Gather the non-hidden methods.
3546 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
3547 SmallVector<ObjCMethodDecl *, 4> Methods;
3548 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
3549 if (M->getMethod() && !M->getMethod()->isHidden())
3550 return M->getMethod();
3551 }
3552 return nullptr;
3553}
3554
3555void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3556 Selector Sel, SourceRange R,
3557 bool receiverIdOrClass) {
3558 // We found multiple methods, so we may have to complain.
3559 bool issueDiagnostic = false, issueError = false;
3560
3561 // We support a warning which complains about *any* difference in
3562 // method signature.
3563 bool strictSelectorMatch =
3564 receiverIdOrClass &&
3565 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
3566 if (strictSelectorMatch) {
3567 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3568 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3569 issueDiagnostic = true;
3570 break;
3571 }
3572 }
3573 }
3574
3575 // If we didn't see any strict differences, we won't see any loose
3576 // differences. In ARC, however, we also need to check for loose
3577 // mismatches, because most of them are errors.
3578 if (!strictSelectorMatch ||
3579 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3580 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3581 // This checks if the methods differ in type mismatch.
3582 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3583 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3584 issueDiagnostic = true;
3585 if (getLangOpts().ObjCAutoRefCount)
3586 issueError = true;
3587 break;
3588 }
3589 }
3590
3591 if (issueDiagnostic) {
3592 if (issueError)
3593 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3594 else if (strictSelectorMatch)
3595 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3596 else
3597 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
3598
3599 Diag(Methods[0]->getBeginLoc(),
3600 issueError ? diag::note_possibility : diag::note_using)
3601 << Methods[0]->getSourceRange();
3602 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3603 Diag(Methods[I]->getBeginLoc(), diag::note_also_found)
3604 << Methods[I]->getSourceRange();
3605 }
3606 }
3607}
3608
3609ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
3610 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3611 if (Pos == MethodPool.end())
3612 return nullptr;
3613
3614 GlobalMethods &Methods = Pos->second;
3615 for (const ObjCMethodList *Method = &Methods.first; Method;
3616 Method = Method->getNext())
3617 if (Method->getMethod() &&
3618 (Method->getMethod()->isDefined() ||
3619 Method->getMethod()->isPropertyAccessor()))
3620 return Method->getMethod();
3621
3622 for (const ObjCMethodList *Method = &Methods.second; Method;
3623 Method = Method->getNext())
3624 if (Method->getMethod() &&
3625 (Method->getMethod()->isDefined() ||
3626 Method->getMethod()->isPropertyAccessor()))
3627 return Method->getMethod();
3628 return nullptr;
3629}
3630
3631static void
3632HelperSelectorsForTypoCorrection(
3633 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3634 StringRef Typo, const ObjCMethodDecl * Method) {
3635 const unsigned MaxEditDistance = 1;
3636 unsigned BestEditDistance = MaxEditDistance + 1;
3637 std::string MethodName = Method->getSelector().getAsString();
3638
3639 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3640 if (MinPossibleEditDistance > 0 &&
3641 Typo.size() / MinPossibleEditDistance < 1)
3642 return;
3643 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3644 if (EditDistance > MaxEditDistance)
3645 return;
3646 if (EditDistance == BestEditDistance)
3647 BestMethod.push_back(Method);
3648 else if (EditDistance < BestEditDistance) {
3649 BestMethod.clear();
3650 BestMethod.push_back(Method);
3651 }
3652}
3653
3654static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3655 QualType ObjectType) {
3656 if (ObjectType.isNull())
3657 return true;
3658 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3659 return true;
3660 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3661 nullptr;
3662}
3663
3664const ObjCMethodDecl *
3665Sema::SelectorsForTypoCorrection(Selector Sel,
3666 QualType ObjectType) {
3667 unsigned NumArgs = Sel.getNumArgs();
3668 SmallVector<const ObjCMethodDecl *, 8> Methods;
3669 bool ObjectIsId = true, ObjectIsClass = true;
3670 if (ObjectType.isNull())
3671 ObjectIsId = ObjectIsClass = false;
3672 else if (!ObjectType->isObjCObjectPointerType())
3673 return nullptr;
3674 else if (const ObjCObjectPointerType *ObjCPtr =
3675 ObjectType->getAsObjCInterfacePointerType()) {
3676 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3677 ObjectIsId = ObjectIsClass = false;
3678 }
3679 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3680 ObjectIsClass = false;
3681 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3682 ObjectIsId = false;
3683 else
3684 return nullptr;
3685
3686 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3687 e = MethodPool.end(); b != e; b++) {
3688 // instance methods
3689 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
3690 if (M->getMethod() &&
3691 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3692 (M->getMethod()->getSelector() != Sel)) {
3693 if (ObjectIsId)
3694 Methods.push_back(M->getMethod());
3695 else if (!ObjectIsClass &&
3696 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3697 ObjectType))
3698 Methods.push_back(M->getMethod());
3699 }
3700 // class methods
3701 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
3702 if (M->getMethod() &&
3703 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3704 (M->getMethod()->getSelector() != Sel)) {
3705 if (ObjectIsClass)
3706 Methods.push_back(M->getMethod());
3707 else if (!ObjectIsId &&
3708 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3709 ObjectType))
3710 Methods.push_back(M->getMethod());
3711 }
3712 }
3713
3714 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3715 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3716 HelperSelectorsForTypoCorrection(SelectedMethods,
3717 Sel.getAsString(), Methods[i]);
3718 }
3719 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
3720}
3721
3722/// DiagnoseDuplicateIvars -
3723/// Check for duplicate ivars in the entire class at the start of
3724/// \@implementation. This becomes necesssary because class extension can
3725/// add ivars to a class in random order which will not be known until
3726/// class's \@implementation is seen.
3727void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3728 ObjCInterfaceDecl *SID) {
3729 for (auto *Ivar : ID->ivars()) {
3730 if (Ivar->isInvalidDecl())
3731 continue;
3732 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3733 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3734 if (prevIvar) {
3735 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3736 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3737 Ivar->setInvalidDecl();
3738 }
3739 }
3740 }
3741}
3742
3743/// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3744static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3745 if (S.getLangOpts().ObjCWeak) return;
3746
3747 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3748 ivar; ivar = ivar->getNextIvar()) {
3749 if (ivar->isInvalidDecl()) continue;
3750 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3751 if (S.getLangOpts().ObjCWeakRuntime) {
3752 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3753 } else {
3754 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3755 }
3756 }
3757 }
3758}
3759
3760/// Diagnose attempts to use flexible array member with retainable object type.
3761static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
3762 ObjCInterfaceDecl *ID) {
3763 if (!S.getLangOpts().ObjCAutoRefCount)
3764 return;
3765
3766 for (auto ivar = ID->all_declared_ivar_begin(); ivar;
3767 ivar = ivar->getNextIvar()) {
3768 if (ivar->isInvalidDecl())
3769 continue;
3770 QualType IvarTy = ivar->getType();
3771 if (IvarTy->isIncompleteArrayType() &&
3772 (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) &&
3773 IvarTy->isObjCLifetimeType()) {
3774 S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3775 ivar->setInvalidDecl();
3776 }
3777 }
3778}
3779
3780Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3781 switch (CurContext->getDeclKind()) {
3782 case Decl::ObjCInterface:
3783 return Sema::OCK_Interface;
3784 case Decl::ObjCProtocol:
3785 return Sema::OCK_Protocol;
3786 case Decl::ObjCCategory:
3787 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
3788 return Sema::OCK_ClassExtension;
3789 return Sema::OCK_Category;
3790 case Decl::ObjCImplementation:
3791 return Sema::OCK_Implementation;
3792 case Decl::ObjCCategoryImpl:
3793 return Sema::OCK_CategoryImplementation;
3794
3795 default:
3796 return Sema::OCK_None;
3797 }
3798}
3799
3800static bool IsVariableSizedType(QualType T) {
3801 if (T->isIncompleteArrayType())
3802 return true;
3803 const auto *RecordTy = T->getAs<RecordType>();
3804 return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
3805}
3806
3807static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
3808 ObjCInterfaceDecl *IntfDecl = nullptr;
3809 ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3810 ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
3811 if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3812 Ivars = IntfDecl->ivars();
3813 } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
3814 IntfDecl = ImplDecl->getClassInterface();
3815 Ivars = ImplDecl->ivars();
3816 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3817 if (CategoryDecl->IsClassExtension()) {
3818 IntfDecl = CategoryDecl->getClassInterface();
3819 Ivars = CategoryDecl->ivars();
3820 }
3821 }
3822
3823 // Check if variable sized ivar is in interface and visible to subclasses.
3824 if (!isa<ObjCInterfaceDecl>(OCD)) {
3825 for (auto ivar : Ivars) {
3826 if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
3827 S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3828 << ivar->getDeclName() << ivar->getType();
3829 }
3830 }
3831 }
3832
3833 // Subsequent checks require interface decl.
3834 if (!IntfDecl)
3835 return;
3836
3837 // Check if variable sized ivar is followed by another ivar.
3838 for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
3839 ivar = ivar->getNextIvar()) {
3840 if (ivar->isInvalidDecl() || !ivar->getNextIvar())
3841 continue;
3842 QualType IvarTy = ivar->getType();
3843 bool IsInvalidIvar = false;
3844 if (IvarTy->isIncompleteArrayType()) {
3845 S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3846 << ivar->getDeclName() << IvarTy
3847 << TTK_Class; // Use "class" for Obj-C.
3848 IsInvalidIvar = true;
3849 } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3850 if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3851 S.Diag(ivar->getLocation(),
3852 diag::err_objc_variable_sized_type_not_at_end)
3853 << ivar->getDeclName() << IvarTy;
3854 IsInvalidIvar = true;
3855 }
3856 }
3857 if (IsInvalidIvar) {
3858 S.Diag(ivar->getNextIvar()->getLocation(),
3859 diag::note_next_ivar_declaration)
3860 << ivar->getNextIvar()->getSynthesize();
3861 ivar->setInvalidDecl();
3862 }
3863 }
3864
3865 // Check if ObjC container adds ivars after variable sized ivar in superclass.
3866 // Perform the check only if OCD is the first container to declare ivars to
3867 // avoid multiple warnings for the same ivar.
3868 ObjCIvarDecl *FirstIvar =
3869 (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
3870 if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
3871 const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3872 while (SuperClass && SuperClass->ivar_empty())
3873 SuperClass = SuperClass->getSuperClass();
3874 if (SuperClass) {
3875 auto IvarIter = SuperClass->ivar_begin();
3876 std::advance(IvarIter, SuperClass->ivar_size() - 1);
3877 const ObjCIvarDecl *LastIvar = *IvarIter;
3878 if (IsVariableSizedType(LastIvar->getType())) {
3879 S.Diag(FirstIvar->getLocation(),
3880 diag::warn_superclass_variable_sized_type_not_at_end)
3881 << FirstIvar->getDeclName() << LastIvar->getDeclName()
3882 << LastIvar->getType() << SuperClass->getDeclName();
3883 S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3884 << LastIvar->getDeclName();
3885 }
3886 }
3887 }
3888}
3889
3890// Note: For class/category implementations, allMethods is always null.
3891Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
3892 ArrayRef<DeclGroupPtrTy> allTUVars) {
3893 if (getObjCContainerKind() == Sema::OCK_None)
3894 return nullptr;
3895
3896 assert(AtEnd.isValid() && "Invalid location for '@end'")((AtEnd.isValid() && "Invalid location for '@end'") ?
static_cast<void> (0) : __assert_fail ("AtEnd.isValid() && \"Invalid location for '@end'\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 3896, __PRETTY_FUNCTION__))
;
3897
3898 auto *OCD = cast<ObjCContainerDecl>(CurContext);
3899 Decl *ClassDecl = OCD;
3900
3901 bool isInterfaceDeclKind =
3902 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3903 || isa<ObjCProtocolDecl>(ClassDecl);
3904 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
3905
3906 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3907 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3908 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3909
3910 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
3911 ObjCMethodDecl *Method =
3912 cast_or_null<ObjCMethodDecl>(allMethods[i]);
3913
3914 if (!Method) continue; // Already issued a diagnostic.
3915 if (Method->isInstanceMethod()) {
3916 /// Check for instance method of the same name with incompatible types
3917 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
3918 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
3919 : false;
3920 if ((isInterfaceDeclKind && PrevMethod && !match)
3921 || (checkIdenticalMethods && match)) {
3922 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
3923 << Method->getDeclName();
3924 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3925 Method->setInvalidDecl();
3926 } else {
3927 if (PrevMethod) {
3928 Method->setAsRedeclaration(PrevMethod);
3929 if (!Context.getSourceManager().isInSystemHeader(
3930 Method->getLocation()))
3931 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3932 << Method->getDeclName();
3933 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3934 }
3935 InsMap[Method->getSelector()] = Method;
3936 /// The following allows us to typecheck messages to "id".
3937 AddInstanceMethodToGlobalPool(Method);
3938 }
3939 } else {
3940 /// Check for class method of the same name with incompatible types
3941 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
3942 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
3943 : false;
3944 if ((isInterfaceDeclKind && PrevMethod && !match)
3945 || (checkIdenticalMethods && match)) {
3946 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
3947 << Method->getDeclName();
3948 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3949 Method->setInvalidDecl();
3950 } else {
3951 if (PrevMethod) {
3952 Method->setAsRedeclaration(PrevMethod);
3953 if (!Context.getSourceManager().isInSystemHeader(
3954 Method->getLocation()))
3955 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3956 << Method->getDeclName();
3957 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3958 }
3959 ClsMap[Method->getSelector()] = Method;
3960 AddFactoryMethodToGlobalPool(Method);
3961 }
3962 }
3963 }
3964 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3965 // Nothing to do here.
3966 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
3967 // Categories are used to extend the class by declaring new methods.
3968 // By the same token, they are also used to add new properties. No
3969 // need to compare the added property to those in the class.
3970
3971 if (C->IsClassExtension()) {
3972 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3973 DiagnoseClassExtensionDupMethods(C, CCPrimary);
3974 }
3975 }
3976 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
3977 if (CDecl->getIdentifier())
3978 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3979 // user-defined setter/getter. It also synthesizes setter/getter methods
3980 // and adds them to the DeclContext and global method pools.
3981 for (auto *I : CDecl->properties())
3982 ProcessPropertyDecl(I);
3983 CDecl->setAtEndRange(AtEnd);
3984 }
3985 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
3986 IC->setAtEndRange(AtEnd);
3987 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
3988 // Any property declared in a class extension might have user
3989 // declared setter or getter in current class extension or one
3990 // of the other class extensions. Mark them as synthesized as
3991 // property will be synthesized when property with same name is
3992 // seen in the @implementation.
3993 for (const auto *Ext : IDecl->visible_extensions()) {
3994 for (const auto *Property : Ext->instance_properties()) {
3995 // Skip over properties declared @dynamic
3996 if (const ObjCPropertyImplDecl *PIDecl
3997 = IC->FindPropertyImplDecl(Property->getIdentifier(),
3998 Property->getQueryKind()))
3999 if (PIDecl->getPropertyImplementation()
4000 == ObjCPropertyImplDecl::Dynamic)
4001 continue;
4002
4003 for (const auto *Ext : IDecl->visible_extensions()) {
4004 if (ObjCMethodDecl *GetterMethod
4005 = Ext->getInstanceMethod(Property->getGetterName()))
4006 GetterMethod->setPropertyAccessor(true);
4007 if (!Property->isReadOnly())
4008 if (ObjCMethodDecl *SetterMethod
4009 = Ext->getInstanceMethod(Property->getSetterName()))
4010 SetterMethod->setPropertyAccessor(true);
4011 }
4012 }
4013 }
4014 ImplMethodsVsClassMethods(S, IC, IDecl);
4015 AtomicPropertySetterGetterRules(IC, IDecl);
4016 DiagnoseOwningPropertyGetterSynthesis(IC);
4017 DiagnoseUnusedBackingIvarInAccessor(S, IC);
4018 if (IDecl->hasDesignatedInitializers())
4019 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
4020 DiagnoseWeakIvars(*this, IC);
4021 DiagnoseRetainableFlexibleArrayMember(*this, IDecl);
4022
4023 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
4024 if (IDecl->getSuperClass() == nullptr) {
4025 // This class has no superclass, so check that it has been marked with
4026 // __attribute((objc_root_class)).
4027 if (!HasRootClassAttr) {
4028 SourceLocation DeclLoc(IDecl->getLocation());
4029 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
4030 Diag(DeclLoc, diag::warn_objc_root_class_missing)
4031 << IDecl->getIdentifier();
4032 // See if NSObject is in the current scope, and if it is, suggest
4033 // adding " : NSObject " to the class declaration.
4034 NamedDecl *IF = LookupSingleName(TUScope,
4035 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
4036 DeclLoc, LookupOrdinaryName);
4037 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
4038 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
4039 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
4040 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
4041 } else {
4042 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
4043 }
4044 }
4045 } else if (HasRootClassAttr) {
4046 // Complain that only root classes may have this attribute.
4047 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
4048 }
4049
4050 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
4051 // An interface can subclass another interface with a
4052 // objc_subclassing_restricted attribute when it has that attribute as
4053 // well (because of interfaces imported from Swift). Therefore we have
4054 // to check if we can subclass in the implementation as well.
4055 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4056 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4057 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
4058 Diag(Super->getLocation(), diag::note_class_declared);
4059 }
4060 }
4061
4062 if (IDecl->hasAttr<ObjCClassStubAttr>())
4063 Diag(IC->getLocation(), diag::err_implementation_of_class_stub);
4064
4065 if (LangOpts.ObjCRuntime.isNonFragile()) {
4066 while (IDecl->getSuperClass()) {
4067 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
4068 IDecl = IDecl->getSuperClass();
4069 }
4070 }
4071 }
4072 SetIvarInitializers(IC);
4073 } else if (ObjCCategoryImplDecl* CatImplClass =
4074 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
4075 CatImplClass->setAtEndRange(AtEnd);
4076
4077 // Find category interface decl and then check that all methods declared
4078 // in this interface are implemented in the category @implementation.
4079 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
4080 if (ObjCCategoryDecl *Cat
4081 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
4082 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
4083 }
4084 }
4085 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
4086 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
4087 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4088 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4089 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
4090 Diag(Super->getLocation(), diag::note_class_declared);
4091 }
4092 }
4093
4094 if (IntfDecl->hasAttr<ObjCClassStubAttr>() &&
4095 !IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>())
4096 Diag(IntfDecl->getLocation(), diag::err_class_stub_subclassing_mismatch);
4097 }
4098 DiagnoseVariableSizedIvars(*this, OCD);
4099 if (isInterfaceDeclKind) {
4100 // Reject invalid vardecls.
4101 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
4102 DeclGroupRef DG = allTUVars[i].get();
4103 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4104 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
4105 if (!VDecl->hasExternalStorage())
4106 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
4107 }
4108 }
4109 }
4110 ActOnObjCContainerFinishDefinition();
4111
4112 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
4113 DeclGroupRef DG = allTUVars[i].get();
4114 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4115 (*I)->setTopLevelDeclInObjCContainer();
4116 Consumer.HandleTopLevelDeclInObjCContainer(DG);
4117 }
4118
4119 ActOnDocumentableDecl(ClassDecl);
4120 return ClassDecl;
4121}
4122
4123/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
4124/// objective-c's type qualifier from the parser version of the same info.
4125static Decl::ObjCDeclQualifier
4126CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
4127 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
4128}
4129
4130/// Check whether the declared result type of the given Objective-C
4131/// method declaration is compatible with the method's class.
4132///
4133static Sema::ResultTypeCompatibilityKind
4134CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
4135 ObjCInterfaceDecl *CurrentClass) {
4136 QualType ResultType = Method->getReturnType();
4137
4138 // If an Objective-C method inherits its related result type, then its
4139 // declared result type must be compatible with its own class type. The
4140 // declared result type is compatible if:
4141 if (const ObjCObjectPointerType *ResultObjectType
4142 = ResultType->getAs<ObjCObjectPointerType>()) {
4143 // - it is id or qualified id, or
4144 if (ResultObjectType->isObjCIdType() ||
4145 ResultObjectType->isObjCQualifiedIdType())
4146 return Sema::RTC_Compatible;
4147
4148 if (CurrentClass) {
4149 if (ObjCInterfaceDecl *ResultClass
4150 = ResultObjectType->getInterfaceDecl()) {
4151 // - it is the same as the method's class type, or
4152 if (declaresSameEntity(CurrentClass, ResultClass))
4153 return Sema::RTC_Compatible;
4154
4155 // - it is a superclass of the method's class type
4156 if (ResultClass->isSuperClassOf(CurrentClass))
4157 return Sema::RTC_Compatible;
4158 }
4159 } else {
4160 // Any Objective-C pointer type might be acceptable for a protocol
4161 // method; we just don't know.
4162 return Sema::RTC_Unknown;
4163 }
4164 }
4165
4166 return Sema::RTC_Incompatible;
4167}
4168
4169namespace {
4170/// A helper class for searching for methods which a particular method
4171/// overrides.
4172class OverrideSearch {
4173public:
4174 const ObjCMethodDecl *Method;
4175 llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
4176 bool Recursive;
4177
4178public:
4179 OverrideSearch(Sema &S, const ObjCMethodDecl *method) : Method(method) {
4180 Selector selector = method->getSelector();
4181
4182 // Bypass this search if we've never seen an instance/class method
4183 // with this selector before.
4184 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4185 if (it == S.MethodPool.end()) {
4186 if (!S.getExternalSource()) return;
4187 S.ReadMethodPool(selector);
4188
4189 it = S.MethodPool.find(selector);
4190 if (it == S.MethodPool.end())
4191 return;
4192 }
4193 const ObjCMethodList &list =
4194 method->isInstanceMethod() ? it->second.first : it->second.second;
4195 if (!list.getMethod()) return;
4196
4197 const ObjCContainerDecl *container
4198 = cast<ObjCContainerDecl>(method->getDeclContext());
4199
4200 // Prevent the search from reaching this container again. This is
4201 // important with categories, which override methods from the
4202 // interface and each other.
4203 if (const ObjCCategoryDecl *Category =
4204 dyn_cast<ObjCCategoryDecl>(container)) {
4205 searchFromContainer(container);
4206 if (const ObjCInterfaceDecl *Interface = Category->getClassInterface())
4207 searchFromContainer(Interface);
4208 } else {
4209 searchFromContainer(container);
4210 }
4211 }
4212
4213 typedef decltype(Overridden)::iterator iterator;
4214 iterator begin() const { return Overridden.begin(); }
4215 iterator end() const { return Overridden.end(); }
4216
4217private:
4218 void searchFromContainer(const ObjCContainerDecl *container) {
4219 if (container->isInvalidDecl()) return;
4220
4221 switch (container->getDeclKind()) {
4222#define OBJCCONTAINER(type, base) \
4223 case Decl::type: \
4224 searchFrom(cast<type##Decl>(container)); \
4225 break;
4226#define ABSTRACT_DECL(expansion)
4227#define DECL(type, base) \
4228 case Decl::type:
4229#include "clang/AST/DeclNodes.inc"
4230 llvm_unreachable("not an ObjC container!")::llvm::llvm_unreachable_internal("not an ObjC container!", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 4230)
;
4231 }
4232 }
4233
4234 void searchFrom(const ObjCProtocolDecl *protocol) {
4235 if (!protocol->hasDefinition())
4236 return;
4237
4238 // A method in a protocol declaration overrides declarations from
4239 // referenced ("parent") protocols.
4240 search(protocol->getReferencedProtocols());
4241 }
4242
4243 void searchFrom(const ObjCCategoryDecl *category) {
4244 // A method in a category declaration overrides declarations from
4245 // the main class and from protocols the category references.
4246 // The main class is handled in the constructor.
4247 search(category->getReferencedProtocols());
4248 }
4249
4250 void searchFrom(const ObjCCategoryImplDecl *impl) {
4251 // A method in a category definition that has a category
4252 // declaration overrides declarations from the category
4253 // declaration.
4254 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4255 search(category);
4256 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4257 search(Interface);
4258
4259 // Otherwise it overrides declarations from the class.
4260 } else if (const auto *Interface = impl->getClassInterface()) {
4261 search(Interface);
4262 }
4263 }
4264
4265 void searchFrom(const ObjCInterfaceDecl *iface) {
4266 // A method in a class declaration overrides declarations from
4267 if (!iface->hasDefinition())
4268 return;
4269
4270 // - categories,
4271 for (auto *Cat : iface->known_categories())
4272 search(Cat);
4273
4274 // - the super class, and
4275 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4276 search(super);
4277
4278 // - any referenced protocols.
4279 search(iface->getReferencedProtocols());
4280 }
4281
4282 void searchFrom(const ObjCImplementationDecl *impl) {
4283 // A method in a class implementation overrides declarations from
4284 // the class interface.
4285 if (const auto *Interface = impl->getClassInterface())
4286 search(Interface);
4287 }
4288
4289 void search(const ObjCProtocolList &protocols) {
4290 for (const auto *Proto : protocols)
4291 search(Proto);
4292 }
4293
4294 void search(const ObjCContainerDecl *container) {
4295 // Check for a method in this container which matches this selector.
4296 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
4297 Method->isInstanceMethod(),
4298 /*AllowHidden=*/true);
4299
4300 // If we find one, record it and bail out.
4301 if (meth) {
4302 Overridden.insert(meth);
4303 return;
4304 }
4305
4306 // Otherwise, search for methods that a hypothetical method here
4307 // would have overridden.
4308
4309 // Note that we're now in a recursive case.
4310 Recursive = true;
4311
4312 searchFromContainer(container);
4313 }
4314};
4315} // end anonymous namespace
4316
4317void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4318 ObjCInterfaceDecl *CurrentClass,
4319 ResultTypeCompatibilityKind RTC) {
4320 if (!ObjCMethod)
4321 return;
4322 // Search for overridden methods and merge information down from them.
4323 OverrideSearch overrides(*this, ObjCMethod);
4324 // Keep track if the method overrides any method in the class's base classes,
4325 // its protocols, or its categories' protocols; we will keep that info
4326 // in the ObjCMethodDecl.
4327 // For this info, a method in an implementation is not considered as
4328 // overriding the same method in the interface or its categories.
4329 bool hasOverriddenMethodsInBaseOrProtocol = false;
4330 for (ObjCMethodDecl *overridden : overrides) {
4331 if (!hasOverriddenMethodsInBaseOrProtocol) {
4332 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4333 CurrentClass != overridden->getClassInterface() ||
4334 overridden->isOverriding()) {
4335 hasOverriddenMethodsInBaseOrProtocol = true;
4336
4337 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4338 // OverrideSearch will return as "overridden" the same method in the
4339 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4340 // check whether a category of a base class introduced a method with the
4341 // same selector, after the interface method declaration.
4342 // To avoid unnecessary lookups in the majority of cases, we use the
4343 // extra info bits in GlobalMethodPool to check whether there were any
4344 // category methods with this selector.
4345 GlobalMethodPool::iterator It =
4346 MethodPool.find(ObjCMethod->getSelector());
4347 if (It != MethodPool.end()) {
4348 ObjCMethodList &List =
4349 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4350 unsigned CategCount = List.getBits();
4351 if (CategCount > 0) {
4352 // If the method is in a category we'll do lookup if there were at
4353 // least 2 category methods recorded, otherwise only one will do.
4354 if (CategCount > 1 ||
4355 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4356 OverrideSearch overrides(*this, overridden);
4357 for (ObjCMethodDecl *SuperOverridden : overrides) {
4358 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4359 CurrentClass != SuperOverridden->getClassInterface()) {
4360 hasOverriddenMethodsInBaseOrProtocol = true;
4361 overridden->setOverriding(true);
4362 break;
4363 }
4364 }
4365 }
4366 }
4367 }
4368 }
4369 }
4370
4371 // Propagate down the 'related result type' bit from overridden methods.
4372 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4373 ObjCMethod->setRelatedResultType();
4374
4375 // Then merge the declarations.
4376 mergeObjCMethodDecls(ObjCMethod, overridden);
4377
4378 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4379 continue; // Conflicting properties are detected elsewhere.
4380
4381 // Check for overriding methods
4382 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4383 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4384 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4385 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4386
4387 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
4388 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4389 !overridden->isImplicit() /* not meant for properties */) {
4390 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4391 E = ObjCMethod->param_end();
4392 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4393 PrevE = overridden->param_end();
4394 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
4395 assert(PrevI != overridden->param_end() && "Param mismatch")((PrevI != overridden->param_end() && "Param mismatch"
) ? static_cast<void> (0) : __assert_fail ("PrevI != overridden->param_end() && \"Param mismatch\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 4395, __PRETTY_FUNCTION__))
;
4396 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4397 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4398 // If type of argument of method in this class does not match its
4399 // respective argument type in the super class method, issue warning;
4400 if (!Context.typesAreCompatible(T1, T2)) {
4401 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4402 << T1 << T2;
4403 Diag(overridden->getLocation(), diag::note_previous_declaration);
4404 break;
4405 }
4406 }
4407 }
4408 }
4409
4410 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4411}
4412
4413/// Merge type nullability from for a redeclaration of the same entity,
4414/// producing the updated type of the redeclared entity.
4415static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4416 QualType type,
4417 bool usesCSKeyword,
4418 SourceLocation prevLoc,
4419 QualType prevType,
4420 bool prevUsesCSKeyword) {
4421 // Determine the nullability of both types.
4422 auto nullability = type->getNullability(S.Context);
4423 auto prevNullability = prevType->getNullability(S.Context);
4424
4425 // Easy case: both have nullability.
4426 if (nullability.hasValue() == prevNullability.hasValue()) {
4427 // Neither has nullability; continue.
4428 if (!nullability)
4429 return type;
4430
4431 // The nullabilities are equivalent; do nothing.
4432 if (*nullability == *prevNullability)
4433 return type;
4434
4435 // Complain about mismatched nullability.
4436 S.Diag(loc, diag::err_nullability_conflicting)
4437 << DiagNullabilityKind(*nullability, usesCSKeyword)
4438 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
4439 return type;
4440 }
4441
4442 // If it's the redeclaration that has nullability, don't change anything.
4443 if (nullability)
4444 return type;
4445
4446 // Otherwise, provide the result with the same nullability.
4447 return S.Context.getAttributedType(
4448 AttributedType::getNullabilityAttrKind(*prevNullability),
4449 type, type);
4450}
4451
4452/// Merge information from the declaration of a method in the \@interface
4453/// (or a category/extension) into the corresponding method in the
4454/// @implementation (for a class or category).
4455static void mergeInterfaceMethodToImpl(Sema &S,
4456 ObjCMethodDecl *method,
4457 ObjCMethodDecl *prevMethod) {
4458 // Merge the objc_requires_super attribute.
4459 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4460 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4461 // merge the attribute into implementation.
4462 method->addAttr(
4463 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4464 method->getLocation()));
4465 }
4466
4467 // Merge nullability of the result type.
4468 QualType newReturnType
4469 = mergeTypeNullabilityForRedecl(
4470 S, method->getReturnTypeSourceRange().getBegin(),
4471 method->getReturnType(),
4472 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4473 prevMethod->getReturnTypeSourceRange().getBegin(),
4474 prevMethod->getReturnType(),
4475 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4476 method->setReturnType(newReturnType);
4477
4478 // Handle each of the parameters.
4479 unsigned numParams = method->param_size();
4480 unsigned numPrevParams = prevMethod->param_size();
4481 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4482 ParmVarDecl *param = method->param_begin()[i];
4483 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4484
4485 // Merge nullability.
4486 QualType newParamType
4487 = mergeTypeNullabilityForRedecl(
4488 S, param->getLocation(), param->getType(),
4489 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4490 prevParam->getLocation(), prevParam->getType(),
4491 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4492 param->setType(newParamType);
4493 }
4494}
4495
4496/// Verify that the method parameters/return value have types that are supported
4497/// by the x86 target.
4498static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4499 const ObjCMethodDecl *Method) {
4500 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==((SemaRef.getASTContext().getTargetInfo().getTriple().getArch
() == llvm::Triple::x86 && "x86-specific check invoked for a different target"
) ? static_cast<void> (0) : __assert_fail ("SemaRef.getASTContext().getTargetInfo().getTriple().getArch() == llvm::Triple::x86 && \"x86-specific check invoked for a different target\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 4502, __PRETTY_FUNCTION__))
4501 llvm::Triple::x86 &&((SemaRef.getASTContext().getTargetInfo().getTriple().getArch
() == llvm::Triple::x86 && "x86-specific check invoked for a different target"
) ? static_cast<void> (0) : __assert_fail ("SemaRef.getASTContext().getTargetInfo().getTriple().getArch() == llvm::Triple::x86 && \"x86-specific check invoked for a different target\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 4502, __PRETTY_FUNCTION__))
4502 "x86-specific check invoked for a different target")((SemaRef.getASTContext().getTargetInfo().getTriple().getArch
() == llvm::Triple::x86 && "x86-specific check invoked for a different target"
) ? static_cast<void> (0) : __assert_fail ("SemaRef.getASTContext().getTargetInfo().getTriple().getArch() == llvm::Triple::x86 && \"x86-specific check invoked for a different target\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 4502, __PRETTY_FUNCTION__))
;
4503 SourceLocation Loc;
4504 QualType T;
4505 for (const ParmVarDecl *P : Method->parameters()) {
4506 if (P->getType()->isVectorType()) {
4507 Loc = P->getBeginLoc();
4508 T = P->getType();
4509 break;
4510 }
4511 }
4512 if (Loc.isInvalid()) {
4513 if (Method->getReturnType()->isVectorType()) {
4514 Loc = Method->getReturnTypeSourceRange().getBegin();
4515 T = Method->getReturnType();
4516 } else
4517 return;
4518 }
4519
4520 // Vector parameters/return values are not supported by objc_msgSend on x86 in
4521 // iOS < 9 and macOS < 10.11.
4522 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4523 VersionTuple AcceptedInVersion;
4524 if (Triple.getOS() == llvm::Triple::IOS)
4525 AcceptedInVersion = VersionTuple(/*Major=*/9);
4526 else if (Triple.isMacOSX())
4527 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4528 else
4529 return;
4530 if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
4531 AcceptedInVersion)
4532 return;
4533 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4534 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4535 : /*parameter*/ 0)
4536 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4537}
4538
4539Decl *Sema::ActOnMethodDeclaration(
4540 Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc,
4541 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4542 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
4543 // optional arguments. The number of types/arguments is obtained
4544 // from the Sel.getNumArgs().
4545 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
4546 unsigned CNumArgs, // c-style args
4547 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
4548 bool isVariadic, bool MethodDefinition) {
4549 // Make sure we can establish a context for the method.
4550 if (!CurContext->isObjCContainer()) {
4551 Diag(MethodLoc, diag::err_missing_method_context);
4552 return nullptr;
4553 }
4554 Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
4555 QualType resultDeclType;
4556
4557 bool HasRelatedResultType = false;
4558 TypeSourceInfo *ReturnTInfo = nullptr;
4559 if (ReturnType) {
4560 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
4561
4562 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
4563 return nullptr;
4564
4565 QualType bareResultType = resultDeclType;
4566 (void)AttributedType::stripOuterNullability(bareResultType);
4567 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
4568 } else { // get the type for "id".
4569 resultDeclType = Context.getObjCIdType();
4570 Diag(MethodLoc, diag::warn_missing_method_return_type)
4571 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
4572 }
4573
4574 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4575 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4576 MethodType == tok::minus, isVariadic,
4577 /*isPropertyAccessor=*/false,
4578 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4579 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4580 : ObjCMethodDecl::Required,
4581 HasRelatedResultType);
4582
4583 SmallVector<ParmVarDecl*, 16> Params;
4584
4585 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
4586 QualType ArgType;
4587 TypeSourceInfo *DI;
4588
4589 if (!ArgInfo[i].Type) {
4590 ArgType = Context.getObjCIdType();
4591 DI = nullptr;
4592 } else {
4593 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
4594 }
4595
4596 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4597 LookupOrdinaryName, forRedeclarationInCurContext());
4598 LookupName(R, S);
4599 if (R.isSingleResult()) {
4600 NamedDecl *PrevDecl = R.getFoundDecl();
4601 if (S->isDeclScope(PrevDecl)) {
4602 Diag(ArgInfo[i].NameLoc,
4603 (MethodDefinition ? diag::warn_method_param_redefinition
4604 : diag::warn_method_param_declaration))
4605 << ArgInfo[i].Name;
4606 Diag(PrevDecl->getLocation(),
4607 diag::note_previous_declaration);
4608 }
4609 }
4610
4611 SourceLocation StartLoc = DI
4612 ? DI->getTypeLoc().getBeginLoc()
4613 : ArgInfo[i].NameLoc;
4614
4615 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4616 ArgInfo[i].NameLoc, ArgInfo[i].Name,
4617 ArgType, DI, SC_None);
4618
4619 Param->setObjCMethodScopeInfo(i);
4620
4621 Param->setObjCDeclQualifier(
4622 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
4623
4624 // Apply the attributes to the parameter.
4625 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
4626 AddPragmaAttributes(TUScope, Param);
4627
4628 if (Param->hasAttr<BlocksAttr>()) {
4629 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4630 Param->setInvalidDecl();
4631 }
4632 S->AddDecl(Param);
4633 IdResolver.AddDecl(Param);
4634
4635 Params.push_back(Param);
4636 }
4637
4638 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
4639 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
4640 QualType ArgType = Param->getType();
4641 if (ArgType.isNull())
4642 ArgType = Context.getObjCIdType();
4643 else
4644 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
4645 ArgType = Context.getAdjustedParameterType(ArgType);
4646
4647 Param->setDeclContext(ObjCMethod);
4648 Params.push_back(Param);
4649 }
4650
4651 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
4652 ObjCMethod->setObjCDeclQualifier(
4653 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
4654
4655 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
4656 AddPragmaAttributes(TUScope, ObjCMethod);
4657
4658 // Add the method now.
4659 const ObjCMethodDecl *PrevMethod = nullptr;
4660 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
4661 if (MethodType == tok::minus) {
4662 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4663 ImpDecl->addInstanceMethod(ObjCMethod);
4664 } else {
4665 PrevMethod = ImpDecl->getClassMethod(Sel);
4666 ImpDecl->addClassMethod(ObjCMethod);
4667 }
4668
4669 // Merge information from the @interface declaration into the
4670 // @implementation.
4671 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4672 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4673 ObjCMethod->isInstanceMethod())) {
4674 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4675
4676 // Warn about defining -dealloc in a category.
4677 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4678 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4679 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4680 << ObjCMethod->getDeclName();
4681 }
4682 }
4683
4684 // Warn if a method declared in a protocol to which a category or
4685 // extension conforms is non-escaping and the implementation's method is
4686 // escaping.
4687 for (auto *C : IDecl->visible_categories())
4688 for (auto &P : C->protocols())
4689 if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(),
4690 ObjCMethod->isInstanceMethod())) {
4691 assert(ObjCMethod->parameters().size() ==((ObjCMethod->parameters().size() == IMD->parameters().
size() && "Methods have different number of parameters"
) ? static_cast<void> (0) : __assert_fail ("ObjCMethod->parameters().size() == IMD->parameters().size() && \"Methods have different number of parameters\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 4693, __PRETTY_FUNCTION__))
4692 IMD->parameters().size() &&((ObjCMethod->parameters().size() == IMD->parameters().
size() && "Methods have different number of parameters"
) ? static_cast<void> (0) : __assert_fail ("ObjCMethod->parameters().size() == IMD->parameters().size() && \"Methods have different number of parameters\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 4693, __PRETTY_FUNCTION__))
4693 "Methods have different number of parameters")((ObjCMethod->parameters().size() == IMD->parameters().
size() && "Methods have different number of parameters"
) ? static_cast<void> (0) : __assert_fail ("ObjCMethod->parameters().size() == IMD->parameters().size() && \"Methods have different number of parameters\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 4693, __PRETTY_FUNCTION__))
;
4694 auto OI = IMD->param_begin(), OE = IMD->param_end();
4695 auto NI = ObjCMethod->param_begin();
4696 for (; OI != OE; ++OI, ++NI)
4697 diagnoseNoescape(*NI, *OI, C, P, *this);
4698 }
4699 }
4700 } else {
4701 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
4702 }
4703
4704 if (PrevMethod) {
4705 // You can never have two method definitions with the same name.
4706 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
4707 << ObjCMethod->getDeclName();
4708 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4709 ObjCMethod->setInvalidDecl();
4710 return ObjCMethod;
4711 }
4712
4713 // If this Objective-C method does not have a related result type, but we
4714 // are allowed to infer related result types, try to do so based on the
4715 // method family.
4716 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4717 if (!CurrentClass) {
4718 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4719 CurrentClass = Cat->getClassInterface();
4720 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4721 CurrentClass = Impl->getClassInterface();
4722 else if (ObjCCategoryImplDecl *CatImpl
4723 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4724 CurrentClass = CatImpl->getClassInterface();
4725 }
4726
4727 ResultTypeCompatibilityKind RTC
4728 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
4729
4730 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
4731
4732 bool ARCError = false;
4733 if (getLangOpts().ObjCAutoRefCount)
4734 ARCError = CheckARCMethodDecl(ObjCMethod);
4735
4736 // Infer the related result type when possible.
4737 if (!ARCError && RTC == Sema::RTC_Compatible &&
4738 !ObjCMethod->hasRelatedResultType() &&
4739 LangOpts.ObjCInferRelatedResultType) {
4740 bool InferRelatedResultType = false;
4741 switch (ObjCMethod->getMethodFamily()) {
4742 case OMF_None:
4743 case OMF_copy:
4744 case OMF_dealloc:
4745 case OMF_finalize:
4746 case OMF_mutableCopy:
4747 case OMF_release:
4748 case OMF_retainCount:
4749 case OMF_initialize:
4750 case OMF_performSelector:
4751 break;
4752
4753 case OMF_alloc:
4754 case OMF_new:
4755 InferRelatedResultType = ObjCMethod->isClassMethod();
4756 break;
4757
4758 case OMF_init:
4759 case OMF_autorelease:
4760 case OMF_retain:
4761 case OMF_self:
4762 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4763 break;
4764 }
4765
4766 if (InferRelatedResultType &&
4767 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
4768 ObjCMethod->setRelatedResultType();
4769 }
4770
4771 if (MethodDefinition &&
4772 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
4773 checkObjCMethodX86VectorTypes(*this, ObjCMethod);
4774
4775 // + load method cannot have availability attributes. It get called on
4776 // startup, so it has to have the availability of the deployment target.
4777 if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
4778 if (ObjCMethod->isClassMethod() &&
4779 ObjCMethod->getSelector().getAsString() == "load") {
4780 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
4781 << 0;
4782 ObjCMethod->dropAttr<AvailabilityAttr>();
4783 }
4784 }
4785
4786 ActOnDocumentableDecl(ObjCMethod);
4787
4788 return ObjCMethod;
4789}
4790
4791bool Sema::CheckObjCDeclScope(Decl *D) {
4792 // Following is also an error. But it is caused by a missing @end
4793 // and diagnostic is issued elsewhere.
4794 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
4795 return false;
4796
4797 // If we switched context to translation unit while we are still lexically in
4798 // an objc container, it means the parser missed emitting an error.
4799 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4800 return false;
4801
4802 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4803 D->setInvalidDecl();
4804
4805 return true;
4806}
4807
4808/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
4809/// instance variables of ClassName into Decls.
4810void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
4811 IdentifierInfo *ClassName,
4812 SmallVectorImpl<Decl*> &Decls) {
4813 // Check that ClassName is a valid class
4814 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
4815 if (!Class) {
4816 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4817 return;
4818 }
4819 if (LangOpts.ObjCRuntime.isNonFragile()) {
4820 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4821 return;
4822 }
4823
4824 // Collect the instance variables
4825 SmallVector<const ObjCIvarDecl*, 32> Ivars;
4826 Context.DeepCollectObjCIvars(Class, true, Ivars);
4827 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
4828 for (unsigned i = 0; i < Ivars.size(); i++) {
4829 const FieldDecl* ID = Ivars[i];
4830 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
4831 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4832 /*FIXME: StartL=*/ID->getLocation(),
4833 ID->getLocation(),
4834 ID->getIdentifier(), ID->getType(),
4835 ID->getBitWidth());
4836 Decls.push_back(FD);
4837 }
4838
4839 // Introduce all of these fields into the appropriate scope.
4840 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
4841 D != Decls.end(); ++D) {
4842 FieldDecl *FD = cast<FieldDecl>(*D);
4843 if (getLangOpts().CPlusPlus)
4844 PushOnScopeChains(FD, S);
4845 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
4846 Record->addDecl(FD);
4847 }
4848}
4849
4850/// Build a type-check a new Objective-C exception variable declaration.
4851VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4852 SourceLocation StartLoc,
4853 SourceLocation IdLoc,
4854 IdentifierInfo *Id,
4855 bool Invalid) {
4856 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4857 // duration shall not be qualified by an address-space qualifier."
4858 // Since all parameters have automatic store duration, they can not have
4859 // an address space.
4860 if (T.getAddressSpace() != LangAS::Default) {
17
Assuming the condition is false
18
Taking false branch
4861 Diag(IdLoc, diag::err_arg_with_address_space);
4862 Invalid = true;
4863 }
4864
4865 // An @catch parameter must be an unqualified object pointer type;
4866 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4867 if (Invalid
18.1
'Invalid' is false
18.1
'Invalid' is false
18.1
'Invalid' is false
) {
19
Taking false branch
4868 // Don't do any further checking.
4869 } else if (T->isDependentType()) {
20
Assuming the condition is false
21
Taking false branch
4870 // Okay: we don't know what this type will instantiate to.
4871 } else if (T->isObjCQualifiedIdType()) {
22
Calling 'Type::isObjCQualifiedIdType'
26
Returning from 'Type::isObjCQualifiedIdType'
27
Taking false branch
4872 Invalid = true;
4873 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
4874 } else if (T->isObjCIdType()) {
28
Calling 'Type::isObjCIdType'
32
Returning from 'Type::isObjCIdType'
33
Taking false branch
4875 // Okay: we don't know what this type will instantiate to.
4876 } else if (!T->isObjCObjectPointerType()) {
34
Calling 'Type::isObjCObjectPointerType'
37
Returning from 'Type::isObjCObjectPointerType'
38
Taking false branch
4877 Invalid = true;
4878 Diag(IdLoc, diag::err_catch_param_not_objc_type);
4879 } else if (!T->getAs<ObjCObjectPointerType>()->getInterfaceType()) {
39
Assuming the object is not a 'ObjCObjectPointerType'
40
Called C++ object pointer is null
4880 Invalid = true;
4881 Diag(IdLoc, diag::err_catch_param_not_objc_type);
4882 }
4883
4884 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
4885 T, TInfo, SC_None);
4886 New->setExceptionVariable(true);
4887
4888 // In ARC, infer 'retaining' for variables of retainable type.
4889 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
4890 Invalid = true;
4891
4892 if (Invalid)
4893 New->setInvalidDecl();
4894 return New;
4895}
4896
4897Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
4898 const DeclSpec &DS = D.getDeclSpec();
4899
4900 // We allow the "register" storage class on exception variables because
4901 // GCC did, but we drop it completely. Any other storage class is an error.
4902 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1
Assuming the condition is false
2
Taking false branch
4903 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4904 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
4905 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3
Assuming 'SCS' is 0
4
Taking false branch
4906 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
4907 << DeclSpec::getSpecifierName(SCS);
4908 }
4909 if (DS.isInlineSpecified())
5
Assuming the condition is false
6
Taking false branch
4910 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4911 << getLangOpts().CPlusPlus17;
4912 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7
Assuming 'TSCS' is 0
8
Taking false branch
4913 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4914 diag::err_invalid_thread)
4915 << DeclSpec::getSpecifierName(TSCS);
4916 D.getMutableDeclSpec().ClearStorageClassSpecs();
4917
4918 DiagnoseFunctionSpecifiers(D.getDeclSpec());
4919
4920 // Check that there are no default arguments inside the type of this
4921 // exception object (C++ only).
4922 if (getLangOpts().CPlusPlus)
9
Assuming field 'CPlusPlus' is 0
10
Taking false branch
4923 CheckExtraCXXDefaultArguments(D);
4924
4925 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4926 QualType ExceptionType = TInfo->getType();
4927
4928 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
16
Calling 'Sema::BuildObjCExceptionDecl'
4929 D.getSourceRange().getBegin(),
4930 D.getIdentifierLoc(),
4931 D.getIdentifier(),
4932 D.isInvalidType());
11
Calling 'Declarator::isInvalidType'
15
Returning from 'Declarator::isInvalidType'
4933
4934 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4935 if (D.getCXXScopeSpec().isSet()) {
4936 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4937 << D.getCXXScopeSpec().getRange();
4938 New->setInvalidDecl();
4939 }
4940
4941 // Add the parameter declaration into this scope.
4942 S->AddDecl(New);
4943 if (D.getIdentifier())
4944 IdResolver.AddDecl(New);
4945
4946 ProcessDeclAttributes(S, New, D);
4947
4948 if (New->hasAttr<BlocksAttr>())
4949 Diag(New->getLocation(), diag::err_block_on_nonlocal);
4950 return New;
4951}
4952
4953/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4954/// initialization.
4955void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4956 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
4957 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
4958 Iv= Iv->getNextIvar()) {
4959 QualType QT = Context.getBaseElementType(Iv->getType());
4960 if (QT->isRecordType())
4961 Ivars.push_back(Iv);
4962 }
4963}
4964
4965void Sema::DiagnoseUseOfUnimplementedSelectors() {
4966 // Load referenced selectors from the external source.
4967 if (ExternalSource) {
4968 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4969 ExternalSource->ReadReferencedSelectors(Sels);
4970 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4971 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4972 }
4973
4974 // Warning will be issued only when selector table is
4975 // generated (which means there is at lease one implementation
4976 // in the TU). This is to match gcc's behavior.
4977 if (ReferencedSelectors.empty() ||
4978 !Context.AnyObjCImplementation())
4979 return;
4980 for (auto &SelectorAndLocation : ReferencedSelectors) {
4981 Selector Sel = SelectorAndLocation.first;
4982 SourceLocation Loc = SelectorAndLocation.second;
4983 if (!LookupImplementedMethodInGlobalPool(Sel))
4984 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
4985 }
4986}
4987
4988ObjCIvarDecl *
4989Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4990 const ObjCPropertyDecl *&PDecl) const {
4991 if (Method->isClassMethod())
4992 return nullptr;
4993 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4994 if (!IDecl)
4995 return nullptr;
4996 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4997 /*shallowCategoryLookup=*/false,
4998 /*followSuper=*/false);
4999 if (!Method || !Method->isPropertyAccessor())
5000 return nullptr;
5001 if ((PDecl = Method->findPropertyDecl()))
5002 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
5003 // property backing ivar must belong to property's class
5004 // or be a private ivar in class's implementation.
5005 // FIXME. fix the const-ness issue.
5006 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
5007 IV->getIdentifier());
5008 return IV;
5009 }
5010 return nullptr;
5011}
5012
5013namespace {
5014 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
5015 /// accessor references the backing ivar.
5016 class UnusedBackingIvarChecker :
5017 public RecursiveASTVisitor<UnusedBackingIvarChecker> {
5018 public:
5019 Sema &S;
5020 const ObjCMethodDecl *Method;
5021 const ObjCIvarDecl *IvarD;
5022 bool AccessedIvar;
5023 bool InvokedSelfMethod;
5024
5025 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
5026 const ObjCIvarDecl *IvarD)
5027 : S(S), Method(Method), IvarD(IvarD),
5028 AccessedIvar(false), InvokedSelfMethod(false) {
5029 assert(IvarD)((IvarD) ? static_cast<void> (0) : __assert_fail ("IvarD"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDeclObjC.cpp"
, 5029, __PRETTY_FUNCTION__))
;
5030 }
5031
5032 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
5033 if (E->getDecl() == IvarD) {
5034 AccessedIvar = true;
5035 return false;
5036 }
5037 return true;
5038 }
5039
5040 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
5041 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
5042 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
5043 InvokedSelfMethod = true;
5044 }
5045 return true;
5046 }
5047 };
5048} // end anonymous namespace
5049
5050void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
5051 const ObjCImplementationDecl *ImplD) {
5052 if (S->hasUnrecoverableErrorOccurred())
5053 return;
5054
5055 for (const auto *CurMethod : ImplD->instance_methods()) {
5056 unsigned DIAG = diag::warn_unused_property_backing_ivar;
5057 SourceLocation Loc = CurMethod->getLocation();
5058 if (Diags.isIgnored(DIAG, Loc))
5059 continue;
5060
5061 const ObjCPropertyDecl *PDecl;
5062 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
5063 if (!IV)
5064 continue;
5065
5066 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
5067 Checker.TraverseStmt(CurMethod->getBody());
5068 if (Checker.AccessedIvar)
5069 continue;
5070
5071 // Do not issue this warning if backing ivar is used somewhere and accessor
5072 // implementation makes a self call. This is to prevent false positive in
5073 // cases where the ivar is accessed by another method that the accessor
5074 // delegates to.
5075 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
5076 Diag(Loc, DIAG) << IV;
5077 Diag(PDecl->getLocation(), diag::note_property_declare);
5078 }
5079 }
5080}

/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h

1//===--- DeclSpec.h - Parsed declaration specifiers -------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file defines the classes used to store parsed information about
11/// declaration-specifiers and declarators.
12///
13/// \verbatim
14/// static const int volatile x, *y, *(*(*z)[10])(const void *x);
15/// ------------------------- - -- ---------------------------
16/// declaration-specifiers \ | /
17/// declarators
18/// \endverbatim
19///
20//===----------------------------------------------------------------------===//
21
22#ifndef LLVM_CLANG_SEMA_DECLSPEC_H
23#define LLVM_CLANG_SEMA_DECLSPEC_H
24
25#include "clang/AST/DeclCXX.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/Basic/ExceptionSpecificationType.h"
28#include "clang/Basic/Lambda.h"
29#include "clang/Basic/OperatorKinds.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Lex/Token.h"
32#include "clang/Sema/Ownership.h"
33#include "clang/Sema/ParsedAttr.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/ErrorHandling.h"
37
38namespace clang {
39 class ASTContext;
40 class CXXRecordDecl;
41 class TypeLoc;
42 class LangOptions;
43 class IdentifierInfo;
44 class NamespaceAliasDecl;
45 class NamespaceDecl;
46 class ObjCDeclSpec;
47 class Sema;
48 class Declarator;
49 struct TemplateIdAnnotation;
50
51/// Represents a C++ nested-name-specifier or a global scope specifier.
52///
53/// These can be in 3 states:
54/// 1) Not present, identified by isEmpty()
55/// 2) Present, identified by isNotEmpty()
56/// 2.a) Valid, identified by isValid()
57/// 2.b) Invalid, identified by isInvalid().
58///
59/// isSet() is deprecated because it mostly corresponded to "valid" but was
60/// often used as if it meant "present".
61///
62/// The actual scope is described by getScopeRep().
63class CXXScopeSpec {
64 SourceRange Range;
65 NestedNameSpecifierLocBuilder Builder;
66
67public:
68 SourceRange getRange() const { return Range; }
69 void setRange(SourceRange R) { Range = R; }
70 void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); }
71 void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); }
72 SourceLocation getBeginLoc() const { return Range.getBegin(); }
73 SourceLocation getEndLoc() const { return Range.getEnd(); }
74
75 /// Retrieve the representation of the nested-name-specifier.
76 NestedNameSpecifier *getScopeRep() const {
77 return Builder.getRepresentation();
78 }
79
80 /// Extend the current nested-name-specifier by another
81 /// nested-name-specifier component of the form 'type::'.
82 ///
83 /// \param Context The AST context in which this nested-name-specifier
84 /// resides.
85 ///
86 /// \param TemplateKWLoc The location of the 'template' keyword, if present.
87 ///
88 /// \param TL The TypeLoc that describes the type preceding the '::'.
89 ///
90 /// \param ColonColonLoc The location of the trailing '::'.
91 void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL,
92 SourceLocation ColonColonLoc);
93
94 /// Extend the current nested-name-specifier by another
95 /// nested-name-specifier component of the form 'identifier::'.
96 ///
97 /// \param Context The AST context in which this nested-name-specifier
98 /// resides.
99 ///
100 /// \param Identifier The identifier.
101 ///
102 /// \param IdentifierLoc The location of the identifier.
103 ///
104 /// \param ColonColonLoc The location of the trailing '::'.
105 void Extend(ASTContext &Context, IdentifierInfo *Identifier,
106 SourceLocation IdentifierLoc, SourceLocation ColonColonLoc);
107
108 /// Extend the current nested-name-specifier by another
109 /// nested-name-specifier component of the form 'namespace::'.
110 ///
111 /// \param Context The AST context in which this nested-name-specifier
112 /// resides.
113 ///
114 /// \param Namespace The namespace.
115 ///
116 /// \param NamespaceLoc The location of the namespace name.
117 ///
118 /// \param ColonColonLoc The location of the trailing '::'.
119 void Extend(ASTContext &Context, NamespaceDecl *Namespace,
120 SourceLocation NamespaceLoc, SourceLocation ColonColonLoc);
121
122 /// Extend the current nested-name-specifier by another
123 /// nested-name-specifier component of the form 'namespace-alias::'.
124 ///
125 /// \param Context The AST context in which this nested-name-specifier
126 /// resides.
127 ///
128 /// \param Alias The namespace alias.
129 ///
130 /// \param AliasLoc The location of the namespace alias
131 /// name.
132 ///
133 /// \param ColonColonLoc The location of the trailing '::'.
134 void Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
135 SourceLocation AliasLoc, SourceLocation ColonColonLoc);
136
137 /// Turn this (empty) nested-name-specifier into the global
138 /// nested-name-specifier '::'.
139 void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
140
141 /// Turns this (empty) nested-name-specifier into '__super'
142 /// nested-name-specifier.
143 ///
144 /// \param Context The AST context in which this nested-name-specifier
145 /// resides.
146 ///
147 /// \param RD The declaration of the class in which nested-name-specifier
148 /// appeared.
149 ///
150 /// \param SuperLoc The location of the '__super' keyword.
151 /// name.
152 ///
153 /// \param ColonColonLoc The location of the trailing '::'.
154 void MakeSuper(ASTContext &Context, CXXRecordDecl *RD,
155 SourceLocation SuperLoc, SourceLocation ColonColonLoc);
156
157 /// Make a new nested-name-specifier from incomplete source-location
158 /// information.
159 ///
160 /// FIXME: This routine should be used very, very rarely, in cases where we
161 /// need to synthesize a nested-name-specifier. Most code should instead use
162 /// \c Adopt() with a proper \c NestedNameSpecifierLoc.
163 void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier,
164 SourceRange R);
165
166 /// Adopt an existing nested-name-specifier (with source-range
167 /// information).
168 void Adopt(NestedNameSpecifierLoc Other);
169
170 /// Retrieve a nested-name-specifier with location information, copied
171 /// into the given AST context.
172 ///
173 /// \param Context The context into which this nested-name-specifier will be
174 /// copied.
175 NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const;
176
177 /// Retrieve the location of the name in the last qualifier
178 /// in this nested name specifier.
179 ///
180 /// For example, the location of \c bar
181 /// in
182 /// \verbatim
183 /// \::foo::bar<0>::
184 /// ^~~
185 /// \endverbatim
186 SourceLocation getLastQualifierNameLoc() const;
187
188 /// No scope specifier.
189 bool isEmpty() const { return !Range.isValid(); }
190 /// A scope specifier is present, but may be valid or invalid.
191 bool isNotEmpty() const { return !isEmpty(); }
192
193 /// An error occurred during parsing of the scope specifier.
194 bool isInvalid() const { return isNotEmpty() && getScopeRep() == nullptr; }
195 /// A scope specifier is present, and it refers to a real scope.
196 bool isValid() const { return isNotEmpty() && getScopeRep() != nullptr; }
197
198 /// Indicate that this nested-name-specifier is invalid.
199 void SetInvalid(SourceRange R) {
200 assert(R.isValid() && "Must have a valid source range")((R.isValid() && "Must have a valid source range") ? static_cast
<void> (0) : __assert_fail ("R.isValid() && \"Must have a valid source range\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 200, __PRETTY_FUNCTION__))
;
201 if (Range.getBegin().isInvalid())
202 Range.setBegin(R.getBegin());
203 Range.setEnd(R.getEnd());
204 Builder.Clear();
205 }
206
207 /// Deprecated. Some call sites intend isNotEmpty() while others intend
208 /// isValid().
209 bool isSet() const { return getScopeRep() != nullptr; }
210
211 void clear() {
212 Range = SourceRange();
213 Builder.Clear();
214 }
215
216 /// Retrieve the data associated with the source-location information.
217 char *location_data() const { return Builder.getBuffer().first; }
218
219 /// Retrieve the size of the data associated with source-location
220 /// information.
221 unsigned location_size() const { return Builder.getBuffer().second; }
222};
223
224/// Captures information about "declaration specifiers".
225///
226/// "Declaration specifiers" encompasses storage-class-specifiers,
227/// type-specifiers, type-qualifiers, and function-specifiers.
228class DeclSpec {
229public:
230 /// storage-class-specifier
231 /// \note The order of these enumerators is important for diagnostics.
232 enum SCS {
233 SCS_unspecified = 0,
234 SCS_typedef,
235 SCS_extern,
236 SCS_static,
237 SCS_auto,
238 SCS_register,
239 SCS_private_extern,
240 SCS_mutable
241 };
242
243 // Import thread storage class specifier enumeration and constants.
244 // These can be combined with SCS_extern and SCS_static.
245 typedef ThreadStorageClassSpecifier TSCS;
246 static const TSCS TSCS_unspecified = clang::TSCS_unspecified;
247 static const TSCS TSCS___thread = clang::TSCS___thread;
248 static const TSCS TSCS_thread_local = clang::TSCS_thread_local;
249 static const TSCS TSCS__Thread_local = clang::TSCS__Thread_local;
250
251 // Import type specifier width enumeration and constants.
252 typedef TypeSpecifierWidth TSW;
253 static const TSW TSW_unspecified = clang::TSW_unspecified;
254 static const TSW TSW_short = clang::TSW_short;
255 static const TSW TSW_long = clang::TSW_long;
256 static const TSW TSW_longlong = clang::TSW_longlong;
257
258 enum TSC {
259 TSC_unspecified,
260 TSC_imaginary,
261 TSC_complex
262 };
263
264 // Import type specifier sign enumeration and constants.
265 typedef TypeSpecifierSign TSS;
266 static const TSS TSS_unspecified = clang::TSS_unspecified;
267 static const TSS TSS_signed = clang::TSS_signed;
268 static const TSS TSS_unsigned = clang::TSS_unsigned;
269
270 // Import type specifier type enumeration and constants.
271 typedef TypeSpecifierType TST;
272 static const TST TST_unspecified = clang::TST_unspecified;
273 static const TST TST_void = clang::TST_void;
274 static const TST TST_char = clang::TST_char;
275 static const TST TST_wchar = clang::TST_wchar;
276 static const TST TST_char8 = clang::TST_char8;
277 static const TST TST_char16 = clang::TST_char16;
278 static const TST TST_char32 = clang::TST_char32;
279 static const TST TST_int = clang::TST_int;
280 static const TST TST_int128 = clang::TST_int128;
281 static const TST TST_half = clang::TST_half;
282 static const TST TST_float = clang::TST_float;
283 static const TST TST_double = clang::TST_double;
284 static const TST TST_float16 = clang::TST_Float16;
285 static const TST TST_accum = clang::TST_Accum;
286 static const TST TST_fract = clang::TST_Fract;
287 static const TST TST_float128 = clang::TST_float128;
288 static const TST TST_bool = clang::TST_bool;
289 static const TST TST_decimal32 = clang::TST_decimal32;
290 static const TST TST_decimal64 = clang::TST_decimal64;
291 static const TST TST_decimal128 = clang::TST_decimal128;
292 static const TST TST_enum = clang::TST_enum;
293 static const TST TST_union = clang::TST_union;
294 static const TST TST_struct = clang::TST_struct;
295 static const TST TST_interface = clang::TST_interface;
296 static const TST TST_class = clang::TST_class;
297 static const TST TST_typename = clang::TST_typename;
298 static const TST TST_typeofType = clang::TST_typeofType;
299 static const TST TST_typeofExpr = clang::TST_typeofExpr;
300 static const TST TST_decltype = clang::TST_decltype;
301 static const TST TST_decltype_auto = clang::TST_decltype_auto;
302 static const TST TST_underlyingType = clang::TST_underlyingType;
303 static const TST TST_auto = clang::TST_auto;
304 static const TST TST_auto_type = clang::TST_auto_type;
305 static const TST TST_unknown_anytype = clang::TST_unknown_anytype;
306 static const TST TST_atomic = clang::TST_atomic;
307#define GENERIC_IMAGE_TYPE(ImgType, Id) \
308 static const TST TST_##ImgType##_t = clang::TST_##ImgType##_t;
309#include "clang/Basic/OpenCLImageTypes.def"
310 static const TST TST_error = clang::TST_error;
311
312 // type-qualifiers
313 enum TQ { // NOTE: These flags must be kept in sync with Qualifiers::TQ.
314 TQ_unspecified = 0,
315 TQ_const = 1,
316 TQ_restrict = 2,
317 TQ_volatile = 4,
318 TQ_unaligned = 8,
319 // This has no corresponding Qualifiers::TQ value, because it's not treated
320 // as a qualifier in our type system.
321 TQ_atomic = 16
322 };
323
324 /// ParsedSpecifiers - Flags to query which specifiers were applied. This is
325 /// returned by getParsedSpecifiers.
326 enum ParsedSpecifiers {
327 PQ_None = 0,
328 PQ_StorageClassSpecifier = 1,
329 PQ_TypeSpecifier = 2,
330 PQ_TypeQualifier = 4,
331 PQ_FunctionSpecifier = 8
332 // FIXME: Attributes should be included here.
333 };
334
335private:
336 // storage-class-specifier
337 /*SCS*/unsigned StorageClassSpec : 3;
338 /*TSCS*/unsigned ThreadStorageClassSpec : 2;
339 unsigned SCS_extern_in_linkage_spec : 1;
340
341 // type-specifier
342 /*TSW*/unsigned TypeSpecWidth : 2;
343 /*TSC*/unsigned TypeSpecComplex : 2;
344 /*TSS*/unsigned TypeSpecSign : 2;
345 /*TST*/unsigned TypeSpecType : 6;
346 unsigned TypeAltiVecVector : 1;
347 unsigned TypeAltiVecPixel : 1;
348 unsigned TypeAltiVecBool : 1;
349 unsigned TypeSpecOwned : 1;
350 unsigned TypeSpecPipe : 1;
351 unsigned TypeSpecSat : 1;
352
353 // type-qualifiers
354 unsigned TypeQualifiers : 5; // Bitwise OR of TQ.
355
356 // function-specifier
357 unsigned FS_inline_specified : 1;
358 unsigned FS_forceinline_specified: 1;
359 unsigned FS_virtual_specified : 1;
360 unsigned FS_noreturn_specified : 1;
361
362 // friend-specifier
363 unsigned Friend_specified : 1;
364
365 // constexpr-specifier
366 unsigned ConstexprSpecifier : 2;
367
368 union {
369 UnionParsedType TypeRep;
370 Decl *DeclRep;
371 Expr *ExprRep;
372 };
373
374 /// ExplicitSpecifier - Store information about explicit spicifer.
375 ExplicitSpecifier FS_explicit_specifier;
376
377 // attributes.
378 ParsedAttributes Attrs;
379
380 // Scope specifier for the type spec, if applicable.
381 CXXScopeSpec TypeScope;
382
383 // SourceLocation info. These are null if the item wasn't specified or if
384 // the setting was synthesized.
385 SourceRange Range;
386
387 SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc;
388 SourceRange TSWRange;
389 SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc, TSSatLoc;
390 /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
391 /// typename, then this is the location of the named type (if present);
392 /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
393 /// TSTNameLoc provides source range info for tag types.
394 SourceLocation TSTNameLoc;
395 SourceRange TypeofParensRange;
396 SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc,
397 TQ_unalignedLoc;
398 SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc;
399 SourceLocation FS_explicitCloseParenLoc;
400 SourceLocation FS_forceinlineLoc;
401 SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc;
402 SourceLocation TQ_pipeLoc;
403
404 WrittenBuiltinSpecs writtenBS;
405 void SaveWrittenBuiltinSpecs();
406
407 ObjCDeclSpec *ObjCQualifiers;
408
409 static bool isTypeRep(TST T) {
410 return (T == TST_typename || T == TST_typeofType ||
411 T == TST_underlyingType || T == TST_atomic);
412 }
413 static bool isExprRep(TST T) {
414 return (T == TST_typeofExpr || T == TST_decltype);
415 }
416
417 DeclSpec(const DeclSpec &) = delete;
418 void operator=(const DeclSpec &) = delete;
419public:
420 static bool isDeclRep(TST T) {
421 return (T == TST_enum || T == TST_struct ||
422 T == TST_interface || T == TST_union ||
423 T == TST_class);
424 }
425
426 DeclSpec(AttributeFactory &attrFactory)
427 : StorageClassSpec(SCS_unspecified),
428 ThreadStorageClassSpec(TSCS_unspecified),
429 SCS_extern_in_linkage_spec(false), TypeSpecWidth(TSW_unspecified),
430 TypeSpecComplex(TSC_unspecified), TypeSpecSign(TSS_unspecified),
431 TypeSpecType(TST_unspecified), TypeAltiVecVector(false),
432 TypeAltiVecPixel(false), TypeAltiVecBool(false), TypeSpecOwned(false),
433 TypeSpecPipe(false), TypeSpecSat(false), TypeQualifiers(TQ_unspecified),
434 FS_inline_specified(false), FS_forceinline_specified(false),
435 FS_virtual_specified(false), FS_noreturn_specified(false),
436 Friend_specified(false), ConstexprSpecifier(CSK_unspecified),
437 FS_explicit_specifier(), Attrs(attrFactory), writtenBS(),
438 ObjCQualifiers(nullptr) {}
439
440 // storage-class-specifier
441 SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
442 TSCS getThreadStorageClassSpec() const {
443 return (TSCS)ThreadStorageClassSpec;
444 }
445 bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
446 void setExternInLinkageSpec(bool Value) {
447 SCS_extern_in_linkage_spec = Value;
448 }
449
450 SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
451 SourceLocation getThreadStorageClassSpecLoc() const {
452 return ThreadStorageClassSpecLoc;
453 }
454
455 void ClearStorageClassSpecs() {
456 StorageClassSpec = DeclSpec::SCS_unspecified;
457 ThreadStorageClassSpec = DeclSpec::TSCS_unspecified;
458 SCS_extern_in_linkage_spec = false;
459 StorageClassSpecLoc = SourceLocation();
460 ThreadStorageClassSpecLoc = SourceLocation();
461 }
462
463 void ClearTypeSpecType() {
464 TypeSpecType = DeclSpec::TST_unspecified;
465 TypeSpecOwned = false;
466 TSTLoc = SourceLocation();
467 }
468
469 // type-specifier
470 TSW getTypeSpecWidth() const { return (TSW)TypeSpecWidth; }
471 TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
472 TSS getTypeSpecSign() const { return (TSS)TypeSpecSign; }
473 TST getTypeSpecType() const { return (TST)TypeSpecType; }
474 bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
475 bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
476 bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
477 bool isTypeSpecOwned() const { return TypeSpecOwned; }
478 bool isTypeRep() const { return isTypeRep((TST) TypeSpecType); }
479 bool isTypeSpecPipe() const { return TypeSpecPipe; }
480 bool isTypeSpecSat() const { return TypeSpecSat; }
481
482 ParsedType getRepAsType() const {
483 assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type")((isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type"
) ? static_cast<void> (0) : __assert_fail ("isTypeRep((TST) TypeSpecType) && \"DeclSpec does not store a type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 483, __PRETTY_FUNCTION__))
;
484 return TypeRep;
485 }
486 Decl *getRepAsDecl() const {
487 assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl")((isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl"
) ? static_cast<void> (0) : __assert_fail ("isDeclRep((TST) TypeSpecType) && \"DeclSpec does not store a decl\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 487, __PRETTY_FUNCTION__))
;
488 return DeclRep;
489 }
490 Expr *getRepAsExpr() const {
491 assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr")((isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr"
) ? static_cast<void> (0) : __assert_fail ("isExprRep((TST) TypeSpecType) && \"DeclSpec does not store an expr\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 491, __PRETTY_FUNCTION__))
;
492 return ExprRep;
493 }
494 CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
495 const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
496
497 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
498 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
499 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
500
501 SourceLocation getTypeSpecWidthLoc() const { return TSWRange.getBegin(); }
502 SourceRange getTypeSpecWidthRange() const { return TSWRange; }
503 SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
504 SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
505 SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
506 SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
507 SourceLocation getTypeSpecSatLoc() const { return TSSatLoc; }
508
509 SourceLocation getTypeSpecTypeNameLoc() const {
510 assert(isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename)((isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename
) ? static_cast<void> (0) : __assert_fail ("isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 510, __PRETTY_FUNCTION__))
;
511 return TSTNameLoc;
512 }
513
514 SourceRange getTypeofParensRange() const { return TypeofParensRange; }
515 void setTypeofParensRange(SourceRange range) { TypeofParensRange = range; }
516
517 bool hasAutoTypeSpec() const {
518 return (TypeSpecType == TST_auto || TypeSpecType == TST_auto_type ||
519 TypeSpecType == TST_decltype_auto);
520 }
521
522 bool hasTagDefinition() const;
523
524 /// Turn a type-specifier-type into a string like "_Bool" or "union".
525 static const char *getSpecifierName(DeclSpec::TST T,
526 const PrintingPolicy &Policy);
527 static const char *getSpecifierName(DeclSpec::TQ Q);
528 static const char *getSpecifierName(DeclSpec::TSS S);
529 static const char *getSpecifierName(DeclSpec::TSC C);
530 static const char *getSpecifierName(DeclSpec::TSW W);
531 static const char *getSpecifierName(DeclSpec::SCS S);
532 static const char *getSpecifierName(DeclSpec::TSCS S);
533 static const char *getSpecifierName(ConstexprSpecKind C);
534
535 // type-qualifiers
536
537 /// getTypeQualifiers - Return a set of TQs.
538 unsigned getTypeQualifiers() const { return TypeQualifiers; }
539 SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
540 SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
541 SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
542 SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; }
543 SourceLocation getUnalignedSpecLoc() const { return TQ_unalignedLoc; }
544 SourceLocation getPipeLoc() const { return TQ_pipeLoc; }
545
546 /// Clear out all of the type qualifiers.
547 void ClearTypeQualifiers() {
548 TypeQualifiers = 0;
549 TQ_constLoc = SourceLocation();
550 TQ_restrictLoc = SourceLocation();
551 TQ_volatileLoc = SourceLocation();
552 TQ_atomicLoc = SourceLocation();
553 TQ_unalignedLoc = SourceLocation();
554 TQ_pipeLoc = SourceLocation();
555 }
556
557 // function-specifier
558 bool isInlineSpecified() const {
559 return FS_inline_specified | FS_forceinline_specified;
560 }
561 SourceLocation getInlineSpecLoc() const {
562 return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc;
563 }
564
565 ExplicitSpecifier getExplicitSpecifier() const {
566 return FS_explicit_specifier;
567 }
568
569 bool isVirtualSpecified() const { return FS_virtual_specified; }
570 SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
571
572 bool hasExplicitSpecifier() const {
573 return FS_explicit_specifier.isSpecified();
574 }
575 SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
576 SourceRange getExplicitSpecRange() const {
577 return FS_explicit_specifier.getExpr()
578 ? SourceRange(FS_explicitLoc, FS_explicitCloseParenLoc)
579 : SourceRange(FS_explicitLoc);
580 }
581
582 bool isNoreturnSpecified() const { return FS_noreturn_specified; }
583 SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; }
584
585 void ClearFunctionSpecs() {
586 FS_inline_specified = false;
587 FS_inlineLoc = SourceLocation();
588 FS_forceinline_specified = false;
589 FS_forceinlineLoc = SourceLocation();
590 FS_virtual_specified = false;
591 FS_virtualLoc = SourceLocation();
592 FS_explicit_specifier = ExplicitSpecifier();
593 FS_explicitLoc = SourceLocation();
594 FS_explicitCloseParenLoc = SourceLocation();
595 FS_noreturn_specified = false;
596 FS_noreturnLoc = SourceLocation();
597 }
598
599 /// This method calls the passed in handler on each CVRU qual being
600 /// set.
601 /// Handle - a handler to be invoked.
602 void forEachCVRUQualifier(
603 llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
604
605 /// This method calls the passed in handler on each qual being
606 /// set.
607 /// Handle - a handler to be invoked.
608 void forEachQualifier(
609 llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
610
611 /// Return true if any type-specifier has been found.
612 bool hasTypeSpecifier() const {
613 return getTypeSpecType() != DeclSpec::TST_unspecified ||
614 getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
615 getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
616 getTypeSpecSign() != DeclSpec::TSS_unspecified;
617 }
618
619 /// Return a bitmask of which flavors of specifiers this
620 /// DeclSpec includes.
621 unsigned getParsedSpecifiers() const;
622
623 /// isEmpty - Return true if this declaration specifier is completely empty:
624 /// no tokens were parsed in the production of it.
625 bool isEmpty() const {
626 return getParsedSpecifiers() == DeclSpec::PQ_None;
627 }
628
629 void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
630 void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
631
632 /// These methods set the specified attribute of the DeclSpec and
633 /// return false if there was no error. If an error occurs (for
634 /// example, if we tried to set "auto" on a spec with "extern"
635 /// already set), they return true and set PrevSpec and DiagID
636 /// such that
637 /// Diag(Loc, DiagID) << PrevSpec;
638 /// will yield a useful result.
639 ///
640 /// TODO: use a more general approach that still allows these
641 /// diagnostics to be ignored when desired.
642 bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
643 const char *&PrevSpec, unsigned &DiagID,
644 const PrintingPolicy &Policy);
645 bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
646 const char *&PrevSpec, unsigned &DiagID);
647 bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec,
648 unsigned &DiagID, const PrintingPolicy &Policy);
649 bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
650 unsigned &DiagID);
651 bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec,
652 unsigned &DiagID);
653 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
654 unsigned &DiagID, const PrintingPolicy &Policy);
655 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
656 unsigned &DiagID, ParsedType Rep,
657 const PrintingPolicy &Policy);
658 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
659 unsigned &DiagID, Decl *Rep, bool Owned,
660 const PrintingPolicy &Policy);
661 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
662 SourceLocation TagNameLoc, const char *&PrevSpec,
663 unsigned &DiagID, ParsedType Rep,
664 const PrintingPolicy &Policy);
665 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
666 SourceLocation TagNameLoc, const char *&PrevSpec,
667 unsigned &DiagID, Decl *Rep, bool Owned,
668 const PrintingPolicy &Policy);
669
670 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
671 unsigned &DiagID, Expr *Rep,
672 const PrintingPolicy &policy);
673 bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
674 const char *&PrevSpec, unsigned &DiagID,
675 const PrintingPolicy &Policy);
676 bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
677 const char *&PrevSpec, unsigned &DiagID,
678 const PrintingPolicy &Policy);
679 bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
680 const char *&PrevSpec, unsigned &DiagID,
681 const PrintingPolicy &Policy);
682 bool SetTypePipe(bool isPipe, SourceLocation Loc,
683 const char *&PrevSpec, unsigned &DiagID,
684 const PrintingPolicy &Policy);
685 bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec,
686 unsigned &DiagID);
687 bool SetTypeSpecError();
688 void UpdateDeclRep(Decl *Rep) {
689 assert(isDeclRep((TST) TypeSpecType))((isDeclRep((TST) TypeSpecType)) ? static_cast<void> (0
) : __assert_fail ("isDeclRep((TST) TypeSpecType)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 689, __PRETTY_FUNCTION__))
;
690 DeclRep = Rep;
691 }
692 void UpdateTypeRep(ParsedType Rep) {
693 assert(isTypeRep((TST) TypeSpecType))((isTypeRep((TST) TypeSpecType)) ? static_cast<void> (0
) : __assert_fail ("isTypeRep((TST) TypeSpecType)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 693, __PRETTY_FUNCTION__))
;
694 TypeRep = Rep;
695 }
696 void UpdateExprRep(Expr *Rep) {
697 assert(isExprRep((TST) TypeSpecType))((isExprRep((TST) TypeSpecType)) ? static_cast<void> (0
) : __assert_fail ("isExprRep((TST) TypeSpecType)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 697, __PRETTY_FUNCTION__))
;
698 ExprRep = Rep;
699 }
700
701 bool SetTypeQual(TQ T, SourceLocation Loc);
702
703 bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
704 unsigned &DiagID, const LangOptions &Lang);
705
706 bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
707 unsigned &DiagID);
708 bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
709 unsigned &DiagID);
710 bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
711 unsigned &DiagID);
712 bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
713 unsigned &DiagID, ExplicitSpecifier ExplicitSpec,
714 SourceLocation CloseParenLoc);
715 bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec,
716 unsigned &DiagID);
717
718 bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
719 unsigned &DiagID);
720 bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
721 unsigned &DiagID);
722 bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc,
723 const char *&PrevSpec, unsigned &DiagID);
724
725 bool isFriendSpecified() const { return Friend_specified; }
726 SourceLocation getFriendSpecLoc() const { return FriendLoc; }
727
728 bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
729 SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
730
731 ConstexprSpecKind getConstexprSpecifier() const {
732 return ConstexprSpecKind(ConstexprSpecifier);
733 }
734
735 SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
736 bool hasConstexprSpecifier() const {
737 return ConstexprSpecifier != CSK_unspecified;
738 }
739
740 void ClearConstexprSpec() {
741 ConstexprSpecifier = CSK_unspecified;
742 ConstexprLoc = SourceLocation();
743 }
744
745 AttributePool &getAttributePool() const {
746 return Attrs.getPool();
747 }
748
749 /// Concatenates two attribute lists.
750 ///
751 /// The GCC attribute syntax allows for the following:
752 ///
753 /// \code
754 /// short __attribute__(( unused, deprecated ))
755 /// int __attribute__(( may_alias, aligned(16) )) var;
756 /// \endcode
757 ///
758 /// This declares 4 attributes using 2 lists. The following syntax is
759 /// also allowed and equivalent to the previous declaration.
760 ///
761 /// \code
762 /// short __attribute__((unused)) __attribute__((deprecated))
763 /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
764 /// \endcode
765 ///
766 void addAttributes(ParsedAttributesView &AL) {
767 Attrs.addAll(AL.begin(), AL.end());
768 }
769
770 bool hasAttributes() const { return !Attrs.empty(); }
771
772 ParsedAttributes &getAttributes() { return Attrs; }
773 const ParsedAttributes &getAttributes() const { return Attrs; }
774
775 void takeAttributesFrom(ParsedAttributes &attrs) {
776 Attrs.takeAllFrom(attrs);
777 }
778
779 /// Finish - This does final analysis of the declspec, issuing diagnostics for
780 /// things like "_Imaginary" (lacking an FP type). After calling this method,
781 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
782 void Finish(Sema &S, const PrintingPolicy &Policy);
783
784 const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
785 return writtenBS;
786 }
787
788 ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
789 void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
790
791 /// Checks if this DeclSpec can stand alone, without a Declarator.
792 ///
793 /// Only tag declspecs can stand alone.
794 bool isMissingDeclaratorOk();
795};
796
797/// Captures information about "declaration specifiers" specific to
798/// Objective-C.
799class ObjCDeclSpec {
800public:
801 /// ObjCDeclQualifier - Qualifier used on types in method
802 /// declarations. Not all combinations are sensible. Parameters
803 /// can be one of { in, out, inout } with one of { bycopy, byref }.
804 /// Returns can either be { oneway } or not.
805 ///
806 /// This should be kept in sync with Decl::ObjCDeclQualifier.
807 enum ObjCDeclQualifier {
808 DQ_None = 0x0,
809 DQ_In = 0x1,
810 DQ_Inout = 0x2,
811 DQ_Out = 0x4,
812 DQ_Bycopy = 0x8,
813 DQ_Byref = 0x10,
814 DQ_Oneway = 0x20,
815 DQ_CSNullability = 0x40
816 };
817
818 /// PropertyAttributeKind - list of property attributes.
819 /// Keep this list in sync with LLVM's Dwarf.h ApplePropertyAttributes.
820 enum ObjCPropertyAttributeKind {
821 DQ_PR_noattr = 0x0,
822 DQ_PR_readonly = 0x01,
823 DQ_PR_getter = 0x02,
824 DQ_PR_assign = 0x04,
825 DQ_PR_readwrite = 0x08,
826 DQ_PR_retain = 0x10,
827 DQ_PR_copy = 0x20,
828 DQ_PR_nonatomic = 0x40,
829 DQ_PR_setter = 0x80,
830 DQ_PR_atomic = 0x100,
831 DQ_PR_weak = 0x200,
832 DQ_PR_strong = 0x400,
833 DQ_PR_unsafe_unretained = 0x800,
834 DQ_PR_nullability = 0x1000,
835 DQ_PR_null_resettable = 0x2000,
836 DQ_PR_class = 0x4000
837 };
838
839 ObjCDeclSpec()
840 : objcDeclQualifier(DQ_None), PropertyAttributes(DQ_PR_noattr),
841 Nullability(0), GetterName(nullptr), SetterName(nullptr) { }
842
843 ObjCDeclQualifier getObjCDeclQualifier() const {
844 return (ObjCDeclQualifier)objcDeclQualifier;
845 }
846 void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
847 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
848 }
849 void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) {
850 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal);
851 }
852
853 ObjCPropertyAttributeKind getPropertyAttributes() const {
854 return ObjCPropertyAttributeKind(PropertyAttributes);
855 }
856 void setPropertyAttributes(ObjCPropertyAttributeKind PRVal) {
857 PropertyAttributes =
858 (ObjCPropertyAttributeKind)(PropertyAttributes | PRVal);
859 }
860
861 NullabilityKind getNullability() const {
862 assert(((getObjCDeclQualifier() & DQ_CSNullability) ||((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & DQ_PR_nullability)) && "Objective-C declspec doesn't have nullability"
) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 864, __PRETTY_FUNCTION__))
863 (getPropertyAttributes() & DQ_PR_nullability)) &&((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & DQ_PR_nullability)) && "Objective-C declspec doesn't have nullability"
) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 864, __PRETTY_FUNCTION__))
864 "Objective-C declspec doesn't have nullability")((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & DQ_PR_nullability)) && "Objective-C declspec doesn't have nullability"
) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 864, __PRETTY_FUNCTION__))
;
865 return static_cast<NullabilityKind>(Nullability);
866 }
867
868 SourceLocation getNullabilityLoc() const {
869 assert(((getObjCDeclQualifier() & DQ_CSNullability) ||((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & DQ_PR_nullability)) && "Objective-C declspec doesn't have nullability"
) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 871, __PRETTY_FUNCTION__))
870 (getPropertyAttributes() & DQ_PR_nullability)) &&((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & DQ_PR_nullability)) && "Objective-C declspec doesn't have nullability"
) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 871, __PRETTY_FUNCTION__))
871 "Objective-C declspec doesn't have nullability")((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & DQ_PR_nullability)) && "Objective-C declspec doesn't have nullability"
) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 871, __PRETTY_FUNCTION__))
;
872 return NullabilityLoc;
873 }
874
875 void setNullability(SourceLocation loc, NullabilityKind kind) {
876 assert(((getObjCDeclQualifier() & DQ_CSNullability) ||((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & DQ_PR_nullability)) && "Set the nullability declspec or property attribute first"
) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Set the nullability declspec or property attribute first\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 878, __PRETTY_FUNCTION__))
877 (getPropertyAttributes() & DQ_PR_nullability)) &&((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & DQ_PR_nullability)) && "Set the nullability declspec or property attribute first"
) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Set the nullability declspec or property attribute first\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 878, __PRETTY_FUNCTION__))
878 "Set the nullability declspec or property attribute first")((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & DQ_PR_nullability)) && "Set the nullability declspec or property attribute first"
) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Set the nullability declspec or property attribute first\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 878, __PRETTY_FUNCTION__))
;
879 Nullability = static_cast<unsigned>(kind);
880 NullabilityLoc = loc;
881 }
882
883 const IdentifierInfo *getGetterName() const { return GetterName; }
884 IdentifierInfo *getGetterName() { return GetterName; }
885 SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
886 void setGetterName(IdentifierInfo *name, SourceLocation loc) {
887 GetterName = name;
888 GetterNameLoc = loc;
889 }
890
891 const IdentifierInfo *getSetterName() const { return SetterName; }
892 IdentifierInfo *getSetterName() { return SetterName; }
893 SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
894 void setSetterName(IdentifierInfo *name, SourceLocation loc) {
895 SetterName = name;
896 SetterNameLoc = loc;
897 }
898
899private:
900 // FIXME: These two are unrelated and mutually exclusive. So perhaps
901 // we can put them in a union to reflect their mutual exclusivity
902 // (space saving is negligible).
903 unsigned objcDeclQualifier : 7;
904
905 // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind
906 unsigned PropertyAttributes : 15;
907
908 unsigned Nullability : 2;
909
910 SourceLocation NullabilityLoc;
911
912 IdentifierInfo *GetterName; // getter name or NULL if no getter
913 IdentifierInfo *SetterName; // setter name or NULL if no setter
914 SourceLocation GetterNameLoc; // location of the getter attribute's value
915 SourceLocation SetterNameLoc; // location of the setter attribute's value
916
917};
918
919/// Describes the kind of unqualified-id parsed.
920enum class UnqualifiedIdKind {
921 /// An identifier.
922 IK_Identifier,
923 /// An overloaded operator name, e.g., operator+.
924 IK_OperatorFunctionId,
925 /// A conversion function name, e.g., operator int.
926 IK_ConversionFunctionId,
927 /// A user-defined literal name, e.g., operator "" _i.
928 IK_LiteralOperatorId,
929 /// A constructor name.
930 IK_ConstructorName,
931 /// A constructor named via a template-id.
932 IK_ConstructorTemplateId,
933 /// A destructor name.
934 IK_DestructorName,
935 /// A template-id, e.g., f<int>.
936 IK_TemplateId,
937 /// An implicit 'self' parameter
938 IK_ImplicitSelfParam,
939 /// A deduction-guide name (a template-name)
940 IK_DeductionGuideName
941};
942
943/// Represents a C++ unqualified-id that has been parsed.
944class UnqualifiedId {
945private:
946 UnqualifiedId(const UnqualifiedId &Other) = delete;
947 const UnqualifiedId &operator=(const UnqualifiedId &) = delete;
948
949public:
950 /// Describes the kind of unqualified-id parsed.
951 UnqualifiedIdKind Kind;
952
953 struct OFI {
954 /// The kind of overloaded operator.
955 OverloadedOperatorKind Operator;
956
957 /// The source locations of the individual tokens that name
958 /// the operator, e.g., the "new", "[", and "]" tokens in
959 /// operator new [].
960 ///
961 /// Different operators have different numbers of tokens in their name,
962 /// up to three. Any remaining source locations in this array will be
963 /// set to an invalid value for operators with fewer than three tokens.
964 unsigned SymbolLocations[3];
965 };
966
967 /// Anonymous union that holds extra data associated with the
968 /// parsed unqualified-id.
969 union {
970 /// When Kind == IK_Identifier, the parsed identifier, or when
971 /// Kind == IK_UserLiteralId, the identifier suffix.
972 IdentifierInfo *Identifier;
973
974 /// When Kind == IK_OperatorFunctionId, the overloaded operator
975 /// that we parsed.
976 struct OFI OperatorFunctionId;
977
978 /// When Kind == IK_ConversionFunctionId, the type that the
979 /// conversion function names.
980 UnionParsedType ConversionFunctionId;
981
982 /// When Kind == IK_ConstructorName, the class-name of the type
983 /// whose constructor is being referenced.
984 UnionParsedType ConstructorName;
985
986 /// When Kind == IK_DestructorName, the type referred to by the
987 /// class-name.
988 UnionParsedType DestructorName;
989
990 /// When Kind == IK_DeductionGuideName, the parsed template-name.
991 UnionParsedTemplateTy TemplateName;
992
993 /// When Kind == IK_TemplateId or IK_ConstructorTemplateId,
994 /// the template-id annotation that contains the template name and
995 /// template arguments.
996 TemplateIdAnnotation *TemplateId;
997 };
998
999 /// The location of the first token that describes this unqualified-id,
1000 /// which will be the location of the identifier, "operator" keyword,
1001 /// tilde (for a destructor), or the template name of a template-id.
1002 SourceLocation StartLocation;
1003
1004 /// The location of the last token that describes this unqualified-id.
1005 SourceLocation EndLocation;
1006
1007 UnqualifiedId()
1008 : Kind(UnqualifiedIdKind::IK_Identifier), Identifier(nullptr) {}
1009
1010 /// Clear out this unqualified-id, setting it to default (invalid)
1011 /// state.
1012 void clear() {
1013 Kind = UnqualifiedIdKind::IK_Identifier;
1014 Identifier = nullptr;
1015 StartLocation = SourceLocation();
1016 EndLocation = SourceLocation();
1017 }
1018
1019 /// Determine whether this unqualified-id refers to a valid name.
1020 bool isValid() const { return StartLocation.isValid(); }
1021
1022 /// Determine whether this unqualified-id refers to an invalid name.
1023 bool isInvalid() const { return !isValid(); }
1024
1025 /// Determine what kind of name we have.
1026 UnqualifiedIdKind getKind() const { return Kind; }
1027 void setKind(UnqualifiedIdKind kind) { Kind = kind; }
1028
1029 /// Specify that this unqualified-id was parsed as an identifier.
1030 ///
1031 /// \param Id the parsed identifier.
1032 /// \param IdLoc the location of the parsed identifier.
1033 void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
1034 Kind = UnqualifiedIdKind::IK_Identifier;
1035 Identifier = const_cast<IdentifierInfo *>(Id);
1036 StartLocation = EndLocation = IdLoc;
1037 }
1038
1039 /// Specify that this unqualified-id was parsed as an
1040 /// operator-function-id.
1041 ///
1042 /// \param OperatorLoc the location of the 'operator' keyword.
1043 ///
1044 /// \param Op the overloaded operator.
1045 ///
1046 /// \param SymbolLocations the locations of the individual operator symbols
1047 /// in the operator.
1048 void setOperatorFunctionId(SourceLocation OperatorLoc,
1049 OverloadedOperatorKind Op,
1050 SourceLocation SymbolLocations[3]);
1051
1052 /// Specify that this unqualified-id was parsed as a
1053 /// conversion-function-id.
1054 ///
1055 /// \param OperatorLoc the location of the 'operator' keyword.
1056 ///
1057 /// \param Ty the type to which this conversion function is converting.
1058 ///
1059 /// \param EndLoc the location of the last token that makes up the type name.
1060 void setConversionFunctionId(SourceLocation OperatorLoc,
1061 ParsedType Ty,
1062 SourceLocation EndLoc) {
1063 Kind = UnqualifiedIdKind::IK_ConversionFunctionId;
1064 StartLocation = OperatorLoc;
1065 EndLocation = EndLoc;
1066 ConversionFunctionId = Ty;
1067 }
1068
1069 /// Specific that this unqualified-id was parsed as a
1070 /// literal-operator-id.
1071 ///
1072 /// \param Id the parsed identifier.
1073 ///
1074 /// \param OpLoc the location of the 'operator' keyword.
1075 ///
1076 /// \param IdLoc the location of the identifier.
1077 void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
1078 SourceLocation IdLoc) {
1079 Kind = UnqualifiedIdKind::IK_LiteralOperatorId;
1080 Identifier = const_cast<IdentifierInfo *>(Id);
1081 StartLocation = OpLoc;
1082 EndLocation = IdLoc;
1083 }
1084
1085 /// Specify that this unqualified-id was parsed as a constructor name.
1086 ///
1087 /// \param ClassType the class type referred to by the constructor name.
1088 ///
1089 /// \param ClassNameLoc the location of the class name.
1090 ///
1091 /// \param EndLoc the location of the last token that makes up the type name.
1092 void setConstructorName(ParsedType ClassType,
1093 SourceLocation ClassNameLoc,
1094 SourceLocation EndLoc) {
1095 Kind = UnqualifiedIdKind::IK_ConstructorName;
1096 StartLocation = ClassNameLoc;
1097 EndLocation = EndLoc;
1098 ConstructorName = ClassType;
1099 }
1100
1101 /// Specify that this unqualified-id was parsed as a
1102 /// template-id that names a constructor.
1103 ///
1104 /// \param TemplateId the template-id annotation that describes the parsed
1105 /// template-id. This UnqualifiedId instance will take ownership of the
1106 /// \p TemplateId and will free it on destruction.
1107 void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
1108
1109 /// Specify that this unqualified-id was parsed as a destructor name.
1110 ///
1111 /// \param TildeLoc the location of the '~' that introduces the destructor
1112 /// name.
1113 ///
1114 /// \param ClassType the name of the class referred to by the destructor name.
1115 void setDestructorName(SourceLocation TildeLoc,
1116 ParsedType ClassType,
1117 SourceLocation EndLoc) {
1118 Kind = UnqualifiedIdKind::IK_DestructorName;
1119 StartLocation = TildeLoc;
1120 EndLocation = EndLoc;
1121 DestructorName = ClassType;
1122 }
1123
1124 /// Specify that this unqualified-id was parsed as a template-id.
1125 ///
1126 /// \param TemplateId the template-id annotation that describes the parsed
1127 /// template-id. This UnqualifiedId instance will take ownership of the
1128 /// \p TemplateId and will free it on destruction.
1129 void setTemplateId(TemplateIdAnnotation *TemplateId);
1130
1131 /// Specify that this unqualified-id was parsed as a template-name for
1132 /// a deduction-guide.
1133 ///
1134 /// \param Template The parsed template-name.
1135 /// \param TemplateLoc The location of the parsed template-name.
1136 void setDeductionGuideName(ParsedTemplateTy Template,
1137 SourceLocation TemplateLoc) {
1138 Kind = UnqualifiedIdKind::IK_DeductionGuideName;
1139 TemplateName = Template;
1140 StartLocation = EndLocation = TemplateLoc;
1141 }
1142
1143 /// Return the source range that covers this unqualified-id.
1144 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
1145 return SourceRange(StartLocation, EndLocation);
1146 }
1147 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return StartLocation; }
1148 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return EndLocation; }
1149};
1150
1151/// A set of tokens that has been cached for later parsing.
1152typedef SmallVector<Token, 4> CachedTokens;
1153
1154/// One instance of this struct is used for each type in a
1155/// declarator that is parsed.
1156///
1157/// This is intended to be a small value object.
1158struct DeclaratorChunk {
1159 enum {
1160 Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe
1161 } Kind;
1162
1163 /// Loc - The place where this type was defined.
1164 SourceLocation Loc;
1165 /// EndLoc - If valid, the place where this chunck ends.
1166 SourceLocation EndLoc;
1167
1168 SourceRange getSourceRange() const {
1169 if (EndLoc.isInvalid())
1170 return SourceRange(Loc, Loc);
1171 return SourceRange(Loc, EndLoc);
1172 }
1173
1174 ParsedAttributesView AttrList;
1175
1176 struct PointerTypeInfo {
1177 /// The type qualifiers: const/volatile/restrict/unaligned/atomic.
1178 unsigned TypeQuals : 5;
1179
1180 /// The location of the const-qualifier, if any.
1181 unsigned ConstQualLoc;
1182
1183 /// The location of the volatile-qualifier, if any.
1184 unsigned VolatileQualLoc;
1185
1186 /// The location of the restrict-qualifier, if any.
1187 unsigned RestrictQualLoc;
1188
1189 /// The location of the _Atomic-qualifier, if any.
1190 unsigned AtomicQualLoc;
1191
1192 /// The location of the __unaligned-qualifier, if any.
1193 unsigned UnalignedQualLoc;
1194
1195 void destroy() {
1196 }
1197 };
1198
1199 struct ReferenceTypeInfo {
1200 /// The type qualifier: restrict. [GNU] C++ extension
1201 bool HasRestrict : 1;
1202 /// True if this is an lvalue reference, false if it's an rvalue reference.
1203 bool LValueRef : 1;
1204 void destroy() {
1205 }
1206 };
1207
1208 struct ArrayTypeInfo {
1209 /// The type qualifiers for the array:
1210 /// const/volatile/restrict/__unaligned/_Atomic.
1211 unsigned TypeQuals : 5;
1212
1213 /// True if this dimension included the 'static' keyword.
1214 unsigned hasStatic : 1;
1215
1216 /// True if this dimension was [*]. In this case, NumElts is null.
1217 unsigned isStar : 1;
1218
1219 /// This is the size of the array, or null if [] or [*] was specified.
1220 /// Since the parser is multi-purpose, and we don't want to impose a root
1221 /// expression class on all clients, NumElts is untyped.
1222 Expr *NumElts;
1223
1224 void destroy() {}
1225 };
1226
1227 /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1228 /// declarator is parsed. There are two interesting styles of parameters
1229 /// here:
1230 /// K&R-style identifier lists and parameter type lists. K&R-style identifier
1231 /// lists will have information about the identifier, but no type information.
1232 /// Parameter type lists will have type info (if the actions module provides
1233 /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1234 struct ParamInfo {
1235 IdentifierInfo *Ident;
1236 SourceLocation IdentLoc;
1237 Decl *Param;
1238
1239 /// DefaultArgTokens - When the parameter's default argument
1240 /// cannot be parsed immediately (because it occurs within the
1241 /// declaration of a member function), it will be stored here as a
1242 /// sequence of tokens to be parsed once the class definition is
1243 /// complete. Non-NULL indicates that there is a default argument.
1244 std::unique_ptr<CachedTokens> DefaultArgTokens;
1245
1246 ParamInfo() = default;
1247 ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
1248 Decl *param,
1249 std::unique_ptr<CachedTokens> DefArgTokens = nullptr)
1250 : Ident(ident), IdentLoc(iloc), Param(param),
1251 DefaultArgTokens(std::move(DefArgTokens)) {}
1252 };
1253
1254 struct TypeAndRange {
1255 ParsedType Ty;
1256 SourceRange Range;
1257 };
1258
1259 struct FunctionTypeInfo {
1260 /// hasPrototype - This is true if the function had at least one typed
1261 /// parameter. If the function is () or (a,b,c), then it has no prototype,
1262 /// and is treated as a K&R-style function.
1263 unsigned hasPrototype : 1;
1264
1265 /// isVariadic - If this function has a prototype, and if that
1266 /// proto ends with ',...)', this is true. When true, EllipsisLoc
1267 /// contains the location of the ellipsis.
1268 unsigned isVariadic : 1;
1269
1270 /// Can this declaration be a constructor-style initializer?
1271 unsigned isAmbiguous : 1;
1272
1273 /// Whether the ref-qualifier (if any) is an lvalue reference.
1274 /// Otherwise, it's an rvalue reference.
1275 unsigned RefQualifierIsLValueRef : 1;
1276
1277 /// ExceptionSpecType - An ExceptionSpecificationType value.
1278 unsigned ExceptionSpecType : 4;
1279
1280 /// DeleteParams - If this is true, we need to delete[] Params.
1281 unsigned DeleteParams : 1;
1282
1283 /// HasTrailingReturnType - If this is true, a trailing return type was
1284 /// specified.
1285 unsigned HasTrailingReturnType : 1;
1286
1287 /// The location of the left parenthesis in the source.
1288 unsigned LParenLoc;
1289
1290 /// When isVariadic is true, the location of the ellipsis in the source.
1291 unsigned EllipsisLoc;
1292
1293 /// The location of the right parenthesis in the source.
1294 unsigned RParenLoc;
1295
1296 /// NumParams - This is the number of formal parameters specified by the
1297 /// declarator.
1298 unsigned NumParams;
1299
1300 /// NumExceptionsOrDecls - This is the number of types in the
1301 /// dynamic-exception-decl, if the function has one. In C, this is the
1302 /// number of declarations in the function prototype.
1303 unsigned NumExceptionsOrDecls;
1304
1305 /// The location of the ref-qualifier, if any.
1306 ///
1307 /// If this is an invalid location, there is no ref-qualifier.
1308 unsigned RefQualifierLoc;
1309
1310 /// The location of the 'mutable' qualifer in a lambda-declarator, if
1311 /// any.
1312 unsigned MutableLoc;
1313
1314 /// The beginning location of the exception specification, if any.
1315 unsigned ExceptionSpecLocBeg;
1316
1317 /// The end location of the exception specification, if any.
1318 unsigned ExceptionSpecLocEnd;
1319
1320 /// Params - This is a pointer to a new[]'d array of ParamInfo objects that
1321 /// describe the parameters specified by this function declarator. null if
1322 /// there are no parameters specified.
1323 ParamInfo *Params;
1324
1325 /// DeclSpec for the function with the qualifier related info.
1326 DeclSpec *MethodQualifiers;
1327
1328 /// AtttibuteFactory for the MethodQualifiers.
1329 AttributeFactory *QualAttrFactory;
1330
1331 union {
1332 /// Pointer to a new[]'d array of TypeAndRange objects that
1333 /// contain the types in the function's dynamic exception specification
1334 /// and their locations, if there is one.
1335 TypeAndRange *Exceptions;
1336
1337 /// Pointer to the expression in the noexcept-specifier of this
1338 /// function, if it has one.
1339 Expr *NoexceptExpr;
1340
1341 /// Pointer to the cached tokens for an exception-specification
1342 /// that has not yet been parsed.
1343 CachedTokens *ExceptionSpecTokens;
1344
1345 /// Pointer to a new[]'d array of declarations that need to be available
1346 /// for lookup inside the function body, if one exists. Does not exist in
1347 /// C++.
1348 NamedDecl **DeclsInPrototype;
1349 };
1350
1351 /// If HasTrailingReturnType is true, this is the trailing return
1352 /// type specified.
1353 UnionParsedType TrailingReturnType;
1354
1355 /// Reset the parameter list to having zero parameters.
1356 ///
1357 /// This is used in various places for error recovery.
1358 void freeParams() {
1359 for (unsigned I = 0; I < NumParams; ++I)
1360 Params[I].DefaultArgTokens.reset();
1361 if (DeleteParams) {
1362 delete[] Params;
1363 DeleteParams = false;
1364 }
1365 NumParams = 0;
1366 }
1367
1368 void destroy() {
1369 freeParams();
1370 delete QualAttrFactory;
1371 delete MethodQualifiers;
1372 switch (getExceptionSpecType()) {
1373 default:
1374 break;
1375 case EST_Dynamic:
1376 delete[] Exceptions;
1377 break;
1378 case EST_Unparsed:
1379 delete ExceptionSpecTokens;
1380 break;
1381 case EST_None:
1382 if (NumExceptionsOrDecls != 0)
1383 delete[] DeclsInPrototype;
1384 break;
1385 }
1386 }
1387
1388 DeclSpec &getOrCreateMethodQualifiers() {
1389 if (!MethodQualifiers) {
1390 QualAttrFactory = new AttributeFactory();
1391 MethodQualifiers = new DeclSpec(*QualAttrFactory);
1392 }
1393 return *MethodQualifiers;
1394 }
1395
1396 /// isKNRPrototype - Return true if this is a K&R style identifier list,
1397 /// like "void foo(a,b,c)". In a function definition, this will be followed
1398 /// by the parameter type definitions.
1399 bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
1400
1401 SourceLocation getLParenLoc() const {
1402 return SourceLocation::getFromRawEncoding(LParenLoc);
1403 }
1404
1405 SourceLocation getEllipsisLoc() const {
1406 return SourceLocation::getFromRawEncoding(EllipsisLoc);
1407 }
1408
1409 SourceLocation getRParenLoc() const {
1410 return SourceLocation::getFromRawEncoding(RParenLoc);
1411 }
1412
1413 SourceLocation getExceptionSpecLocBeg() const {
1414 return SourceLocation::getFromRawEncoding(ExceptionSpecLocBeg);
1415 }
1416
1417 SourceLocation getExceptionSpecLocEnd() const {
1418 return SourceLocation::getFromRawEncoding(ExceptionSpecLocEnd);
1419 }
1420
1421 SourceRange getExceptionSpecRange() const {
1422 return SourceRange(getExceptionSpecLocBeg(), getExceptionSpecLocEnd());
1423 }
1424
1425 /// Retrieve the location of the ref-qualifier, if any.
1426 SourceLocation getRefQualifierLoc() const {
1427 return SourceLocation::getFromRawEncoding(RefQualifierLoc);
1428 }
1429
1430 /// Retrieve the location of the 'const' qualifier.
1431 SourceLocation getConstQualifierLoc() const {
1432 assert(MethodQualifiers)((MethodQualifiers) ? static_cast<void> (0) : __assert_fail
("MethodQualifiers", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 1432, __PRETTY_FUNCTION__))
;
1433 return MethodQualifiers->getConstSpecLoc();
1434 }
1435
1436 /// Retrieve the location of the 'volatile' qualifier.
1437 SourceLocation getVolatileQualifierLoc() const {
1438 assert(MethodQualifiers)((MethodQualifiers) ? static_cast<void> (0) : __assert_fail
("MethodQualifiers", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 1438, __PRETTY_FUNCTION__))
;
1439 return MethodQualifiers->getVolatileSpecLoc();
1440 }
1441
1442 /// Retrieve the location of the 'restrict' qualifier.
1443 SourceLocation getRestrictQualifierLoc() const {
1444 assert(MethodQualifiers)((MethodQualifiers) ? static_cast<void> (0) : __assert_fail
("MethodQualifiers", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 1444, __PRETTY_FUNCTION__))
;
1445 return MethodQualifiers->getRestrictSpecLoc();
1446 }
1447
1448 /// Retrieve the location of the 'mutable' qualifier, if any.
1449 SourceLocation getMutableLoc() const {
1450 return SourceLocation::getFromRawEncoding(MutableLoc);
1451 }
1452
1453 /// Determine whether this function declaration contains a
1454 /// ref-qualifier.
1455 bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1456
1457 /// Determine whether this lambda-declarator contains a 'mutable'
1458 /// qualifier.
1459 bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1460
1461 /// Determine whether this method has qualifiers.
1462 bool hasMethodTypeQualifiers() const {
1463 return MethodQualifiers && (MethodQualifiers->getTypeQualifiers() ||
1464 MethodQualifiers->getAttributes().size());
1465 }
1466
1467 /// Get the type of exception specification this function has.
1468 ExceptionSpecificationType getExceptionSpecType() const {
1469 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1470 }
1471
1472 /// Get the number of dynamic exception specifications.
1473 unsigned getNumExceptions() const {
1474 assert(ExceptionSpecType != EST_None)((ExceptionSpecType != EST_None) ? static_cast<void> (0
) : __assert_fail ("ExceptionSpecType != EST_None", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 1474, __PRETTY_FUNCTION__))
;
1475 return NumExceptionsOrDecls;
1476 }
1477
1478 /// Get the non-parameter decls defined within this function
1479 /// prototype. Typically these are tag declarations.
1480 ArrayRef<NamedDecl *> getDeclsInPrototype() const {
1481 assert(ExceptionSpecType == EST_None)((ExceptionSpecType == EST_None) ? static_cast<void> (0
) : __assert_fail ("ExceptionSpecType == EST_None", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 1481, __PRETTY_FUNCTION__))
;
1482 return llvm::makeArrayRef(DeclsInPrototype, NumExceptionsOrDecls);
1483 }
1484
1485 /// Determine whether this function declarator had a
1486 /// trailing-return-type.
1487 bool hasTrailingReturnType() const { return HasTrailingReturnType; }
1488
1489 /// Get the trailing-return-type for this function declarator.
1490 ParsedType getTrailingReturnType() const { return TrailingReturnType; }
1491 };
1492
1493 struct BlockPointerTypeInfo {
1494 /// For now, sema will catch these as invalid.
1495 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1496 unsigned TypeQuals : 5;
1497
1498 void destroy() {
1499 }
1500 };
1501
1502 struct MemberPointerTypeInfo {
1503 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1504 unsigned TypeQuals : 5;
1505 // CXXScopeSpec has a constructor, so it can't be a direct member.
1506 // So we need some pointer-aligned storage and a bit of trickery.
1507 alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)];
1508 CXXScopeSpec &Scope() {
1509 return *reinterpret_cast<CXXScopeSpec *>(ScopeMem);
1510 }
1511 const CXXScopeSpec &Scope() const {
1512 return *reinterpret_cast<const CXXScopeSpec *>(ScopeMem);
1513 }
1514 void destroy() {
1515 Scope().~CXXScopeSpec();
1516 }
1517 };
1518
1519 struct PipeTypeInfo {
1520 /// The access writes.
1521 unsigned AccessWrites : 3;
1522
1523 void destroy() {}
1524 };
1525
1526 union {
1527 PointerTypeInfo Ptr;
1528 ReferenceTypeInfo Ref;
1529 ArrayTypeInfo Arr;
1530 FunctionTypeInfo Fun;
1531 BlockPointerTypeInfo Cls;
1532 MemberPointerTypeInfo Mem;
1533 PipeTypeInfo PipeInfo;
1534 };
1535
1536 void destroy() {
1537 switch (Kind) {
1538 case DeclaratorChunk::Function: return Fun.destroy();
1539 case DeclaratorChunk::Pointer: return Ptr.destroy();
1540 case DeclaratorChunk::BlockPointer: return Cls.destroy();
1541 case DeclaratorChunk::Reference: return Ref.destroy();
1542 case DeclaratorChunk::Array: return Arr.destroy();
1543 case DeclaratorChunk::MemberPointer: return Mem.destroy();
1544 case DeclaratorChunk::Paren: return;
1545 case DeclaratorChunk::Pipe: return PipeInfo.destroy();
1546 }
1547 }
1548
1549 /// If there are attributes applied to this declaratorchunk, return
1550 /// them.
1551 const ParsedAttributesView &getAttrs() const { return AttrList; }
1552 ParsedAttributesView &getAttrs() { return AttrList; }
1553
1554 /// Return a DeclaratorChunk for a pointer.
1555 static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1556 SourceLocation ConstQualLoc,
1557 SourceLocation VolatileQualLoc,
1558 SourceLocation RestrictQualLoc,
1559 SourceLocation AtomicQualLoc,
1560 SourceLocation UnalignedQualLoc) {
1561 DeclaratorChunk I;
1562 I.Kind = Pointer;
1563 I.Loc = Loc;
1564 I.Ptr.TypeQuals = TypeQuals;
1565 I.Ptr.ConstQualLoc = ConstQualLoc.getRawEncoding();
1566 I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding();
1567 I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding();
1568 I.Ptr.AtomicQualLoc = AtomicQualLoc.getRawEncoding();
1569 I.Ptr.UnalignedQualLoc = UnalignedQualLoc.getRawEncoding();
1570 return I;
1571 }
1572
1573 /// Return a DeclaratorChunk for a reference.
1574 static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1575 bool lvalue) {
1576 DeclaratorChunk I;
1577 I.Kind = Reference;
1578 I.Loc = Loc;
1579 I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1580 I.Ref.LValueRef = lvalue;
1581 return I;
1582 }
1583
1584 /// Return a DeclaratorChunk for an array.
1585 static DeclaratorChunk getArray(unsigned TypeQuals,
1586 bool isStatic, bool isStar, Expr *NumElts,
1587 SourceLocation LBLoc, SourceLocation RBLoc) {
1588 DeclaratorChunk I;
1589 I.Kind = Array;
1590 I.Loc = LBLoc;
1591 I.EndLoc = RBLoc;
1592 I.Arr.TypeQuals = TypeQuals;
1593 I.Arr.hasStatic = isStatic;
1594 I.Arr.isStar = isStar;
1595 I.Arr.NumElts = NumElts;
1596 return I;
1597 }
1598
1599 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1600 /// "TheDeclarator" is the declarator that this will be added to.
1601 static DeclaratorChunk getFunction(bool HasProto,
1602 bool IsAmbiguous,
1603 SourceLocation LParenLoc,
1604 ParamInfo *Params, unsigned NumParams,
1605 SourceLocation EllipsisLoc,
1606 SourceLocation RParenLoc,
1607 bool RefQualifierIsLvalueRef,
1608 SourceLocation RefQualifierLoc,
1609 SourceLocation MutableLoc,
1610 ExceptionSpecificationType ESpecType,
1611 SourceRange ESpecRange,
1612 ParsedType *Exceptions,
1613 SourceRange *ExceptionRanges,
1614 unsigned NumExceptions,
1615 Expr *NoexceptExpr,
1616 CachedTokens *ExceptionSpecTokens,
1617 ArrayRef<NamedDecl *> DeclsInPrototype,
1618 SourceLocation LocalRangeBegin,
1619 SourceLocation LocalRangeEnd,
1620 Declarator &TheDeclarator,
1621 TypeResult TrailingReturnType =
1622 TypeResult(),
1623 DeclSpec *MethodQualifiers = nullptr);
1624
1625 /// Return a DeclaratorChunk for a block.
1626 static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1627 SourceLocation Loc) {
1628 DeclaratorChunk I;
1629 I.Kind = BlockPointer;
1630 I.Loc = Loc;
1631 I.Cls.TypeQuals = TypeQuals;
1632 return I;
1633 }
1634
1635 /// Return a DeclaratorChunk for a block.
1636 static DeclaratorChunk getPipe(unsigned TypeQuals,
1637 SourceLocation Loc) {
1638 DeclaratorChunk I;
1639 I.Kind = Pipe;
1640 I.Loc = Loc;
1641 I.Cls.TypeQuals = TypeQuals;
1642 return I;
1643 }
1644
1645 static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1646 unsigned TypeQuals,
1647 SourceLocation Loc) {
1648 DeclaratorChunk I;
1649 I.Kind = MemberPointer;
1650 I.Loc = SS.getBeginLoc();
1651 I.EndLoc = Loc;
1652 I.Mem.TypeQuals = TypeQuals;
1653 new (I.Mem.ScopeMem) CXXScopeSpec(SS);
1654 return I;
1655 }
1656
1657 /// Return a DeclaratorChunk for a paren.
1658 static DeclaratorChunk getParen(SourceLocation LParenLoc,
1659 SourceLocation RParenLoc) {
1660 DeclaratorChunk I;
1661 I.Kind = Paren;
1662 I.Loc = LParenLoc;
1663 I.EndLoc = RParenLoc;
1664 return I;
1665 }
1666
1667 bool isParen() const {
1668 return Kind == Paren;
1669 }
1670};
1671
1672/// A parsed C++17 decomposition declarator of the form
1673/// '[' identifier-list ']'
1674class DecompositionDeclarator {
1675public:
1676 struct Binding {
1677 IdentifierInfo *Name;
1678 SourceLocation NameLoc;
1679 };
1680
1681private:
1682 /// The locations of the '[' and ']' tokens.
1683 SourceLocation LSquareLoc, RSquareLoc;
1684
1685 /// The bindings.
1686 Binding *Bindings;
1687 unsigned NumBindings : 31;
1688 unsigned DeleteBindings : 1;
1689
1690 friend class Declarator;
1691
1692public:
1693 DecompositionDeclarator()
1694 : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {}
1695 DecompositionDeclarator(const DecompositionDeclarator &G) = delete;
1696 DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete;
1697 ~DecompositionDeclarator() {
1698 if (DeleteBindings)
1699 delete[] Bindings;
1700 }
1701
1702 void clear() {
1703 LSquareLoc = RSquareLoc = SourceLocation();
1704 if (DeleteBindings)
1705 delete[] Bindings;
1706 Bindings = nullptr;
1707 NumBindings = 0;
1708 DeleteBindings = false;
1709 }
1710
1711 ArrayRef<Binding> bindings() const {
1712 return llvm::makeArrayRef(Bindings, NumBindings);
1713 }
1714
1715 bool isSet() const { return LSquareLoc.isValid(); }
1716
1717 SourceLocation getLSquareLoc() const { return LSquareLoc; }
1718 SourceLocation getRSquareLoc() const { return RSquareLoc; }
1719 SourceRange getSourceRange() const {
1720 return SourceRange(LSquareLoc, RSquareLoc);
1721 }
1722};
1723
1724/// Described the kind of function definition (if any) provided for
1725/// a function.
1726enum FunctionDefinitionKind {
1727 FDK_Declaration,
1728 FDK_Definition,
1729 FDK_Defaulted,
1730 FDK_Deleted
1731};
1732
1733enum class DeclaratorContext {
1734 FileContext, // File scope declaration.
1735 PrototypeContext, // Within a function prototype.
1736 ObjCResultContext, // An ObjC method result type.
1737 ObjCParameterContext,// An ObjC method parameter type.
1738 KNRTypeListContext, // K&R type definition list for formals.
1739 TypeNameContext, // Abstract declarator for types.
1740 FunctionalCastContext, // Type in a C++ functional cast expression.
1741 MemberContext, // Struct/Union field.
1742 BlockContext, // Declaration within a block in a function.
1743 ForContext, // Declaration within first part of a for loop.
1744 InitStmtContext, // Declaration within optional init stmt of if/switch.
1745 ConditionContext, // Condition declaration in a C++ if/switch/while/for.
1746 TemplateParamContext,// Within a template parameter list.
1747 CXXNewContext, // C++ new-expression.
1748 CXXCatchContext, // C++ catch exception-declaration
1749 ObjCCatchContext, // Objective-C catch exception-declaration
1750 BlockLiteralContext, // Block literal declarator.
1751 LambdaExprContext, // Lambda-expression declarator.
1752 LambdaExprParameterContext, // Lambda-expression parameter declarator.
1753 ConversionIdContext, // C++ conversion-type-id.
1754 TrailingReturnContext, // C++11 trailing-type-specifier.
1755 TrailingReturnVarContext, // C++11 trailing-type-specifier for variable.
1756 TemplateArgContext, // Any template argument (in template argument list).
1757 TemplateTypeArgContext, // Template type argument (in default argument).
1758 AliasDeclContext, // C++11 alias-declaration.
1759 AliasTemplateContext // C++11 alias-declaration template.
1760};
1761
1762
1763/// Information about one declarator, including the parsed type
1764/// information and the identifier.
1765///
1766/// When the declarator is fully formed, this is turned into the appropriate
1767/// Decl object.
1768///
1769/// Declarators come in two types: normal declarators and abstract declarators.
1770/// Abstract declarators are used when parsing types, and don't have an
1771/// identifier. Normal declarators do have ID's.
1772///
1773/// Instances of this class should be a transient object that lives on the
1774/// stack, not objects that are allocated in large quantities on the heap.
1775class Declarator {
1776
1777private:
1778 const DeclSpec &DS;
1779 CXXScopeSpec SS;
1780 UnqualifiedId Name;
1781 SourceRange Range;
1782
1783 /// Where we are parsing this declarator.
1784 DeclaratorContext Context;
1785
1786 /// The C++17 structured binding, if any. This is an alternative to a Name.
1787 DecompositionDeclarator BindingGroup;
1788
1789 /// DeclTypeInfo - This holds each type that the declarator includes as it is
1790 /// parsed. This is pushed from the identifier out, which means that element
1791 /// #0 will be the most closely bound to the identifier, and
1792 /// DeclTypeInfo.back() will be the least closely bound.
1793 SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1794
1795 /// InvalidType - Set by Sema::GetTypeForDeclarator().
1796 unsigned InvalidType : 1;
1797
1798 /// GroupingParens - Set by Parser::ParseParenDeclarator().
1799 unsigned GroupingParens : 1;
1800
1801 /// FunctionDefinition - Is this Declarator for a function or member
1802 /// definition and, if so, what kind?
1803 ///
1804 /// Actually a FunctionDefinitionKind.
1805 unsigned FunctionDefinition : 2;
1806
1807 /// Is this Declarator a redeclaration?
1808 unsigned Redeclaration : 1;
1809
1810 /// true if the declaration is preceded by \c __extension__.
1811 unsigned Extension : 1;
1812
1813 /// Indicates whether this is an Objective-C instance variable.
1814 unsigned ObjCIvar : 1;
1815
1816 /// Indicates whether this is an Objective-C 'weak' property.
1817 unsigned ObjCWeakProperty : 1;
1818
1819 /// Indicates whether the InlineParams / InlineBindings storage has been used.
1820 unsigned InlineStorageUsed : 1;
1821
1822 /// Attrs - Attributes.
1823 ParsedAttributes Attrs;
1824
1825 /// The asm label, if specified.
1826 Expr *AsmLabel;
1827
1828#ifndef _MSC_VER
1829 union {
1830#endif
1831 /// InlineParams - This is a local array used for the first function decl
1832 /// chunk to avoid going to the heap for the common case when we have one
1833 /// function chunk in the declarator.
1834 DeclaratorChunk::ParamInfo InlineParams[16];
1835 DecompositionDeclarator::Binding InlineBindings[16];
1836#ifndef _MSC_VER
1837 };
1838#endif
1839
1840 /// If this is the second or subsequent declarator in this declaration,
1841 /// the location of the comma before this declarator.
1842 SourceLocation CommaLoc;
1843
1844 /// If provided, the source location of the ellipsis used to describe
1845 /// this declarator as a parameter pack.
1846 SourceLocation EllipsisLoc;
1847
1848 friend struct DeclaratorChunk;
1849
1850public:
1851 Declarator(const DeclSpec &ds, DeclaratorContext C)
1852 : DS(ds), Range(ds.getSourceRange()), Context(C),
1853 InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1854 GroupingParens(false), FunctionDefinition(FDK_Declaration),
1855 Redeclaration(false), Extension(false), ObjCIvar(false),
1856 ObjCWeakProperty(false), InlineStorageUsed(false),
1857 Attrs(ds.getAttributePool().getFactory()), AsmLabel(nullptr) {}
1858
1859 ~Declarator() {
1860 clear();
1861 }
1862 /// getDeclSpec - Return the declaration-specifier that this declarator was
1863 /// declared with.
1864 const DeclSpec &getDeclSpec() const { return DS; }
1865
1866 /// getMutableDeclSpec - Return a non-const version of the DeclSpec. This
1867 /// should be used with extreme care: declspecs can often be shared between
1868 /// multiple declarators, so mutating the DeclSpec affects all of the
1869 /// Declarators. This should only be done when the declspec is known to not
1870 /// be shared or when in error recovery etc.
1871 DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1872
1873 AttributePool &getAttributePool() const {
1874 return Attrs.getPool();
1875 }
1876
1877 /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1878 /// nested-name-specifier) that is part of the declarator-id.
1879 const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
1880 CXXScopeSpec &getCXXScopeSpec() { return SS; }
1881
1882 /// Retrieve the name specified by this declarator.
1883 UnqualifiedId &getName() { return Name; }
1884
1885 const DecompositionDeclarator &getDecompositionDeclarator() const {
1886 return BindingGroup;
1887 }
1888
1889 DeclaratorContext getContext() const { return Context; }
1890
1891 bool isPrototypeContext() const {
1892 return (Context == DeclaratorContext::PrototypeContext ||
1893 Context == DeclaratorContext::ObjCParameterContext ||
1894 Context == DeclaratorContext::ObjCResultContext ||
1895 Context == DeclaratorContext::LambdaExprParameterContext);
1896 }
1897
1898 /// Get the source range that spans this declarator.
1899 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
1900 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
1901 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
1902
1903 void SetSourceRange(SourceRange R) { Range = R; }
1904 /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1905 /// invalid.
1906 void SetRangeBegin(SourceLocation Loc) {
1907 if (!Loc.isInvalid())
1908 Range.setBegin(Loc);
1909 }
1910 /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1911 void SetRangeEnd(SourceLocation Loc) {
1912 if (!Loc.isInvalid())
1913 Range.setEnd(Loc);
1914 }
1915 /// ExtendWithDeclSpec - Extend the declarator source range to include the
1916 /// given declspec, unless its location is invalid. Adopts the range start if
1917 /// the current range start is invalid.
1918 void ExtendWithDeclSpec(const DeclSpec &DS) {
1919 SourceRange SR = DS.getSourceRange();
1920 if (Range.getBegin().isInvalid())
1921 Range.setBegin(SR.getBegin());
1922 if (!SR.getEnd().isInvalid())
1923 Range.setEnd(SR.getEnd());
1924 }
1925
1926 /// Reset the contents of this Declarator.
1927 void clear() {
1928 SS.clear();
1929 Name.clear();
1930 Range = DS.getSourceRange();
1931 BindingGroup.clear();
1932
1933 for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1934 DeclTypeInfo[i].destroy();
1935 DeclTypeInfo.clear();
1936 Attrs.clear();
1937 AsmLabel = nullptr;
1938 InlineStorageUsed = false;
1939 ObjCIvar = false;
1940 ObjCWeakProperty = false;
1941 CommaLoc = SourceLocation();
1942 EllipsisLoc = SourceLocation();
1943 }
1944
1945 /// mayOmitIdentifier - Return true if the identifier is either optional or
1946 /// not allowed. This is true for typenames, prototypes, and template
1947 /// parameter lists.
1948 bool mayOmitIdentifier() const {
1949 switch (Context) {
1950 case DeclaratorContext::FileContext:
1951 case DeclaratorContext::KNRTypeListContext:
1952 case DeclaratorContext::MemberContext:
1953 case DeclaratorContext::BlockContext:
1954 case DeclaratorContext::ForContext:
1955 case DeclaratorContext::InitStmtContext:
1956 case DeclaratorContext::ConditionContext:
1957 return false;
1958
1959 case DeclaratorContext::TypeNameContext:
1960 case DeclaratorContext::FunctionalCastContext:
1961 case DeclaratorContext::AliasDeclContext:
1962 case DeclaratorContext::AliasTemplateContext:
1963 case DeclaratorContext::PrototypeContext:
1964 case DeclaratorContext::LambdaExprParameterContext:
1965 case DeclaratorContext::ObjCParameterContext:
1966 case DeclaratorContext::ObjCResultContext:
1967 case DeclaratorContext::TemplateParamContext:
1968 case DeclaratorContext::CXXNewContext:
1969 case DeclaratorContext::CXXCatchContext:
1970 case DeclaratorContext::ObjCCatchContext:
1971 case DeclaratorContext::BlockLiteralContext:
1972 case DeclaratorContext::LambdaExprContext:
1973 case DeclaratorContext::ConversionIdContext:
1974 case DeclaratorContext::TemplateArgContext:
1975 case DeclaratorContext::TemplateTypeArgContext:
1976 case DeclaratorContext::TrailingReturnContext:
1977 case DeclaratorContext::TrailingReturnVarContext:
1978 return true;
1979 }
1980 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 1980)
;
1981 }
1982
1983 /// mayHaveIdentifier - Return true if the identifier is either optional or
1984 /// required. This is true for normal declarators and prototypes, but not
1985 /// typenames.
1986 bool mayHaveIdentifier() const {
1987 switch (Context) {
1988 case DeclaratorContext::FileContext:
1989 case DeclaratorContext::KNRTypeListContext:
1990 case DeclaratorContext::MemberContext:
1991 case DeclaratorContext::BlockContext:
1992 case DeclaratorContext::ForContext:
1993 case DeclaratorContext::InitStmtContext:
1994 case DeclaratorContext::ConditionContext:
1995 case DeclaratorContext::PrototypeContext:
1996 case DeclaratorContext::LambdaExprParameterContext:
1997 case DeclaratorContext::TemplateParamContext:
1998 case DeclaratorContext::CXXCatchContext:
1999 case DeclaratorContext::ObjCCatchContext:
2000 return true;
2001
2002 case DeclaratorContext::TypeNameContext:
2003 case DeclaratorContext::FunctionalCastContext:
2004 case DeclaratorContext::CXXNewContext:
2005 case DeclaratorContext::AliasDeclContext:
2006 case DeclaratorContext::AliasTemplateContext:
2007 case DeclaratorContext::ObjCParameterContext:
2008 case DeclaratorContext::ObjCResultContext:
2009 case DeclaratorContext::BlockLiteralContext:
2010 case DeclaratorContext::LambdaExprContext:
2011 case DeclaratorContext::ConversionIdContext:
2012 case DeclaratorContext::TemplateArgContext:
2013 case DeclaratorContext::TemplateTypeArgContext:
2014 case DeclaratorContext::TrailingReturnContext:
2015 case DeclaratorContext::TrailingReturnVarContext:
2016 return false;
2017 }
2018 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 2018)
;
2019 }
2020
2021 /// Return true if the context permits a C++17 decomposition declarator.
2022 bool mayHaveDecompositionDeclarator() const {
2023 switch (Context) {
2024 case DeclaratorContext::FileContext:
2025 // FIXME: It's not clear that the proposal meant to allow file-scope
2026 // structured bindings, but it does.
2027 case DeclaratorContext::BlockContext:
2028 case DeclaratorContext::ForContext:
2029 case DeclaratorContext::InitStmtContext:
2030 case DeclaratorContext::ConditionContext:
2031 return true;
2032
2033 case DeclaratorContext::MemberContext:
2034 case DeclaratorContext::PrototypeContext:
2035 case DeclaratorContext::TemplateParamContext:
2036 // Maybe one day...
2037 return false;
2038
2039 // These contexts don't allow any kind of non-abstract declarator.
2040 case DeclaratorContext::KNRTypeListContext:
2041 case DeclaratorContext::TypeNameContext:
2042 case DeclaratorContext::FunctionalCastContext:
2043 case DeclaratorContext::AliasDeclContext:
2044 case DeclaratorContext::AliasTemplateContext:
2045 case DeclaratorContext::LambdaExprParameterContext:
2046 case DeclaratorContext::ObjCParameterContext:
2047 case DeclaratorContext::ObjCResultContext:
2048 case DeclaratorContext::CXXNewContext:
2049 case DeclaratorContext::CXXCatchContext:
2050 case DeclaratorContext::ObjCCatchContext:
2051 case DeclaratorContext::BlockLiteralContext:
2052 case DeclaratorContext::LambdaExprContext:
2053 case DeclaratorContext::ConversionIdContext:
2054 case DeclaratorContext::TemplateArgContext:
2055 case DeclaratorContext::TemplateTypeArgContext:
2056 case DeclaratorContext::TrailingReturnContext:
2057 case DeclaratorContext::TrailingReturnVarContext:
2058 return false;
2059 }
2060 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 2060)
;
2061 }
2062
2063 /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
2064 /// followed by a C++ direct initializer, e.g. "int x(1);".
2065 bool mayBeFollowedByCXXDirectInit() const {
2066 if (hasGroupingParens()) return false;
2067
2068 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2069 return false;
2070
2071 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
2072 Context != DeclaratorContext::FileContext)
2073 return false;
2074
2075 // Special names can't have direct initializers.
2076 if (Name.getKind() != UnqualifiedIdKind::IK_Identifier)
2077 return false;
2078
2079 switch (Context) {
2080 case DeclaratorContext::FileContext:
2081 case DeclaratorContext::BlockContext:
2082 case DeclaratorContext::ForContext:
2083 case DeclaratorContext::InitStmtContext:
2084 case DeclaratorContext::TrailingReturnVarContext:
2085 return true;
2086
2087 case DeclaratorContext::ConditionContext:
2088 // This may not be followed by a direct initializer, but it can't be a
2089 // function declaration either, and we'd prefer to perform a tentative
2090 // parse in order to produce the right diagnostic.
2091 return true;
2092
2093 case DeclaratorContext::KNRTypeListContext:
2094 case DeclaratorContext::MemberContext:
2095 case DeclaratorContext::PrototypeContext:
2096 case DeclaratorContext::LambdaExprParameterContext:
2097 case DeclaratorContext::ObjCParameterContext:
2098 case DeclaratorContext::ObjCResultContext:
2099 case DeclaratorContext::TemplateParamContext:
2100 case DeclaratorContext::CXXCatchContext:
2101 case DeclaratorContext::ObjCCatchContext:
2102 case DeclaratorContext::TypeNameContext:
2103 case DeclaratorContext::FunctionalCastContext: // FIXME
2104 case DeclaratorContext::CXXNewContext:
2105 case DeclaratorContext::AliasDeclContext:
2106 case DeclaratorContext::AliasTemplateContext:
2107 case DeclaratorContext::BlockLiteralContext:
2108 case DeclaratorContext::LambdaExprContext:
2109 case DeclaratorContext::ConversionIdContext:
2110 case DeclaratorContext::TemplateArgContext:
2111 case DeclaratorContext::TemplateTypeArgContext:
2112 case DeclaratorContext::TrailingReturnContext:
2113 return false;
2114 }
2115 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 2115)
;
2116 }
2117
2118 /// isPastIdentifier - Return true if we have parsed beyond the point where
2119 /// the name would appear. (This may happen even if we haven't actually parsed
2120 /// a name, perhaps because this context doesn't require one.)
2121 bool isPastIdentifier() const { return Name.isValid(); }
2122
2123 /// hasName - Whether this declarator has a name, which might be an
2124 /// identifier (accessible via getIdentifier()) or some kind of
2125 /// special C++ name (constructor, destructor, etc.), or a structured
2126 /// binding (which is not exactly a name, but occupies the same position).
2127 bool hasName() const {
2128 return Name.getKind() != UnqualifiedIdKind::IK_Identifier ||
2129 Name.Identifier || isDecompositionDeclarator();
2130 }
2131
2132 /// Return whether this declarator is a decomposition declarator.
2133 bool isDecompositionDeclarator() const {
2134 return BindingGroup.isSet();
2135 }
2136
2137 IdentifierInfo *getIdentifier() const {
2138 if (Name.getKind() == UnqualifiedIdKind::IK_Identifier)
2139 return Name.Identifier;
2140
2141 return nullptr;
2142 }
2143 SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
2144
2145 /// Set the name of this declarator to be the given identifier.
2146 void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
2147 Name.setIdentifier(Id, IdLoc);
2148 }
2149
2150 /// Set the decomposition bindings for this declarator.
2151 void
2152 setDecompositionBindings(SourceLocation LSquareLoc,
2153 ArrayRef<DecompositionDeclarator::Binding> Bindings,
2154 SourceLocation RSquareLoc);
2155
2156 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2157 /// EndLoc, which should be the last token of the chunk.
2158 /// This function takes attrs by R-Value reference because it takes ownership
2159 /// of those attributes from the parameter.
2160 void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs,
2161 SourceLocation EndLoc) {
2162 DeclTypeInfo.push_back(TI);
2163 DeclTypeInfo.back().getAttrs().addAll(attrs.begin(), attrs.end());
2164 getAttributePool().takeAllFrom(attrs.getPool());
2165
2166 if (!EndLoc.isInvalid())
2167 SetRangeEnd(EndLoc);
2168 }
2169
2170 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2171 /// EndLoc, which should be the last token of the chunk.
2172 void AddTypeInfo(const DeclaratorChunk &TI, SourceLocation EndLoc) {
2173 DeclTypeInfo.push_back(TI);
2174
2175 if (!EndLoc.isInvalid())
2176 SetRangeEnd(EndLoc);
2177 }
2178
2179 /// Add a new innermost chunk to this declarator.
2180 void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
2181 DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
2182 }
2183
2184 /// Return the number of types applied to this declarator.
2185 unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
2186
2187 /// Return the specified TypeInfo from this declarator. TypeInfo #0 is
2188 /// closest to the identifier.
2189 const DeclaratorChunk &getTypeObject(unsigned i) const {
2190 assert(i < DeclTypeInfo.size() && "Invalid type chunk")((i < DeclTypeInfo.size() && "Invalid type chunk")
? static_cast<void> (0) : __assert_fail ("i < DeclTypeInfo.size() && \"Invalid type chunk\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 2190, __PRETTY_FUNCTION__))
;
2191 return DeclTypeInfo[i];
2192 }
2193 DeclaratorChunk &getTypeObject(unsigned i) {
2194 assert(i < DeclTypeInfo.size() && "Invalid type chunk")((i < DeclTypeInfo.size() && "Invalid type chunk")
? static_cast<void> (0) : __assert_fail ("i < DeclTypeInfo.size() && \"Invalid type chunk\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 2194, __PRETTY_FUNCTION__))
;
2195 return DeclTypeInfo[i];
2196 }
2197
2198 typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator;
2199 typedef llvm::iterator_range<type_object_iterator> type_object_range;
2200
2201 /// Returns the range of type objects, from the identifier outwards.
2202 type_object_range type_objects() const {
2203 return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end());
2204 }
2205
2206 void DropFirstTypeObject() {
2207 assert(!DeclTypeInfo.empty() && "No type chunks to drop.")((!DeclTypeInfo.empty() && "No type chunks to drop.")
? static_cast<void> (0) : __assert_fail ("!DeclTypeInfo.empty() && \"No type chunks to drop.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 2207, __PRETTY_FUNCTION__))
;
2208 DeclTypeInfo.front().destroy();
2209 DeclTypeInfo.erase(DeclTypeInfo.begin());
2210 }
2211
2212 /// Return the innermost (closest to the declarator) chunk of this
2213 /// declarator that is not a parens chunk, or null if there are no
2214 /// non-parens chunks.
2215 const DeclaratorChunk *getInnermostNonParenChunk() const {
2216 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2217 if (!DeclTypeInfo[i].isParen())
2218 return &DeclTypeInfo[i];
2219 }
2220 return nullptr;
2221 }
2222
2223 /// Return the outermost (furthest from the declarator) chunk of
2224 /// this declarator that is not a parens chunk, or null if there are
2225 /// no non-parens chunks.
2226 const DeclaratorChunk *getOutermostNonParenChunk() const {
2227 for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
2228 if (!DeclTypeInfo[i-1].isParen())
2229 return &DeclTypeInfo[i-1];
2230 }
2231 return nullptr;
2232 }
2233
2234 /// isArrayOfUnknownBound - This method returns true if the declarator
2235 /// is a declarator for an array of unknown bound (looking through
2236 /// parentheses).
2237 bool isArrayOfUnknownBound() const {
2238 const DeclaratorChunk *chunk = getInnermostNonParenChunk();
2239 return (chunk && chunk->Kind == DeclaratorChunk::Array &&
2240 !chunk->Arr.NumElts);
2241 }
2242
2243 /// isFunctionDeclarator - This method returns true if the declarator
2244 /// is a function declarator (looking through parentheses).
2245 /// If true is returned, then the reference type parameter idx is
2246 /// assigned with the index of the declaration chunk.
2247 bool isFunctionDeclarator(unsigned& idx) const {
2248 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2249 switch (DeclTypeInfo[i].Kind) {
2250 case DeclaratorChunk::Function:
2251 idx = i;
2252 return true;
2253 case DeclaratorChunk::Paren:
2254 continue;
2255 case DeclaratorChunk::Pointer:
2256 case DeclaratorChunk::Reference:
2257 case DeclaratorChunk::Array:
2258 case DeclaratorChunk::BlockPointer:
2259 case DeclaratorChunk::MemberPointer:
2260 case DeclaratorChunk::Pipe:
2261 return false;
2262 }
2263 llvm_unreachable("Invalid type chunk")::llvm::llvm_unreachable_internal("Invalid type chunk", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 2263)
;
2264 }
2265 return false;
2266 }
2267
2268 /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
2269 /// this method returns true if the identifier is a function declarator
2270 /// (looking through parentheses).
2271 bool isFunctionDeclarator() const {
2272 unsigned index;
2273 return isFunctionDeclarator(index);
2274 }
2275
2276 /// getFunctionTypeInfo - Retrieves the function type info object
2277 /// (looking through parentheses).
2278 DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
2279 assert(isFunctionDeclarator() && "Not a function declarator!")((isFunctionDeclarator() && "Not a function declarator!"
) ? static_cast<void> (0) : __assert_fail ("isFunctionDeclarator() && \"Not a function declarator!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 2279, __PRETTY_FUNCTION__))
;
2280 unsigned index = 0;
2281 isFunctionDeclarator(index);
2282 return DeclTypeInfo[index].Fun;
2283 }
2284
2285 /// getFunctionTypeInfo - Retrieves the function type info object
2286 /// (looking through parentheses).
2287 const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
2288 return const_cast<Declarator*>(this)->getFunctionTypeInfo();
2289 }
2290
2291 /// Determine whether the declaration that will be produced from
2292 /// this declaration will be a function.
2293 ///
2294 /// A declaration can declare a function even if the declarator itself
2295 /// isn't a function declarator, if the type specifier refers to a function
2296 /// type. This routine checks for both cases.
2297 bool isDeclarationOfFunction() const;
2298
2299 /// Return true if this declaration appears in a context where a
2300 /// function declarator would be a function declaration.
2301 bool isFunctionDeclarationContext() const {
2302 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2303 return false;
2304
2305 switch (Context) {
2306 case DeclaratorContext::FileContext:
2307 case DeclaratorContext::MemberContext:
2308 case DeclaratorContext::BlockContext:
2309 case DeclaratorContext::ForContext:
2310 case DeclaratorContext::InitStmtContext:
2311 return true;
2312
2313 case DeclaratorContext::ConditionContext:
2314 case DeclaratorContext::KNRTypeListContext:
2315 case DeclaratorContext::TypeNameContext:
2316 case DeclaratorContext::FunctionalCastContext:
2317 case DeclaratorContext::AliasDeclContext:
2318 case DeclaratorContext::AliasTemplateContext:
2319 case DeclaratorContext::PrototypeContext:
2320 case DeclaratorContext::LambdaExprParameterContext:
2321 case DeclaratorContext::ObjCParameterContext:
2322 case DeclaratorContext::ObjCResultContext:
2323 case DeclaratorContext::TemplateParamContext:
2324 case DeclaratorContext::CXXNewContext:
2325 case DeclaratorContext::CXXCatchContext:
2326 case DeclaratorContext::ObjCCatchContext:
2327 case DeclaratorContext::BlockLiteralContext:
2328 case DeclaratorContext::LambdaExprContext:
2329 case DeclaratorContext::ConversionIdContext:
2330 case DeclaratorContext::TemplateArgContext:
2331 case DeclaratorContext::TemplateTypeArgContext:
2332 case DeclaratorContext::TrailingReturnContext:
2333 case DeclaratorContext::TrailingReturnVarContext:
2334 return false;
2335 }
2336 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 2336)
;
2337 }
2338
2339 /// Determine whether this declaration appears in a context where an
2340 /// expression could appear.
2341 bool isExpressionContext() const {
2342 switch (Context) {
2343 case DeclaratorContext::FileContext:
2344 case DeclaratorContext::KNRTypeListContext:
2345 case DeclaratorContext::MemberContext:
2346
2347 // FIXME: sizeof(...) permits an expression.
2348 case DeclaratorContext::TypeNameContext:
2349
2350 case DeclaratorContext::FunctionalCastContext:
2351 case DeclaratorContext::AliasDeclContext:
2352 case DeclaratorContext::AliasTemplateContext:
2353 case DeclaratorContext::PrototypeContext:
2354 case DeclaratorContext::LambdaExprParameterContext:
2355 case DeclaratorContext::ObjCParameterContext:
2356 case DeclaratorContext::ObjCResultContext:
2357 case DeclaratorContext::TemplateParamContext:
2358 case DeclaratorContext::CXXNewContext:
2359 case DeclaratorContext::CXXCatchContext:
2360 case DeclaratorContext::ObjCCatchContext:
2361 case DeclaratorContext::BlockLiteralContext:
2362 case DeclaratorContext::LambdaExprContext:
2363 case DeclaratorContext::ConversionIdContext:
2364 case DeclaratorContext::TrailingReturnContext:
2365 case DeclaratorContext::TrailingReturnVarContext:
2366 case DeclaratorContext::TemplateTypeArgContext:
2367 return false;
2368
2369 case DeclaratorContext::BlockContext:
2370 case DeclaratorContext::ForContext:
2371 case DeclaratorContext::InitStmtContext:
2372 case DeclaratorContext::ConditionContext:
2373 case DeclaratorContext::TemplateArgContext:
2374 return true;
2375 }
2376
2377 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/DeclSpec.h"
, 2377)
;
2378 }
2379
2380 /// Return true if a function declarator at this position would be a
2381 /// function declaration.
2382 bool isFunctionDeclaratorAFunctionDeclaration() const {
2383 if (!isFunctionDeclarationContext())
2384 return false;
2385
2386 for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
2387 if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
2388 return false;
2389
2390 return true;
2391 }
2392
2393 /// Determine whether a trailing return type was written (at any
2394 /// level) within this declarator.
2395 bool hasTrailingReturnType() const {
2396 for (const auto &Chunk : type_objects())
2397 if (Chunk.Kind == DeclaratorChunk::Function &&
2398 Chunk.Fun.hasTrailingReturnType())
2399 return true;
2400 return false;
2401 }
2402
2403 /// takeAttributes - Takes attributes from the given parsed-attributes
2404 /// set and add them to this declarator.
2405 ///
2406 /// These examples both add 3 attributes to "var":
2407 /// short int var __attribute__((aligned(16),common,deprecated));
2408 /// short int x, __attribute__((aligned(16)) var
2409 /// __attribute__((common,deprecated));
2410 ///
2411 /// Also extends the range of the declarator.
2412 void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
2413 Attrs.takeAllFrom(attrs);
2414
2415 if (!lastLoc.isInvalid())
2416 SetRangeEnd(lastLoc);
2417 }
2418
2419 const ParsedAttributes &getAttributes() const { return Attrs; }
2420 ParsedAttributes &getAttributes() { return Attrs; }
2421
2422 /// hasAttributes - do we contain any attributes?
2423 bool hasAttributes() const {
2424 if (!getAttributes().empty() || getDeclSpec().hasAttributes())
2425 return true;
2426 for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
2427 if (!getTypeObject(i).getAttrs().empty())
2428 return true;
2429 return false;
2430 }
2431
2432 /// Return a source range list of C++11 attributes associated
2433 /// with the declarator.
2434 void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) {
2435 for (const ParsedAttr &AL : Attrs)
2436 if (AL.isCXX11Attribute())
2437 Ranges.push_back(AL.getRange());
2438 }
2439
2440 void setAsmLabel(Expr *E) { AsmLabel = E; }
2441 Expr *getAsmLabel() const { return AsmLabel; }
2442
2443 void setExtension(bool Val = true) { Extension = Val; }
2444 bool getExtension() const { return Extension; }
2445
2446 void setObjCIvar(bool Val = true) { ObjCIvar = Val; }
2447 bool isObjCIvar() const { return ObjCIvar; }
2448
2449 void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; }
2450 bool isObjCWeakProperty() const { return ObjCWeakProperty; }
2451
2452 void setInvalidType(bool Val = true) { InvalidType = Val; }
2453 bool isInvalidType() const {
2454 return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
12
Assuming field 'InvalidType' is 0
13
Assuming the condition is false
14
Returning zero, which participates in a condition later
2455 }
2456
2457 void setGroupingParens(bool flag) { GroupingParens = flag; }
2458 bool hasGroupingParens() const { return GroupingParens; }
2459
2460 bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
2461 SourceLocation getCommaLoc() const { return CommaLoc; }
2462 void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2463
2464 bool hasEllipsis() const { return EllipsisLoc.isValid(); }
2465 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
2466 void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2467
2468 void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
2469 FunctionDefinition = Val;
2470 }
2471
2472 bool isFunctionDefinition() const {
2473 return getFunctionDefinitionKind() != FDK_Declaration;
2474 }
2475
2476 FunctionDefinitionKind getFunctionDefinitionKind() const {
2477 return (FunctionDefinitionKind)FunctionDefinition;
2478 }
2479
2480 /// Returns true if this declares a real member and not a friend.
2481 bool isFirstDeclarationOfMember() {
2482 return getContext() == DeclaratorContext::MemberContext &&
2483 !getDeclSpec().isFriendSpecified();
2484 }
2485
2486 /// Returns true if this declares a static member. This cannot be called on a
2487 /// declarator outside of a MemberContext because we won't know until
2488 /// redeclaration time if the decl is static.
2489 bool isStaticMember();
2490
2491 /// Returns true if this declares a constructor or a destructor.
2492 bool isCtorOrDtor();
2493
2494 void setRedeclaration(bool Val) { Redeclaration = Val; }
2495 bool isRedeclaration() const { return Redeclaration; }
2496};
2497
2498/// This little struct is used to capture information about
2499/// structure field declarators, which is basically just a bitfield size.
2500struct FieldDeclarator {
2501 Declarator D;
2502 Expr *BitfieldSize;
2503 explicit FieldDeclarator(const DeclSpec &DS)
2504 : D(DS, DeclaratorContext::MemberContext),
2505 BitfieldSize(nullptr) {}
2506};
2507
2508/// Represents a C++11 virt-specifier-seq.
2509class VirtSpecifiers {
2510public:
2511 enum Specifier {
2512 VS_None = 0,
2513 VS_Override = 1,
2514 VS_Final = 2,
2515 VS_Sealed = 4,
2516 // Represents the __final keyword, which is legal for gcc in pre-C++11 mode.
2517 VS_GNU_Final = 8
2518 };
2519
2520 VirtSpecifiers() : Specifiers(0), LastSpecifier(VS_None) { }
2521
2522 bool SetSpecifier(Specifier VS, SourceLocation Loc,
2523 const char *&PrevSpec);
2524
2525 bool isUnset() const { return Specifiers == 0; }
2526
2527 bool isOverrideSpecified() const { return Specifiers & VS_Override; }
2528 SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2529
2530 bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed | VS_GNU_Final); }
2531 bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
2532 SourceLocation getFinalLoc() const { return VS_finalLoc; }
2533
2534 void clear() { Specifiers = 0; }
2535
2536 static const char *getSpecifierName(Specifier VS);
2537
2538 SourceLocation getFirstLocation() const { return FirstLocation; }
2539 SourceLocation getLastLocation() const { return LastLocation; }
2540 Specifier getLastSpecifier() const { return LastSpecifier; }
2541
2542private:
2543 unsigned Specifiers;
2544 Specifier LastSpecifier;
2545
2546 SourceLocation VS_overrideLoc, VS_finalLoc;
2547 SourceLocation FirstLocation;
2548 SourceLocation LastLocation;
2549};
2550
2551enum class LambdaCaptureInitKind {
2552 NoInit, //!< [a]
2553 CopyInit, //!< [a = b], [a = {b}]
2554 DirectInit, //!< [a(b)]
2555 ListInit //!< [a{b}]
2556};
2557
2558/// Represents a complete lambda introducer.
2559struct LambdaIntroducer {
2560 /// An individual capture in a lambda introducer.
2561 struct LambdaCapture {
2562 LambdaCaptureKind Kind;
2563 SourceLocation Loc;
2564 IdentifierInfo *Id;
2565 SourceLocation EllipsisLoc;
2566 LambdaCaptureInitKind InitKind;
2567 ExprResult Init;
2568 ParsedType InitCaptureType;
2569 SourceRange ExplicitRange;
2570
2571 LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2572 IdentifierInfo *Id, SourceLocation EllipsisLoc,
2573 LambdaCaptureInitKind InitKind, ExprResult Init,
2574 ParsedType InitCaptureType,
2575 SourceRange ExplicitRange)
2576 : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc),
2577 InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType),
2578 ExplicitRange(ExplicitRange) {}
2579 };
2580
2581 SourceRange Range;
2582 SourceLocation DefaultLoc;
2583 LambdaCaptureDefault Default;
2584 SmallVector<LambdaCapture, 4> Captures;
2585
2586 LambdaIntroducer()
2587 : Default(LCD_None) {}
2588
2589 /// Append a capture in a lambda introducer.
2590 void addCapture(LambdaCaptureKind Kind,
2591 SourceLocation Loc,
2592 IdentifierInfo* Id,
2593 SourceLocation EllipsisLoc,
2594 LambdaCaptureInitKind InitKind,
2595 ExprResult Init,
2596 ParsedType InitCaptureType,
2597 SourceRange ExplicitRange) {
2598 Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
2599 InitCaptureType, ExplicitRange));
2600 }
2601};
2602
2603} // end namespace clang
2604
2605#endif // LLVM_CLANG_SEMA_DECLSPEC_H

/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/NestedNameSpecifier.h"
21#include "clang/AST/TemplateName.h"
22#include "clang/Basic/AddressSpaces.h"
23#include "clang/Basic/AttrKinds.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/ExceptionSpecificationType.h"
26#include "clang/Basic/LLVM.h"
27#include "clang/Basic/Linkage.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Basic/Visibility.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/APSInt.h"
34#include "llvm/ADT/ArrayRef.h"
35#include "llvm/ADT/FoldingSet.h"
36#include "llvm/ADT/None.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/Twine.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/type_traits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include <cassert>
50#include <cstddef>
51#include <cstdint>
52#include <cstring>
53#include <string>
54#include <type_traits>
55#include <utility>
56
57namespace clang {
58
59class ExtQuals;
60class QualType;
61class TagDecl;
62class Type;
63
64enum {
65 TypeAlignmentInBits = 4,
66 TypeAlignment = 1 << TypeAlignmentInBits
67};
68
69} // namespace clang
70
71namespace llvm {
72
73 template <typename T>
74 struct PointerLikeTypeTraits;
75 template<>
76 struct PointerLikeTypeTraits< ::clang::Type*> {
77 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
78
79 static inline ::clang::Type *getFromVoidPointer(void *P) {
80 return static_cast< ::clang::Type*>(P);
81 }
82
83 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
84 };
85
86 template<>
87 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
88 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
89
90 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
91 return static_cast< ::clang::ExtQuals*>(P);
92 }
93
94 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
95 };
96
97} // namespace llvm
98
99namespace clang {
100
101class ASTContext;
102template <typename> class CanQual;
103class CXXRecordDecl;
104class DeclContext;
105class EnumDecl;
106class Expr;
107class ExtQualsTypeCommonBase;
108class FunctionDecl;
109class IdentifierInfo;
110class NamedDecl;
111class ObjCInterfaceDecl;
112class ObjCProtocolDecl;
113class ObjCTypeParamDecl;
114struct PrintingPolicy;
115class RecordDecl;
116class Stmt;
117class TagDecl;
118class TemplateArgument;
119class TemplateArgumentListInfo;
120class TemplateArgumentLoc;
121class TemplateTypeParmDecl;
122class TypedefNameDecl;
123class UnresolvedUsingTypenameDecl;
124
125using CanQualType = CanQual<Type>;
126
127// Provide forward declarations for all of the *Type classes.
128#define TYPE(Class, Base) class Class##Type;
129#include "clang/AST/TypeNodes.inc"
130
131/// The collection of all-type qualifiers we support.
132/// Clang supports five independent qualifiers:
133/// * C99: const, volatile, and restrict
134/// * MS: __unaligned
135/// * Embedded C (TR18037): address spaces
136/// * Objective C: the GC attributes (none, weak, or strong)
137class Qualifiers {
138public:
139 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
140 Const = 0x1,
141 Restrict = 0x2,
142 Volatile = 0x4,
143 CVRMask = Const | Volatile | Restrict
144 };
145
146 enum GC {
147 GCNone = 0,
148 Weak,
149 Strong
150 };
151
152 enum ObjCLifetime {
153 /// There is no lifetime qualification on this type.
154 OCL_None,
155
156 /// This object can be modified without requiring retains or
157 /// releases.
158 OCL_ExplicitNone,
159
160 /// Assigning into this object requires the old value to be
161 /// released and the new value to be retained. The timing of the
162 /// release of the old value is inexact: it may be moved to
163 /// immediately after the last known point where the value is
164 /// live.
165 OCL_Strong,
166
167 /// Reading or writing from this object requires a barrier call.
168 OCL_Weak,
169
170 /// Assigning into this object requires a lifetime extension.
171 OCL_Autoreleasing
172 };
173
174 enum {
175 /// The maximum supported address space number.
176 /// 23 bits should be enough for anyone.
177 MaxAddressSpace = 0x7fffffu,
178
179 /// The width of the "fast" qualifier mask.
180 FastWidth = 3,
181
182 /// The fast qualifier mask.
183 FastMask = (1 << FastWidth) - 1
184 };
185
186 /// Returns the common set of qualifiers while removing them from
187 /// the given sets.
188 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
189 // If both are only CVR-qualified, bit operations are sufficient.
190 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
191 Qualifiers Q;
192 Q.Mask = L.Mask & R.Mask;
193 L.Mask &= ~Q.Mask;
194 R.Mask &= ~Q.Mask;
195 return Q;
196 }
197
198 Qualifiers Q;
199 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
200 Q.addCVRQualifiers(CommonCRV);
201 L.removeCVRQualifiers(CommonCRV);
202 R.removeCVRQualifiers(CommonCRV);
203
204 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
205 Q.setObjCGCAttr(L.getObjCGCAttr());
206 L.removeObjCGCAttr();
207 R.removeObjCGCAttr();
208 }
209
210 if (L.getObjCLifetime() == R.getObjCLifetime()) {
211 Q.setObjCLifetime(L.getObjCLifetime());
212 L.removeObjCLifetime();
213 R.removeObjCLifetime();
214 }
215
216 if (L.getAddressSpace() == R.getAddressSpace()) {
217 Q.setAddressSpace(L.getAddressSpace());
218 L.removeAddressSpace();
219 R.removeAddressSpace();
220 }
221 return Q;
222 }
223
224 static Qualifiers fromFastMask(unsigned Mask) {
225 Qualifiers Qs;
226 Qs.addFastQualifiers(Mask);
227 return Qs;
228 }
229
230 static Qualifiers fromCVRMask(unsigned CVR) {
231 Qualifiers Qs;
232 Qs.addCVRQualifiers(CVR);
233 return Qs;
234 }
235
236 static Qualifiers fromCVRUMask(unsigned CVRU) {
237 Qualifiers Qs;
238 Qs.addCVRUQualifiers(CVRU);
239 return Qs;
240 }
241
242 // Deserialize qualifiers from an opaque representation.
243 static Qualifiers fromOpaqueValue(unsigned opaque) {
244 Qualifiers Qs;
245 Qs.Mask = opaque;
246 return Qs;
247 }
248
249 // Serialize these qualifiers into an opaque representation.
250 unsigned getAsOpaqueValue() const {
251 return Mask;
252 }
253
254 bool hasConst() const { return Mask & Const; }
255 bool hasOnlyConst() const { return Mask == Const; }
256 void removeConst() { Mask &= ~Const; }
257 void addConst() { Mask |= Const; }
258
259 bool hasVolatile() const { return Mask & Volatile; }
260 bool hasOnlyVolatile() const { return Mask == Volatile; }
261 void removeVolatile() { Mask &= ~Volatile; }
262 void addVolatile() { Mask |= Volatile; }
263
264 bool hasRestrict() const { return Mask & Restrict; }
265 bool hasOnlyRestrict() const { return Mask == Restrict; }
266 void removeRestrict() { Mask &= ~Restrict; }
267 void addRestrict() { Mask |= Restrict; }
268
269 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
270 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
271 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
272
273 void setCVRQualifiers(unsigned mask) {
274 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 274, __PRETTY_FUNCTION__))
;
275 Mask = (Mask & ~CVRMask) | mask;
276 }
277 void removeCVRQualifiers(unsigned mask) {
278 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 278, __PRETTY_FUNCTION__))
;
279 Mask &= ~mask;
280 }
281 void removeCVRQualifiers() {
282 removeCVRQualifiers(CVRMask);
283 }
284 void addCVRQualifiers(unsigned mask) {
285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 285, __PRETTY_FUNCTION__))
;
286 Mask |= mask;
287 }
288 void addCVRUQualifiers(unsigned mask) {
289 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 289, __PRETTY_FUNCTION__))
;
290 Mask |= mask;
291 }
292
293 bool hasUnaligned() const { return Mask & UMask; }
294 void setUnaligned(bool flag) {
295 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
296 }
297 void removeUnaligned() { Mask &= ~UMask; }
298 void addUnaligned() { Mask |= UMask; }
299
300 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
301 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
302 void setObjCGCAttr(GC type) {
303 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
304 }
305 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
306 void addObjCGCAttr(GC type) {
307 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 307, __PRETTY_FUNCTION__))
;
308 setObjCGCAttr(type);
309 }
310 Qualifiers withoutObjCGCAttr() const {
311 Qualifiers qs = *this;
312 qs.removeObjCGCAttr();
313 return qs;
314 }
315 Qualifiers withoutObjCLifetime() const {
316 Qualifiers qs = *this;
317 qs.removeObjCLifetime();
318 return qs;
319 }
320 Qualifiers withoutAddressSpace() const {
321 Qualifiers qs = *this;
322 qs.removeAddressSpace();
323 return qs;
324 }
325
326 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
327 ObjCLifetime getObjCLifetime() const {
328 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
329 }
330 void setObjCLifetime(ObjCLifetime type) {
331 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
332 }
333 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
334 void addObjCLifetime(ObjCLifetime type) {
335 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 335, __PRETTY_FUNCTION__))
;
336 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 336, __PRETTY_FUNCTION__))
;
337 Mask |= (type << LifetimeShift);
338 }
339
340 /// True if the lifetime is neither None or ExplicitNone.
341 bool hasNonTrivialObjCLifetime() const {
342 ObjCLifetime lifetime = getObjCLifetime();
343 return (lifetime > OCL_ExplicitNone);
344 }
345
346 /// True if the lifetime is either strong or weak.
347 bool hasStrongOrWeakObjCLifetime() const {
348 ObjCLifetime lifetime = getObjCLifetime();
349 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
350 }
351
352 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
353 LangAS getAddressSpace() const {
354 return static_cast<LangAS>(Mask >> AddressSpaceShift);
355 }
356 bool hasTargetSpecificAddressSpace() const {
357 return isTargetAddressSpace(getAddressSpace());
358 }
359 /// Get the address space attribute value to be printed by diagnostics.
360 unsigned getAddressSpaceAttributePrintValue() const {
361 auto Addr = getAddressSpace();
362 // This function is not supposed to be used with language specific
363 // address spaces. If that happens, the diagnostic message should consider
364 // printing the QualType instead of the address space value.
365 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 365, __PRETTY_FUNCTION__))
;
366 if (Addr != LangAS::Default)
367 return toTargetAddressSpace(Addr);
368 // TODO: The diagnostic messages where Addr may be 0 should be fixed
369 // since it cannot differentiate the situation where 0 denotes the default
370 // address space or user specified __attribute__((address_space(0))).
371 return 0;
372 }
373 void setAddressSpace(LangAS space) {
374 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 374, __PRETTY_FUNCTION__))
;
375 Mask = (Mask & ~AddressSpaceMask)
376 | (((uint32_t) space) << AddressSpaceShift);
377 }
378 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
379 void addAddressSpace(LangAS space) {
380 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 380, __PRETTY_FUNCTION__))
;
381 setAddressSpace(space);
382 }
383
384 // Fast qualifiers are those that can be allocated directly
385 // on a QualType object.
386 bool hasFastQualifiers() const { return getFastQualifiers(); }
387 unsigned getFastQualifiers() const { return Mask & FastMask; }
388 void setFastQualifiers(unsigned mask) {
389 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 389, __PRETTY_FUNCTION__))
;
390 Mask = (Mask & ~FastMask) | mask;
391 }
392 void removeFastQualifiers(unsigned mask) {
393 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 393, __PRETTY_FUNCTION__))
;
394 Mask &= ~mask;
395 }
396 void removeFastQualifiers() {
397 removeFastQualifiers(FastMask);
398 }
399 void addFastQualifiers(unsigned mask) {
400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 400, __PRETTY_FUNCTION__))
;
401 Mask |= mask;
402 }
403
404 /// Return true if the set contains any qualifiers which require an ExtQuals
405 /// node to be allocated.
406 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
407 Qualifiers getNonFastQualifiers() const {
408 Qualifiers Quals = *this;
409 Quals.setFastQualifiers(0);
410 return Quals;
411 }
412
413 /// Return true if the set contains any qualifiers.
414 bool hasQualifiers() const { return Mask; }
415 bool empty() const { return !Mask; }
416
417 /// Add the qualifiers from the given set to this set.
418 void addQualifiers(Qualifiers Q) {
419 // If the other set doesn't have any non-boolean qualifiers, just
420 // bit-or it in.
421 if (!(Q.Mask & ~CVRMask))
422 Mask |= Q.Mask;
423 else {
424 Mask |= (Q.Mask & CVRMask);
425 if (Q.hasAddressSpace())
426 addAddressSpace(Q.getAddressSpace());
427 if (Q.hasObjCGCAttr())
428 addObjCGCAttr(Q.getObjCGCAttr());
429 if (Q.hasObjCLifetime())
430 addObjCLifetime(Q.getObjCLifetime());
431 }
432 }
433
434 /// Remove the qualifiers from the given set from this set.
435 void removeQualifiers(Qualifiers Q) {
436 // If the other set doesn't have any non-boolean qualifiers, just
437 // bit-and the inverse in.
438 if (!(Q.Mask & ~CVRMask))
439 Mask &= ~Q.Mask;
440 else {
441 Mask &= ~(Q.Mask & CVRMask);
442 if (getObjCGCAttr() == Q.getObjCGCAttr())
443 removeObjCGCAttr();
444 if (getObjCLifetime() == Q.getObjCLifetime())
445 removeObjCLifetime();
446 if (getAddressSpace() == Q.getAddressSpace())
447 removeAddressSpace();
448 }
449 }
450
451 /// Add the qualifiers from the given set to this set, given that
452 /// they don't conflict.
453 void addConsistentQualifiers(Qualifiers qs) {
454 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
455 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
;
456 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
457 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
;
458 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
459 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
;
460 Mask |= qs.Mask;
461 }
462
463 /// Returns true if address space A is equal to or a superset of B.
464 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
465 /// overlapping address spaces.
466 /// CL1.1 or CL1.2:
467 /// every address space is a superset of itself.
468 /// CL2.0 adds:
469 /// __generic is a superset of any address space except for __constant.
470 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
471 // Address spaces must match exactly.
472 return A == B ||
473 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
474 // for __constant can be used as __generic.
475 (A == LangAS::opencl_generic && B != LangAS::opencl_constant);
476 }
477
478 /// Returns true if the address space in these qualifiers is equal to or
479 /// a superset of the address space in the argument qualifiers.
480 bool isAddressSpaceSupersetOf(Qualifiers other) const {
481 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
482 }
483
484 /// Determines if these qualifiers compatibly include another set.
485 /// Generally this answers the question of whether an object with the other
486 /// qualifiers can be safely used as an object with these qualifiers.
487 bool compatiblyIncludes(Qualifiers other) const {
488 return isAddressSpaceSupersetOf(other) &&
489 // ObjC GC qualifiers can match, be added, or be removed, but can't
490 // be changed.
491 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
492 !other.hasObjCGCAttr()) &&
493 // ObjC lifetime qualifiers must match exactly.
494 getObjCLifetime() == other.getObjCLifetime() &&
495 // CVR qualifiers may subset.
496 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
497 // U qualifier may superset.
498 (!other.hasUnaligned() || hasUnaligned());
499 }
500
501 /// Determines if these qualifiers compatibly include another set of
502 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
503 ///
504 /// One set of Objective-C lifetime qualifiers compatibly includes the other
505 /// if the lifetime qualifiers match, or if both are non-__weak and the
506 /// including set also contains the 'const' qualifier, or both are non-__weak
507 /// and one is None (which can only happen in non-ARC modes).
508 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
509 if (getObjCLifetime() == other.getObjCLifetime())
510 return true;
511
512 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
513 return false;
514
515 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
516 return true;
517
518 return hasConst();
519 }
520
521 /// Determine whether this set of qualifiers is a strict superset of
522 /// another set of qualifiers, not considering qualifier compatibility.
523 bool isStrictSupersetOf(Qualifiers Other) const;
524
525 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
526 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
527
528 explicit operator bool() const { return hasQualifiers(); }
529
530 Qualifiers &operator+=(Qualifiers R) {
531 addQualifiers(R);
532 return *this;
533 }
534
535 // Union two qualifier sets. If an enumerated qualifier appears
536 // in both sets, use the one from the right.
537 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
538 L += R;
539 return L;
540 }
541
542 Qualifiers &operator-=(Qualifiers R) {
543 removeQualifiers(R);
544 return *this;
545 }
546
547 /// Compute the difference between two qualifier sets.
548 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
549 L -= R;
550 return L;
551 }
552
553 std::string getAsString() const;
554 std::string getAsString(const PrintingPolicy &Policy) const;
555
556 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
557 void print(raw_ostream &OS, const PrintingPolicy &Policy,
558 bool appendSpaceIfNonEmpty = false) const;
559
560 void Profile(llvm::FoldingSetNodeID &ID) const {
561 ID.AddInteger(Mask);
562 }
563
564private:
565 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
566 // |C R V|U|GCAttr|Lifetime|AddressSpace|
567 uint32_t Mask = 0;
568
569 static const uint32_t UMask = 0x8;
570 static const uint32_t UShift = 3;
571 static const uint32_t GCAttrMask = 0x30;
572 static const uint32_t GCAttrShift = 4;
573 static const uint32_t LifetimeMask = 0x1C0;
574 static const uint32_t LifetimeShift = 6;
575 static const uint32_t AddressSpaceMask =
576 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
577 static const uint32_t AddressSpaceShift = 9;
578};
579
580/// A std::pair-like structure for storing a qualified type split
581/// into its local qualifiers and its locally-unqualified type.
582struct SplitQualType {
583 /// The locally-unqualified type.
584 const Type *Ty = nullptr;
585
586 /// The local qualifiers.
587 Qualifiers Quals;
588
589 SplitQualType() = default;
590 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
591
592 SplitQualType getSingleStepDesugaredType() const; // end of this file
593
594 // Make std::tie work.
595 std::pair<const Type *,Qualifiers> asPair() const {
596 return std::pair<const Type *, Qualifiers>(Ty, Quals);
597 }
598
599 friend bool operator==(SplitQualType a, SplitQualType b) {
600 return a.Ty == b.Ty && a.Quals == b.Quals;
601 }
602 friend bool operator!=(SplitQualType a, SplitQualType b) {
603 return a.Ty != b.Ty || a.Quals != b.Quals;
604 }
605};
606
607/// The kind of type we are substituting Objective-C type arguments into.
608///
609/// The kind of substitution affects the replacement of type parameters when
610/// no concrete type information is provided, e.g., when dealing with an
611/// unspecialized type.
612enum class ObjCSubstitutionContext {
613 /// An ordinary type.
614 Ordinary,
615
616 /// The result type of a method or function.
617 Result,
618
619 /// The parameter type of a method or function.
620 Parameter,
621
622 /// The type of a property.
623 Property,
624
625 /// The superclass of a type.
626 Superclass,
627};
628
629/// A (possibly-)qualified type.
630///
631/// For efficiency, we don't store CV-qualified types as nodes on their
632/// own: instead each reference to a type stores the qualifiers. This
633/// greatly reduces the number of nodes we need to allocate for types (for
634/// example we only need one for 'int', 'const int', 'volatile int',
635/// 'const volatile int', etc).
636///
637/// As an added efficiency bonus, instead of making this a pair, we
638/// just store the two bits we care about in the low bits of the
639/// pointer. To handle the packing/unpacking, we make QualType be a
640/// simple wrapper class that acts like a smart pointer. A third bit
641/// indicates whether there are extended qualifiers present, in which
642/// case the pointer points to a special structure.
643class QualType {
644 friend class QualifierCollector;
645
646 // Thankfully, these are efficiently composable.
647 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
648 Qualifiers::FastWidth> Value;
649
650 const ExtQuals *getExtQualsUnsafe() const {
651 return Value.getPointer().get<const ExtQuals*>();
652 }
653
654 const Type *getTypePtrUnsafe() const {
655 return Value.getPointer().get<const Type*>();
656 }
657
658 const ExtQualsTypeCommonBase *getCommonPtr() const {
659 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 659, __PRETTY_FUNCTION__))
;
660 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
661 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
662 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
663 }
664
665public:
666 QualType() = default;
667 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
668 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
669
670 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
671 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
672
673 /// Retrieves a pointer to the underlying (unqualified) type.
674 ///
675 /// This function requires that the type not be NULL. If the type might be
676 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
677 const Type *getTypePtr() const;
678
679 const Type *getTypePtrOrNull() const;
680
681 /// Retrieves a pointer to the name of the base type.
682 const IdentifierInfo *getBaseTypeIdentifier() const;
683
684 /// Divides a QualType into its unqualified type and a set of local
685 /// qualifiers.
686 SplitQualType split() const;
687
688 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
689
690 static QualType getFromOpaquePtr(const void *Ptr) {
691 QualType T;
692 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
693 return T;
694 }
695
696 const Type &operator*() const {
697 return *getTypePtr();
698 }
699
700 const Type *operator->() const {
701 return getTypePtr();
702 }
703
704 bool isCanonical() const;
705 bool isCanonicalAsParam() const;
706
707 /// Return true if this QualType doesn't point to a type yet.
708 bool isNull() const {
709 return Value.getPointer().isNull();
710 }
711
712 /// Determine whether this particular QualType instance has the
713 /// "const" qualifier set, without looking through typedefs that may have
714 /// added "const" at a different level.
715 bool isLocalConstQualified() const {
716 return (getLocalFastQualifiers() & Qualifiers::Const);
717 }
718
719 /// Determine whether this type is const-qualified.
720 bool isConstQualified() const;
721
722 /// Determine whether this particular QualType instance has the
723 /// "restrict" qualifier set, without looking through typedefs that may have
724 /// added "restrict" at a different level.
725 bool isLocalRestrictQualified() const {
726 return (getLocalFastQualifiers() & Qualifiers::Restrict);
727 }
728
729 /// Determine whether this type is restrict-qualified.
730 bool isRestrictQualified() const;
731
732 /// Determine whether this particular QualType instance has the
733 /// "volatile" qualifier set, without looking through typedefs that may have
734 /// added "volatile" at a different level.
735 bool isLocalVolatileQualified() const {
736 return (getLocalFastQualifiers() & Qualifiers::Volatile);
737 }
738
739 /// Determine whether this type is volatile-qualified.
740 bool isVolatileQualified() const;
741
742 /// Determine whether this particular QualType instance has any
743 /// qualifiers, without looking through any typedefs that might add
744 /// qualifiers at a different level.
745 bool hasLocalQualifiers() const {
746 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
747 }
748
749 /// Determine whether this type has any qualifiers.
750 bool hasQualifiers() const;
751
752 /// Determine whether this particular QualType instance has any
753 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
754 /// instance.
755 bool hasLocalNonFastQualifiers() const {
756 return Value.getPointer().is<const ExtQuals*>();
757 }
758
759 /// Retrieve the set of qualifiers local to this particular QualType
760 /// instance, not including any qualifiers acquired through typedefs or
761 /// other sugar.
762 Qualifiers getLocalQualifiers() const;
763
764 /// Retrieve the set of qualifiers applied to this type.
765 Qualifiers getQualifiers() const;
766
767 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
768 /// local to this particular QualType instance, not including any qualifiers
769 /// acquired through typedefs or other sugar.
770 unsigned getLocalCVRQualifiers() const {
771 return getLocalFastQualifiers();
772 }
773
774 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
775 /// applied to this type.
776 unsigned getCVRQualifiers() const;
777
778 bool isConstant(const ASTContext& Ctx) const {
779 return QualType::isConstant(*this, Ctx);
780 }
781
782 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
783 bool isPODType(const ASTContext &Context) const;
784
785 /// Return true if this is a POD type according to the rules of the C++98
786 /// standard, regardless of the current compilation's language.
787 bool isCXX98PODType(const ASTContext &Context) const;
788
789 /// Return true if this is a POD type according to the more relaxed rules
790 /// of the C++11 standard, regardless of the current compilation's language.
791 /// (C++0x [basic.types]p9). Note that, unlike
792 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
793 bool isCXX11PODType(const ASTContext &Context) const;
794
795 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
796 bool isTrivialType(const ASTContext &Context) const;
797
798 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
799 bool isTriviallyCopyableType(const ASTContext &Context) const;
800
801
802 /// Returns true if it is a class and it might be dynamic.
803 bool mayBeDynamicClass() const;
804
805 /// Returns true if it is not a class or if the class might not be dynamic.
806 bool mayBeNotDynamicClass() const;
807
808 // Don't promise in the API that anything besides 'const' can be
809 // easily added.
810
811 /// Add the `const` type qualifier to this QualType.
812 void addConst() {
813 addFastQualifiers(Qualifiers::Const);
814 }
815 QualType withConst() const {
816 return withFastQualifiers(Qualifiers::Const);
817 }
818
819 /// Add the `volatile` type qualifier to this QualType.
820 void addVolatile() {
821 addFastQualifiers(Qualifiers::Volatile);
822 }
823 QualType withVolatile() const {
824 return withFastQualifiers(Qualifiers::Volatile);
825 }
826
827 /// Add the `restrict` qualifier to this QualType.
828 void addRestrict() {
829 addFastQualifiers(Qualifiers::Restrict);
830 }
831 QualType withRestrict() const {
832 return withFastQualifiers(Qualifiers::Restrict);
833 }
834
835 QualType withCVRQualifiers(unsigned CVR) const {
836 return withFastQualifiers(CVR);
837 }
838
839 void addFastQualifiers(unsigned TQs) {
840 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
841 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
;
842 Value.setInt(Value.getInt() | TQs);
843 }
844
845 void removeLocalConst();
846 void removeLocalVolatile();
847 void removeLocalRestrict();
848 void removeLocalCVRQualifiers(unsigned Mask);
849
850 void removeLocalFastQualifiers() { Value.setInt(0); }
851 void removeLocalFastQualifiers(unsigned Mask) {
852 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 852, __PRETTY_FUNCTION__))
;
853 Value.setInt(Value.getInt() & ~Mask);
854 }
855
856 // Creates a type with the given qualifiers in addition to any
857 // qualifiers already on this type.
858 QualType withFastQualifiers(unsigned TQs) const {
859 QualType T = *this;
860 T.addFastQualifiers(TQs);
861 return T;
862 }
863
864 // Creates a type with exactly the given fast qualifiers, removing
865 // any existing fast qualifiers.
866 QualType withExactLocalFastQualifiers(unsigned TQs) const {
867 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
868 }
869
870 // Removes fast qualifiers, but leaves any extended qualifiers in place.
871 QualType withoutLocalFastQualifiers() const {
872 QualType T = *this;
873 T.removeLocalFastQualifiers();
874 return T;
875 }
876
877 QualType getCanonicalType() const;
878
879 /// Return this type with all of the instance-specific qualifiers
880 /// removed, but without removing any qualifiers that may have been applied
881 /// through typedefs.
882 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
883
884 /// Retrieve the unqualified variant of the given type,
885 /// removing as little sugar as possible.
886 ///
887 /// This routine looks through various kinds of sugar to find the
888 /// least-desugared type that is unqualified. For example, given:
889 ///
890 /// \code
891 /// typedef int Integer;
892 /// typedef const Integer CInteger;
893 /// typedef CInteger DifferenceType;
894 /// \endcode
895 ///
896 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
897 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
898 ///
899 /// The resulting type might still be qualified if it's sugar for an array
900 /// type. To strip qualifiers even from within a sugared array type, use
901 /// ASTContext::getUnqualifiedArrayType.
902 inline QualType getUnqualifiedType() const;
903
904 /// Retrieve the unqualified variant of the given type, removing as little
905 /// sugar as possible.
906 ///
907 /// Like getUnqualifiedType(), but also returns the set of
908 /// qualifiers that were built up.
909 ///
910 /// The resulting type might still be qualified if it's sugar for an array
911 /// type. To strip qualifiers even from within a sugared array type, use
912 /// ASTContext::getUnqualifiedArrayType.
913 inline SplitQualType getSplitUnqualifiedType() const;
914
915 /// Determine whether this type is more qualified than the other
916 /// given type, requiring exact equality for non-CVR qualifiers.
917 bool isMoreQualifiedThan(QualType Other) const;
918
919 /// Determine whether this type is at least as qualified as the other
920 /// given type, requiring exact equality for non-CVR qualifiers.
921 bool isAtLeastAsQualifiedAs(QualType Other) const;
922
923 QualType getNonReferenceType() const;
924
925 /// Determine the type of a (typically non-lvalue) expression with the
926 /// specified result type.
927 ///
928 /// This routine should be used for expressions for which the return type is
929 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
930 /// an lvalue. It removes a top-level reference (since there are no
931 /// expressions of reference type) and deletes top-level cvr-qualifiers
932 /// from non-class types (in C++) or all types (in C).
933 QualType getNonLValueExprType(const ASTContext &Context) const;
934
935 /// Return the specified type with any "sugar" removed from
936 /// the type. This takes off typedefs, typeof's etc. If the outer level of
937 /// the type is already concrete, it returns it unmodified. This is similar
938 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
939 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
940 /// concrete.
941 ///
942 /// Qualifiers are left in place.
943 QualType getDesugaredType(const ASTContext &Context) const {
944 return getDesugaredType(*this, Context);
945 }
946
947 SplitQualType getSplitDesugaredType() const {
948 return getSplitDesugaredType(*this);
949 }
950
951 /// Return the specified type with one level of "sugar" removed from
952 /// the type.
953 ///
954 /// This routine takes off the first typedef, typeof, etc. If the outer level
955 /// of the type is already concrete, it returns it unmodified.
956 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
957 return getSingleStepDesugaredTypeImpl(*this, Context);
958 }
959
960 /// Returns the specified type after dropping any
961 /// outer-level parentheses.
962 QualType IgnoreParens() const {
963 if (isa<ParenType>(*this))
964 return QualType::IgnoreParens(*this);
965 return *this;
966 }
967
968 /// Indicate whether the specified types and qualifiers are identical.
969 friend bool operator==(const QualType &LHS, const QualType &RHS) {
970 return LHS.Value == RHS.Value;
971 }
972 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
973 return LHS.Value != RHS.Value;
974 }
975 friend bool operator<(const QualType &LHS, const QualType &RHS) {
976 return LHS.Value < RHS.Value;
977 }
978
979 static std::string getAsString(SplitQualType split,
980 const PrintingPolicy &Policy) {
981 return getAsString(split.Ty, split.Quals, Policy);
982 }
983 static std::string getAsString(const Type *ty, Qualifiers qs,
984 const PrintingPolicy &Policy);
985
986 std::string getAsString() const;
987 std::string getAsString(const PrintingPolicy &Policy) const;
988
989 void print(raw_ostream &OS, const PrintingPolicy &Policy,
990 const Twine &PlaceHolder = Twine(),
991 unsigned Indentation = 0) const;
992
993 static void print(SplitQualType split, raw_ostream &OS,
994 const PrintingPolicy &policy, const Twine &PlaceHolder,
995 unsigned Indentation = 0) {
996 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
997 }
998
999 static void print(const Type *ty, Qualifiers qs,
1000 raw_ostream &OS, const PrintingPolicy &policy,
1001 const Twine &PlaceHolder,
1002 unsigned Indentation = 0);
1003
1004 void getAsStringInternal(std::string &Str,
1005 const PrintingPolicy &Policy) const;
1006
1007 static void getAsStringInternal(SplitQualType split, std::string &out,
1008 const PrintingPolicy &policy) {
1009 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1010 }
1011
1012 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1013 std::string &out,
1014 const PrintingPolicy &policy);
1015
1016 class StreamedQualTypeHelper {
1017 const QualType &T;
1018 const PrintingPolicy &Policy;
1019 const Twine &PlaceHolder;
1020 unsigned Indentation;
1021
1022 public:
1023 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1024 const Twine &PlaceHolder, unsigned Indentation)
1025 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1026 Indentation(Indentation) {}
1027
1028 friend raw_ostream &operator<<(raw_ostream &OS,
1029 const StreamedQualTypeHelper &SQT) {
1030 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1031 return OS;
1032 }
1033 };
1034
1035 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1036 const Twine &PlaceHolder = Twine(),
1037 unsigned Indentation = 0) const {
1038 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1039 }
1040
1041 void dump(const char *s) const;
1042 void dump() const;
1043 void dump(llvm::raw_ostream &OS) const;
1044
1045 void Profile(llvm::FoldingSetNodeID &ID) const {
1046 ID.AddPointer(getAsOpaquePtr());
1047 }
1048
1049 /// Return the address space of this type.
1050 inline LangAS getAddressSpace() const;
1051
1052 /// Returns gc attribute of this type.
1053 inline Qualifiers::GC getObjCGCAttr() const;
1054
1055 /// true when Type is objc's weak.
1056 bool isObjCGCWeak() const {
1057 return getObjCGCAttr() == Qualifiers::Weak;
1058 }
1059
1060 /// true when Type is objc's strong.
1061 bool isObjCGCStrong() const {
1062 return getObjCGCAttr() == Qualifiers::Strong;
1063 }
1064
1065 /// Returns lifetime attribute of this type.
1066 Qualifiers::ObjCLifetime getObjCLifetime() const {
1067 return getQualifiers().getObjCLifetime();
1068 }
1069
1070 bool hasNonTrivialObjCLifetime() const {
1071 return getQualifiers().hasNonTrivialObjCLifetime();
1072 }
1073
1074 bool hasStrongOrWeakObjCLifetime() const {
1075 return getQualifiers().hasStrongOrWeakObjCLifetime();
1076 }
1077
1078 // true when Type is objc's weak and weak is enabled but ARC isn't.
1079 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1080
1081 enum PrimitiveDefaultInitializeKind {
1082 /// The type does not fall into any of the following categories. Note that
1083 /// this case is zero-valued so that values of this enum can be used as a
1084 /// boolean condition for non-triviality.
1085 PDIK_Trivial,
1086
1087 /// The type is an Objective-C retainable pointer type that is qualified
1088 /// with the ARC __strong qualifier.
1089 PDIK_ARCStrong,
1090
1091 /// The type is an Objective-C retainable pointer type that is qualified
1092 /// with the ARC __weak qualifier.
1093 PDIK_ARCWeak,
1094
1095 /// The type is a struct containing a field whose type is not PCK_Trivial.
1096 PDIK_Struct
1097 };
1098
1099 /// Functions to query basic properties of non-trivial C struct types.
1100
1101 /// Check if this is a non-trivial type that would cause a C struct
1102 /// transitively containing this type to be non-trivial to default initialize
1103 /// and return the kind.
1104 PrimitiveDefaultInitializeKind
1105 isNonTrivialToPrimitiveDefaultInitialize() const;
1106
1107 enum PrimitiveCopyKind {
1108 /// The type does not fall into any of the following categories. Note that
1109 /// this case is zero-valued so that values of this enum can be used as a
1110 /// boolean condition for non-triviality.
1111 PCK_Trivial,
1112
1113 /// The type would be trivial except that it is volatile-qualified. Types
1114 /// that fall into one of the other non-trivial cases may additionally be
1115 /// volatile-qualified.
1116 PCK_VolatileTrivial,
1117
1118 /// The type is an Objective-C retainable pointer type that is qualified
1119 /// with the ARC __strong qualifier.
1120 PCK_ARCStrong,
1121
1122 /// The type is an Objective-C retainable pointer type that is qualified
1123 /// with the ARC __weak qualifier.
1124 PCK_ARCWeak,
1125
1126 /// The type is a struct containing a field whose type is neither
1127 /// PCK_Trivial nor PCK_VolatileTrivial.
1128 /// Note that a C++ struct type does not necessarily match this; C++ copying
1129 /// semantics are too complex to express here, in part because they depend
1130 /// on the exact constructor or assignment operator that is chosen by
1131 /// overload resolution to do the copy.
1132 PCK_Struct
1133 };
1134
1135 /// Check if this is a non-trivial type that would cause a C struct
1136 /// transitively containing this type to be non-trivial to copy and return the
1137 /// kind.
1138 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1139
1140 /// Check if this is a non-trivial type that would cause a C struct
1141 /// transitively containing this type to be non-trivial to destructively
1142 /// move and return the kind. Destructive move in this context is a C++-style
1143 /// move in which the source object is placed in a valid but unspecified state
1144 /// after it is moved, as opposed to a truly destructive move in which the
1145 /// source object is placed in an uninitialized state.
1146 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1147
1148 enum DestructionKind {
1149 DK_none,
1150 DK_cxx_destructor,
1151 DK_objc_strong_lifetime,
1152 DK_objc_weak_lifetime,
1153 DK_nontrivial_c_struct
1154 };
1155
1156 /// Returns a nonzero value if objects of this type require
1157 /// non-trivial work to clean up after. Non-zero because it's
1158 /// conceivable that qualifiers (objc_gc(weak)?) could make
1159 /// something require destruction.
1160 DestructionKind isDestructedType() const {
1161 return isDestructedTypeImpl(*this);
1162 }
1163
1164 /// Check if this is or contains a C union that is non-trivial to
1165 /// default-initialize, which is a union that has a member that is non-trivial
1166 /// to default-initialize. If this returns true,
1167 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1168 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1169
1170 /// Check if this is or contains a C union that is non-trivial to destruct,
1171 /// which is a union that has a member that is non-trivial to destruct. If
1172 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1173 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1174
1175 /// Check if this is or contains a C union that is non-trivial to copy, which
1176 /// is a union that has a member that is non-trivial to copy. If this returns
1177 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1178 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1179
1180 /// Determine whether expressions of the given type are forbidden
1181 /// from being lvalues in C.
1182 ///
1183 /// The expression types that are forbidden to be lvalues are:
1184 /// - 'void', but not qualified void
1185 /// - function types
1186 ///
1187 /// The exact rule here is C99 6.3.2.1:
1188 /// An lvalue is an expression with an object type or an incomplete
1189 /// type other than void.
1190 bool isCForbiddenLValueType() const;
1191
1192 /// Substitute type arguments for the Objective-C type parameters used in the
1193 /// subject type.
1194 ///
1195 /// \param ctx ASTContext in which the type exists.
1196 ///
1197 /// \param typeArgs The type arguments that will be substituted for the
1198 /// Objective-C type parameters in the subject type, which are generally
1199 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1200 /// parameters will be replaced with their bounds or id/Class, as appropriate
1201 /// for the context.
1202 ///
1203 /// \param context The context in which the subject type was written.
1204 ///
1205 /// \returns the resulting type.
1206 QualType substObjCTypeArgs(ASTContext &ctx,
1207 ArrayRef<QualType> typeArgs,
1208 ObjCSubstitutionContext context) const;
1209
1210 /// Substitute type arguments from an object type for the Objective-C type
1211 /// parameters used in the subject type.
1212 ///
1213 /// This operation combines the computation of type arguments for
1214 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1215 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1216 /// callers that need to perform a single substitution in isolation.
1217 ///
1218 /// \param objectType The type of the object whose member type we're
1219 /// substituting into. For example, this might be the receiver of a message
1220 /// or the base of a property access.
1221 ///
1222 /// \param dc The declaration context from which the subject type was
1223 /// retrieved, which indicates (for example) which type parameters should
1224 /// be substituted.
1225 ///
1226 /// \param context The context in which the subject type was written.
1227 ///
1228 /// \returns the subject type after replacing all of the Objective-C type
1229 /// parameters with their corresponding arguments.
1230 QualType substObjCMemberType(QualType objectType,
1231 const DeclContext *dc,
1232 ObjCSubstitutionContext context) const;
1233
1234 /// Strip Objective-C "__kindof" types from the given type.
1235 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1236
1237 /// Remove all qualifiers including _Atomic.
1238 QualType getAtomicUnqualifiedType() const;
1239
1240private:
1241 // These methods are implemented in a separate translation unit;
1242 // "static"-ize them to avoid creating temporary QualTypes in the
1243 // caller.
1244 static bool isConstant(QualType T, const ASTContext& Ctx);
1245 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1246 static SplitQualType getSplitDesugaredType(QualType T);
1247 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1248 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1249 const ASTContext &C);
1250 static QualType IgnoreParens(QualType T);
1251 static DestructionKind isDestructedTypeImpl(QualType type);
1252
1253 /// Check if \param RD is or contains a non-trivial C union.
1254 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1255 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1256 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1257};
1258
1259} // namespace clang
1260
1261namespace llvm {
1262
1263/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1264/// to a specific Type class.
1265template<> struct simplify_type< ::clang::QualType> {
1266 using SimpleType = const ::clang::Type *;
1267
1268 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1269 return Val.getTypePtr();
1270 }
1271};
1272
1273// Teach SmallPtrSet that QualType is "basically a pointer".
1274template<>
1275struct PointerLikeTypeTraits<clang::QualType> {
1276 static inline void *getAsVoidPointer(clang::QualType P) {
1277 return P.getAsOpaquePtr();
1278 }
1279
1280 static inline clang::QualType getFromVoidPointer(void *P) {
1281 return clang::QualType::getFromOpaquePtr(P);
1282 }
1283
1284 // Various qualifiers go in low bits.
1285 enum { NumLowBitsAvailable = 0 };
1286};
1287
1288} // namespace llvm
1289
1290namespace clang {
1291
1292/// Base class that is common to both the \c ExtQuals and \c Type
1293/// classes, which allows \c QualType to access the common fields between the
1294/// two.
1295class ExtQualsTypeCommonBase {
1296 friend class ExtQuals;
1297 friend class QualType;
1298 friend class Type;
1299
1300 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1301 /// a self-referential pointer (for \c Type).
1302 ///
1303 /// This pointer allows an efficient mapping from a QualType to its
1304 /// underlying type pointer.
1305 const Type *const BaseType;
1306
1307 /// The canonical type of this type. A QualType.
1308 QualType CanonicalType;
1309
1310 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1311 : BaseType(baseType), CanonicalType(canon) {}
1312};
1313
1314/// We can encode up to four bits in the low bits of a
1315/// type pointer, but there are many more type qualifiers that we want
1316/// to be able to apply to an arbitrary type. Therefore we have this
1317/// struct, intended to be heap-allocated and used by QualType to
1318/// store qualifiers.
1319///
1320/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1321/// in three low bits on the QualType pointer; a fourth bit records whether
1322/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1323/// Objective-C GC attributes) are much more rare.
1324class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1325 // NOTE: changing the fast qualifiers should be straightforward as
1326 // long as you don't make 'const' non-fast.
1327 // 1. Qualifiers:
1328 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1329 // Fast qualifiers must occupy the low-order bits.
1330 // b) Update Qualifiers::FastWidth and FastMask.
1331 // 2. QualType:
1332 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1333 // b) Update remove{Volatile,Restrict}, defined near the end of
1334 // this header.
1335 // 3. ASTContext:
1336 // a) Update get{Volatile,Restrict}Type.
1337
1338 /// The immutable set of qualifiers applied by this node. Always contains
1339 /// extended qualifiers.
1340 Qualifiers Quals;
1341
1342 ExtQuals *this_() { return this; }
1343
1344public:
1345 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1346 : ExtQualsTypeCommonBase(baseType,
1347 canon.isNull() ? QualType(this_(), 0) : canon),
1348 Quals(quals) {
1349 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
1350 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
;
1351 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
1352 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
;
1353 }
1354
1355 Qualifiers getQualifiers() const { return Quals; }
1356
1357 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1358 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1359
1360 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1361 Qualifiers::ObjCLifetime getObjCLifetime() const {
1362 return Quals.getObjCLifetime();
1363 }
1364
1365 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1366 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1367
1368 const Type *getBaseType() const { return BaseType; }
1369
1370public:
1371 void Profile(llvm::FoldingSetNodeID &ID) const {
1372 Profile(ID, getBaseType(), Quals);
1373 }
1374
1375 static void Profile(llvm::FoldingSetNodeID &ID,
1376 const Type *BaseType,
1377 Qualifiers Quals) {
1378 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 1378, __PRETTY_FUNCTION__))
;
1379 ID.AddPointer(BaseType);
1380 Quals.Profile(ID);
1381 }
1382};
1383
1384/// The kind of C++11 ref-qualifier associated with a function type.
1385/// This determines whether a member function's "this" object can be an
1386/// lvalue, rvalue, or neither.
1387enum RefQualifierKind {
1388 /// No ref-qualifier was provided.
1389 RQ_None = 0,
1390
1391 /// An lvalue ref-qualifier was provided (\c &).
1392 RQ_LValue,
1393
1394 /// An rvalue ref-qualifier was provided (\c &&).
1395 RQ_RValue
1396};
1397
1398/// Which keyword(s) were used to create an AutoType.
1399enum class AutoTypeKeyword {
1400 /// auto
1401 Auto,
1402
1403 /// decltype(auto)
1404 DecltypeAuto,
1405
1406 /// __auto_type (GNU extension)
1407 GNUAutoType
1408};
1409
1410/// The base class of the type hierarchy.
1411///
1412/// A central concept with types is that each type always has a canonical
1413/// type. A canonical type is the type with any typedef names stripped out
1414/// of it or the types it references. For example, consider:
1415///
1416/// typedef int foo;
1417/// typedef foo* bar;
1418/// 'int *' 'foo *' 'bar'
1419///
1420/// There will be a Type object created for 'int'. Since int is canonical, its
1421/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1422/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1423/// there is a PointerType that represents 'int*', which, like 'int', is
1424/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1425/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1426/// is also 'int*'.
1427///
1428/// Non-canonical types are useful for emitting diagnostics, without losing
1429/// information about typedefs being used. Canonical types are useful for type
1430/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1431/// about whether something has a particular form (e.g. is a function type),
1432/// because they implicitly, recursively, strip all typedefs out of a type.
1433///
1434/// Types, once created, are immutable.
1435///
1436class alignas(8) Type : public ExtQualsTypeCommonBase {
1437public:
1438 enum TypeClass {
1439#define TYPE(Class, Base) Class,
1440#define LAST_TYPE(Class) TypeLast = Class
1441#define ABSTRACT_TYPE(Class, Base)
1442#include "clang/AST/TypeNodes.inc"
1443 };
1444
1445private:
1446 /// Bitfields required by the Type class.
1447 class TypeBitfields {
1448 friend class Type;
1449 template <class T> friend class TypePropertyCache;
1450
1451 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1452 unsigned TC : 8;
1453
1454 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1455 unsigned Dependent : 1;
1456
1457 /// Whether this type somehow involves a template parameter, even
1458 /// if the resolution of the type does not depend on a template parameter.
1459 unsigned InstantiationDependent : 1;
1460
1461 /// Whether this type is a variably-modified type (C99 6.7.5).
1462 unsigned VariablyModified : 1;
1463
1464 /// Whether this type contains an unexpanded parameter pack
1465 /// (for C++11 variadic templates).
1466 unsigned ContainsUnexpandedParameterPack : 1;
1467
1468 /// True if the cache (i.e. the bitfields here starting with
1469 /// 'Cache') is valid.
1470 mutable unsigned CacheValid : 1;
1471
1472 /// Linkage of this type.
1473 mutable unsigned CachedLinkage : 3;
1474
1475 /// Whether this type involves and local or unnamed types.
1476 mutable unsigned CachedLocalOrUnnamed : 1;
1477
1478 /// Whether this type comes from an AST file.
1479 mutable unsigned FromAST : 1;
1480
1481 bool isCacheValid() const {
1482 return CacheValid;
1483 }
1484
1485 Linkage getLinkage() const {
1486 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 1486, __PRETTY_FUNCTION__))
;
1487 return static_cast<Linkage>(CachedLinkage);
1488 }
1489
1490 bool hasLocalOrUnnamedType() const {
1491 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 1491, __PRETTY_FUNCTION__))
;
1492 return CachedLocalOrUnnamed;
1493 }
1494 };
1495 enum { NumTypeBits = 18 };
1496
1497protected:
1498 // These classes allow subclasses to somewhat cleanly pack bitfields
1499 // into Type.
1500
1501 class ArrayTypeBitfields {
1502 friend class ArrayType;
1503
1504 unsigned : NumTypeBits;
1505
1506 /// CVR qualifiers from declarations like
1507 /// 'int X[static restrict 4]'. For function parameters only.
1508 unsigned IndexTypeQuals : 3;
1509
1510 /// Storage class qualifiers from declarations like
1511 /// 'int X[static restrict 4]'. For function parameters only.
1512 /// Actually an ArrayType::ArraySizeModifier.
1513 unsigned SizeModifier : 3;
1514 };
1515
1516 class ConstantArrayTypeBitfields {
1517 friend class ConstantArrayType;
1518
1519 unsigned : NumTypeBits + 3 + 3;
1520
1521 /// Whether we have a stored size expression.
1522 unsigned HasStoredSizeExpr : 1;
1523 };
1524
1525 class BuiltinTypeBitfields {
1526 friend class BuiltinType;
1527
1528 unsigned : NumTypeBits;
1529
1530 /// The kind (BuiltinType::Kind) of builtin type this is.
1531 unsigned Kind : 8;
1532 };
1533
1534 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1535 /// Only common bits are stored here. Additional uncommon bits are stored
1536 /// in a trailing object after FunctionProtoType.
1537 class FunctionTypeBitfields {
1538 friend class FunctionProtoType;
1539 friend class FunctionType;
1540
1541 unsigned : NumTypeBits;
1542
1543 /// Extra information which affects how the function is called, like
1544 /// regparm and the calling convention.
1545 unsigned ExtInfo : 12;
1546
1547 /// The ref-qualifier associated with a \c FunctionProtoType.
1548 ///
1549 /// This is a value of type \c RefQualifierKind.
1550 unsigned RefQualifier : 2;
1551
1552 /// Used only by FunctionProtoType, put here to pack with the
1553 /// other bitfields.
1554 /// The qualifiers are part of FunctionProtoType because...
1555 ///
1556 /// C++ 8.3.5p4: The return type, the parameter type list and the
1557 /// cv-qualifier-seq, [...], are part of the function type.
1558 unsigned FastTypeQuals : Qualifiers::FastWidth;
1559 /// Whether this function has extended Qualifiers.
1560 unsigned HasExtQuals : 1;
1561
1562 /// The number of parameters this function has, not counting '...'.
1563 /// According to [implimits] 8 bits should be enough here but this is
1564 /// somewhat easy to exceed with metaprogramming and so we would like to
1565 /// keep NumParams as wide as reasonably possible.
1566 unsigned NumParams : 16;
1567
1568 /// The type of exception specification this function has.
1569 unsigned ExceptionSpecType : 4;
1570
1571 /// Whether this function has extended parameter information.
1572 unsigned HasExtParameterInfos : 1;
1573
1574 /// Whether the function is variadic.
1575 unsigned Variadic : 1;
1576
1577 /// Whether this function has a trailing return type.
1578 unsigned HasTrailingReturn : 1;
1579 };
1580
1581 class ObjCObjectTypeBitfields {
1582 friend class ObjCObjectType;
1583
1584 unsigned : NumTypeBits;
1585
1586 /// The number of type arguments stored directly on this object type.
1587 unsigned NumTypeArgs : 7;
1588
1589 /// The number of protocols stored directly on this object type.
1590 unsigned NumProtocols : 6;
1591
1592 /// Whether this is a "kindof" type.
1593 unsigned IsKindOf : 1;
1594 };
1595
1596 class ReferenceTypeBitfields {
1597 friend class ReferenceType;
1598
1599 unsigned : NumTypeBits;
1600
1601 /// True if the type was originally spelled with an lvalue sigil.
1602 /// This is never true of rvalue references but can also be false
1603 /// on lvalue references because of C++0x [dcl.typedef]p9,
1604 /// as follows:
1605 ///
1606 /// typedef int &ref; // lvalue, spelled lvalue
1607 /// typedef int &&rvref; // rvalue
1608 /// ref &a; // lvalue, inner ref, spelled lvalue
1609 /// ref &&a; // lvalue, inner ref
1610 /// rvref &a; // lvalue, inner ref, spelled lvalue
1611 /// rvref &&a; // rvalue, inner ref
1612 unsigned SpelledAsLValue : 1;
1613
1614 /// True if the inner type is a reference type. This only happens
1615 /// in non-canonical forms.
1616 unsigned InnerRef : 1;
1617 };
1618
1619 class TypeWithKeywordBitfields {
1620 friend class TypeWithKeyword;
1621
1622 unsigned : NumTypeBits;
1623
1624 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1625 unsigned Keyword : 8;
1626 };
1627
1628 enum { NumTypeWithKeywordBits = 8 };
1629
1630 class ElaboratedTypeBitfields {
1631 friend class ElaboratedType;
1632
1633 unsigned : NumTypeBits;
1634 unsigned : NumTypeWithKeywordBits;
1635
1636 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1637 unsigned HasOwnedTagDecl : 1;
1638 };
1639
1640 class VectorTypeBitfields {
1641 friend class VectorType;
1642 friend class DependentVectorType;
1643
1644 unsigned : NumTypeBits;
1645
1646 /// The kind of vector, either a generic vector type or some
1647 /// target-specific vector type such as for AltiVec or Neon.
1648 unsigned VecKind : 3;
1649
1650 /// The number of elements in the vector.
1651 unsigned NumElements : 29 - NumTypeBits;
1652
1653 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1654 };
1655
1656 class AttributedTypeBitfields {
1657 friend class AttributedType;
1658
1659 unsigned : NumTypeBits;
1660
1661 /// An AttributedType::Kind
1662 unsigned AttrKind : 32 - NumTypeBits;
1663 };
1664
1665 class AutoTypeBitfields {
1666 friend class AutoType;
1667
1668 unsigned : NumTypeBits;
1669
1670 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1671 /// or '__auto_type'? AutoTypeKeyword value.
1672 unsigned Keyword : 2;
1673 };
1674
1675 class SubstTemplateTypeParmPackTypeBitfields {
1676 friend class SubstTemplateTypeParmPackType;
1677
1678 unsigned : NumTypeBits;
1679
1680 /// The number of template arguments in \c Arguments, which is
1681 /// expected to be able to hold at least 1024 according to [implimits].
1682 /// However as this limit is somewhat easy to hit with template
1683 /// metaprogramming we'd prefer to keep it as large as possible.
1684 /// At the moment it has been left as a non-bitfield since this type
1685 /// safely fits in 64 bits as an unsigned, so there is no reason to
1686 /// introduce the performance impact of a bitfield.
1687 unsigned NumArgs;
1688 };
1689
1690 class TemplateSpecializationTypeBitfields {
1691 friend class TemplateSpecializationType;
1692
1693 unsigned : NumTypeBits;
1694
1695 /// Whether this template specialization type is a substituted type alias.
1696 unsigned TypeAlias : 1;
1697
1698 /// The number of template arguments named in this class template
1699 /// specialization, which is expected to be able to hold at least 1024
1700 /// according to [implimits]. However, as this limit is somewhat easy to
1701 /// hit with template metaprogramming we'd prefer to keep it as large
1702 /// as possible. At the moment it has been left as a non-bitfield since
1703 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1704 /// to introduce the performance impact of a bitfield.
1705 unsigned NumArgs;
1706 };
1707
1708 class DependentTemplateSpecializationTypeBitfields {
1709 friend class DependentTemplateSpecializationType;
1710
1711 unsigned : NumTypeBits;
1712 unsigned : NumTypeWithKeywordBits;
1713
1714 /// The number of template arguments named in this class template
1715 /// specialization, which is expected to be able to hold at least 1024
1716 /// according to [implimits]. However, as this limit is somewhat easy to
1717 /// hit with template metaprogramming we'd prefer to keep it as large
1718 /// as possible. At the moment it has been left as a non-bitfield since
1719 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1720 /// to introduce the performance impact of a bitfield.
1721 unsigned NumArgs;
1722 };
1723
1724 class PackExpansionTypeBitfields {
1725 friend class PackExpansionType;
1726
1727 unsigned : NumTypeBits;
1728
1729 /// The number of expansions that this pack expansion will
1730 /// generate when substituted (+1), which is expected to be able to
1731 /// hold at least 1024 according to [implimits]. However, as this limit
1732 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1733 /// keep it as large as possible. At the moment it has been left as a
1734 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1735 /// there is no reason to introduce the performance impact of a bitfield.
1736 ///
1737 /// This field will only have a non-zero value when some of the parameter
1738 /// packs that occur within the pattern have been substituted but others
1739 /// have not.
1740 unsigned NumExpansions;
1741 };
1742
1743 union {
1744 TypeBitfields TypeBits;
1745 ArrayTypeBitfields ArrayTypeBits;
1746 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1747 AttributedTypeBitfields AttributedTypeBits;
1748 AutoTypeBitfields AutoTypeBits;
1749 BuiltinTypeBitfields BuiltinTypeBits;
1750 FunctionTypeBitfields FunctionTypeBits;
1751 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1752 ReferenceTypeBitfields ReferenceTypeBits;
1753 TypeWithKeywordBitfields TypeWithKeywordBits;
1754 ElaboratedTypeBitfields ElaboratedTypeBits;
1755 VectorTypeBitfields VectorTypeBits;
1756 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1757 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1758 DependentTemplateSpecializationTypeBitfields
1759 DependentTemplateSpecializationTypeBits;
1760 PackExpansionTypeBitfields PackExpansionTypeBits;
1761
1762 static_assert(sizeof(TypeBitfields) <= 8,
1763 "TypeBitfields is larger than 8 bytes!");
1764 static_assert(sizeof(ArrayTypeBitfields) <= 8,
1765 "ArrayTypeBitfields is larger than 8 bytes!");
1766 static_assert(sizeof(AttributedTypeBitfields) <= 8,
1767 "AttributedTypeBitfields is larger than 8 bytes!");
1768 static_assert(sizeof(AutoTypeBitfields) <= 8,
1769 "AutoTypeBitfields is larger than 8 bytes!");
1770 static_assert(sizeof(BuiltinTypeBitfields) <= 8,
1771 "BuiltinTypeBitfields is larger than 8 bytes!");
1772 static_assert(sizeof(FunctionTypeBitfields) <= 8,
1773 "FunctionTypeBitfields is larger than 8 bytes!");
1774 static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
1775 "ObjCObjectTypeBitfields is larger than 8 bytes!");
1776 static_assert(sizeof(ReferenceTypeBitfields) <= 8,
1777 "ReferenceTypeBitfields is larger than 8 bytes!");
1778 static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
1779 "TypeWithKeywordBitfields is larger than 8 bytes!");
1780 static_assert(sizeof(ElaboratedTypeBitfields) <= 8,
1781 "ElaboratedTypeBitfields is larger than 8 bytes!");
1782 static_assert(sizeof(VectorTypeBitfields) <= 8,
1783 "VectorTypeBitfields is larger than 8 bytes!");
1784 static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8,
1785 "SubstTemplateTypeParmPackTypeBitfields is larger"
1786 " than 8 bytes!");
1787 static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8,
1788 "TemplateSpecializationTypeBitfields is larger"
1789 " than 8 bytes!");
1790 static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8,
1791 "DependentTemplateSpecializationTypeBitfields is larger"
1792 " than 8 bytes!");
1793 static_assert(sizeof(PackExpansionTypeBitfields) <= 8,
1794 "PackExpansionTypeBitfields is larger than 8 bytes");
1795 };
1796
1797private:
1798 template <class T> friend class TypePropertyCache;
1799
1800 /// Set whether this type comes from an AST file.
1801 void setFromAST(bool V = true) const {
1802 TypeBits.FromAST = V;
1803 }
1804
1805protected:
1806 friend class ASTContext;
1807
1808 Type(TypeClass tc, QualType canon, bool Dependent,
1809 bool InstantiationDependent, bool VariablyModified,
1810 bool ContainsUnexpandedParameterPack)
1811 : ExtQualsTypeCommonBase(this,
1812 canon.isNull() ? QualType(this_(), 0) : canon) {
1813 TypeBits.TC = tc;
1814 TypeBits.Dependent = Dependent;
1815 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1816 TypeBits.VariablyModified = VariablyModified;
1817 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1818 TypeBits.CacheValid = false;
1819 TypeBits.CachedLocalOrUnnamed = false;
1820 TypeBits.CachedLinkage = NoLinkage;
1821 TypeBits.FromAST = false;
1822 }
1823
1824 // silence VC++ warning C4355: 'this' : used in base member initializer list
1825 Type *this_() { return this; }
1826
1827 void setDependent(bool D = true) {
1828 TypeBits.Dependent = D;
1829 if (D)
1830 TypeBits.InstantiationDependent = true;
1831 }
1832
1833 void setInstantiationDependent(bool D = true) {
1834 TypeBits.InstantiationDependent = D; }
1835
1836 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1837
1838 void setContainsUnexpandedParameterPack(bool PP = true) {
1839 TypeBits.ContainsUnexpandedParameterPack = PP;
1840 }
1841
1842public:
1843 friend class ASTReader;
1844 friend class ASTWriter;
1845
1846 Type(const Type &) = delete;
1847 Type(Type &&) = delete;
1848 Type &operator=(const Type &) = delete;
1849 Type &operator=(Type &&) = delete;
1850
1851 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1852
1853 /// Whether this type comes from an AST file.
1854 bool isFromAST() const { return TypeBits.FromAST; }
1855
1856 /// Whether this type is or contains an unexpanded parameter
1857 /// pack, used to support C++0x variadic templates.
1858 ///
1859 /// A type that contains a parameter pack shall be expanded by the
1860 /// ellipsis operator at some point. For example, the typedef in the
1861 /// following example contains an unexpanded parameter pack 'T':
1862 ///
1863 /// \code
1864 /// template<typename ...T>
1865 /// struct X {
1866 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1867 /// };
1868 /// \endcode
1869 ///
1870 /// Note that this routine does not specify which
1871 bool containsUnexpandedParameterPack() const {
1872 return TypeBits.ContainsUnexpandedParameterPack;
1873 }
1874
1875 /// Determines if this type would be canonical if it had no further
1876 /// qualification.
1877 bool isCanonicalUnqualified() const {
1878 return CanonicalType == QualType(this, 0);
1879 }
1880
1881 /// Pull a single level of sugar off of this locally-unqualified type.
1882 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1883 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1884 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1885
1886 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1887 /// object types, function types, and incomplete types.
1888
1889 /// Return true if this is an incomplete type.
1890 /// A type that can describe objects, but which lacks information needed to
1891 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1892 /// routine will need to determine if the size is actually required.
1893 ///
1894 /// Def If non-null, and the type refers to some kind of declaration
1895 /// that can be completed (such as a C struct, C++ class, or Objective-C
1896 /// class), will be set to the declaration.
1897 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1898
1899 /// Return true if this is an incomplete or object
1900 /// type, in other words, not a function type.
1901 bool isIncompleteOrObjectType() const {
1902 return !isFunctionType();
1903 }
1904
1905 /// Determine whether this type is an object type.
1906 bool isObjectType() const {
1907 // C++ [basic.types]p8:
1908 // An object type is a (possibly cv-qualified) type that is not a
1909 // function type, not a reference type, and not a void type.
1910 return !isReferenceType() && !isFunctionType() && !isVoidType();
1911 }
1912
1913 /// Return true if this is a literal type
1914 /// (C++11 [basic.types]p10)
1915 bool isLiteralType(const ASTContext &Ctx) const;
1916
1917 /// Test if this type is a standard-layout type.
1918 /// (C++0x [basic.type]p9)
1919 bool isStandardLayoutType() const;
1920
1921 /// Helper methods to distinguish type categories. All type predicates
1922 /// operate on the canonical type, ignoring typedefs and qualifiers.
1923
1924 /// Returns true if the type is a builtin type.
1925 bool isBuiltinType() const;
1926
1927 /// Test for a particular builtin type.
1928 bool isSpecificBuiltinType(unsigned K) const;
1929
1930 /// Test for a type which does not represent an actual type-system type but
1931 /// is instead used as a placeholder for various convenient purposes within
1932 /// Clang. All such types are BuiltinTypes.
1933 bool isPlaceholderType() const;
1934 const BuiltinType *getAsPlaceholderType() const;
1935
1936 /// Test for a specific placeholder type.
1937 bool isSpecificPlaceholderType(unsigned K) const;
1938
1939 /// Test for a placeholder type other than Overload; see
1940 /// BuiltinType::isNonOverloadPlaceholderType.
1941 bool isNonOverloadPlaceholderType() const;
1942
1943 /// isIntegerType() does *not* include complex integers (a GCC extension).
1944 /// isComplexIntegerType() can be used to test for complex integers.
1945 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1946 bool isEnumeralType() const;
1947
1948 /// Determine whether this type is a scoped enumeration type.
1949 bool isScopedEnumeralType() const;
1950 bool isBooleanType() const;
1951 bool isCharType() const;
1952 bool isWideCharType() const;
1953 bool isChar8Type() const;
1954 bool isChar16Type() const;
1955 bool isChar32Type() const;
1956 bool isAnyCharacterType() const;
1957 bool isIntegralType(const ASTContext &Ctx) const;
1958
1959 /// Determine whether this type is an integral or enumeration type.
1960 bool isIntegralOrEnumerationType() const;
1961
1962 /// Determine whether this type is an integral or unscoped enumeration type.
1963 bool isIntegralOrUnscopedEnumerationType() const;
1964
1965 /// Floating point categories.
1966 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1967 /// isComplexType() does *not* include complex integers (a GCC extension).
1968 /// isComplexIntegerType() can be used to test for complex integers.
1969 bool isComplexType() const; // C99 6.2.5p11 (complex)
1970 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1971 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1972 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1973 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1974 bool isFloat128Type() const;
1975 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1976 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1977 bool isVoidType() const; // C99 6.2.5p19
1978 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1979 bool isAggregateType() const;
1980 bool isFundamentalType() const;
1981 bool isCompoundType() const;
1982
1983 // Type Predicates: Check to see if this type is structurally the specified
1984 // type, ignoring typedefs and qualifiers.
1985 bool isFunctionType() const;
1986 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1987 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1988 bool isPointerType() const;
1989 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1990 bool isBlockPointerType() const;
1991 bool isVoidPointerType() const;
1992 bool isReferenceType() const;
1993 bool isLValueReferenceType() const;
1994 bool isRValueReferenceType() const;
1995 bool isFunctionPointerType() const;
1996 bool isFunctionReferenceType() const;
1997 bool isMemberPointerType() const;
1998 bool isMemberFunctionPointerType() const;
1999 bool isMemberDataPointerType() const;
2000 bool isArrayType() const;
2001 bool isConstantArrayType() const;
2002 bool isIncompleteArrayType() const;
2003 bool isVariableArrayType() const;
2004 bool isDependentSizedArrayType() const;
2005 bool isRecordType() const;
2006 bool isClassType() const;
2007 bool isStructureType() const;
2008 bool isObjCBoxableRecordType() const;
2009 bool isInterfaceType() const;
2010 bool isStructureOrClassType() const;
2011 bool isUnionType() const;
2012 bool isComplexIntegerType() const; // GCC _Complex integer type.
2013 bool isVectorType() const; // GCC vector type.
2014 bool isExtVectorType() const; // Extended vector type.
2015 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2016 bool isObjCObjectPointerType() const; // pointer to ObjC object
2017 bool isObjCRetainableType() const; // ObjC object or block pointer
2018 bool isObjCLifetimeType() const; // (array of)* retainable type
2019 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2020 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2021 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2022 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2023 // for the common case.
2024 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2025 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2026 bool isObjCQualifiedIdType() const; // id<foo>
2027 bool isObjCQualifiedClassType() const; // Class<foo>
2028 bool isObjCObjectOrInterfaceType() const;
2029 bool isObjCIdType() const; // id
2030 bool isDecltypeType() const;
2031 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2032 /// qualifier?
2033 ///
2034 /// This approximates the answer to the following question: if this
2035 /// translation unit were compiled in ARC, would this type be qualified
2036 /// with __unsafe_unretained?
2037 bool isObjCInertUnsafeUnretainedType() const {
2038 return hasAttr(attr::ObjCInertUnsafeUnretained);
2039 }
2040
2041 /// Whether the type is Objective-C 'id' or a __kindof type of an
2042 /// object type, e.g., __kindof NSView * or __kindof id
2043 /// <NSCopying>.
2044 ///
2045 /// \param bound Will be set to the bound on non-id subtype types,
2046 /// which will be (possibly specialized) Objective-C class type, or
2047 /// null for 'id.
2048 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2049 const ObjCObjectType *&bound) const;
2050
2051 bool isObjCClassType() const; // Class
2052
2053 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2054 /// Class type, e.g., __kindof Class <NSCopying>.
2055 ///
2056 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2057 /// here because Objective-C's type system cannot express "a class
2058 /// object for a subclass of NSFoo".
2059 bool isObjCClassOrClassKindOfType() const;
2060
2061 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2062 bool isObjCSelType() const; // Class
2063 bool isObjCBuiltinType() const; // 'id' or 'Class'
2064 bool isObjCARCBridgableType() const;
2065 bool isCARCBridgableType() const;
2066 bool isTemplateTypeParmType() const; // C++ template type parameter
2067 bool isNullPtrType() const; // C++11 std::nullptr_t
2068 bool isNothrowT() const; // C++ std::nothrow_t
2069 bool isAlignValT() const; // C++17 std::align_val_t
2070 bool isStdByteType() const; // C++17 std::byte
2071 bool isAtomicType() const; // C11 _Atomic()
2072
2073#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2074 bool is##Id##Type() const;
2075#include "clang/Basic/OpenCLImageTypes.def"
2076
2077 bool isImageType() const; // Any OpenCL image type
2078
2079 bool isSamplerT() const; // OpenCL sampler_t
2080 bool isEventT() const; // OpenCL event_t
2081 bool isClkEventT() const; // OpenCL clk_event_t
2082 bool isQueueT() const; // OpenCL queue_t
2083 bool isReserveIDT() const; // OpenCL reserve_id_t
2084
2085#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2086 bool is##Id##Type() const;
2087#include "clang/Basic/OpenCLExtensionTypes.def"
2088 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2089 bool isOCLIntelSubgroupAVCType() const;
2090 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2091
2092 bool isPipeType() const; // OpenCL pipe type
2093 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2094
2095 /// Determines if this type, which must satisfy
2096 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2097 /// than implicitly __strong.
2098 bool isObjCARCImplicitlyUnretainedType() const;
2099
2100 /// Return the implicit lifetime for this type, which must not be dependent.
2101 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2102
2103 enum ScalarTypeKind {
2104 STK_CPointer,
2105 STK_BlockPointer,
2106 STK_ObjCObjectPointer,
2107 STK_MemberPointer,
2108 STK_Bool,
2109 STK_Integral,
2110 STK_Floating,
2111 STK_IntegralComplex,
2112 STK_FloatingComplex,
2113 STK_FixedPoint
2114 };
2115
2116 /// Given that this is a scalar type, classify it.
2117 ScalarTypeKind getScalarTypeKind() const;
2118
2119 /// Whether this type is a dependent type, meaning that its definition
2120 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2121 bool isDependentType() const { return TypeBits.Dependent; }
2122
2123 /// Determine whether this type is an instantiation-dependent type,
2124 /// meaning that the type involves a template parameter (even if the
2125 /// definition does not actually depend on the type substituted for that
2126 /// template parameter).
2127 bool isInstantiationDependentType() const {
2128 return TypeBits.InstantiationDependent;
2129 }
2130
2131 /// Determine whether this type is an undeduced type, meaning that
2132 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2133 /// deduced.
2134 bool isUndeducedType() const;
2135
2136 /// Whether this type is a variably-modified type (C99 6.7.5).
2137 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
2138
2139 /// Whether this type involves a variable-length array type
2140 /// with a definite size.
2141 bool hasSizedVLAType() const;
2142
2143 /// Whether this type is or contains a local or unnamed type.
2144 bool hasUnnamedOrLocalType() const;
2145
2146 bool isOverloadableType() const;
2147
2148 /// Determine wither this type is a C++ elaborated-type-specifier.
2149 bool isElaboratedTypeSpecifier() const;
2150
2151 bool canDecayToPointerType() const;
2152
2153 /// Whether this type is represented natively as a pointer. This includes
2154 /// pointers, references, block pointers, and Objective-C interface,
2155 /// qualified id, and qualified interface types, as well as nullptr_t.
2156 bool hasPointerRepresentation() const;
2157
2158 /// Whether this type can represent an objective pointer type for the
2159 /// purpose of GC'ability
2160 bool hasObjCPointerRepresentation() const;
2161
2162 /// Determine whether this type has an integer representation
2163 /// of some sort, e.g., it is an integer type or a vector.
2164 bool hasIntegerRepresentation() const;
2165
2166 /// Determine whether this type has an signed integer representation
2167 /// of some sort, e.g., it is an signed integer type or a vector.
2168 bool hasSignedIntegerRepresentation() const;
2169
2170 /// Determine whether this type has an unsigned integer representation
2171 /// of some sort, e.g., it is an unsigned integer type or a vector.
2172 bool hasUnsignedIntegerRepresentation() const;
2173
2174 /// Determine whether this type has a floating-point representation
2175 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2176 bool hasFloatingRepresentation() const;
2177
2178 // Type Checking Functions: Check to see if this type is structurally the
2179 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2180 // the best type we can.
2181 const RecordType *getAsStructureType() const;
2182 /// NOTE: getAs*ArrayType are methods on ASTContext.
2183 const RecordType *getAsUnionType() const;
2184 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2185 const ObjCObjectType *getAsObjCInterfaceType() const;
2186
2187 // The following is a convenience method that returns an ObjCObjectPointerType
2188 // for object declared using an interface.
2189 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2190 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2191 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2192 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2193
2194 /// Retrieves the CXXRecordDecl that this type refers to, either
2195 /// because the type is a RecordType or because it is the injected-class-name
2196 /// type of a class template or class template partial specialization.
2197 CXXRecordDecl *getAsCXXRecordDecl() const;
2198
2199 /// Retrieves the RecordDecl this type refers to.
2200 RecordDecl *getAsRecordDecl() const;
2201
2202 /// Retrieves the TagDecl that this type refers to, either
2203 /// because the type is a TagType or because it is the injected-class-name
2204 /// type of a class template or class template partial specialization.
2205 TagDecl *getAsTagDecl() const;
2206
2207 /// If this is a pointer or reference to a RecordType, return the
2208 /// CXXRecordDecl that the type refers to.
2209 ///
2210 /// If this is not a pointer or reference, or the type being pointed to does
2211 /// not refer to a CXXRecordDecl, returns NULL.
2212 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2213
2214 /// Get the DeducedType whose type will be deduced for a variable with
2215 /// an initializer of this type. This looks through declarators like pointer
2216 /// types, but not through decltype or typedefs.
2217 DeducedType *getContainedDeducedType() const;
2218
2219 /// Get the AutoType whose type will be deduced for a variable with
2220 /// an initializer of this type. This looks through declarators like pointer
2221 /// types, but not through decltype or typedefs.
2222 AutoType *getContainedAutoType() const {
2223 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2224 }
2225
2226 /// Determine whether this type was written with a leading 'auto'
2227 /// corresponding to a trailing return type (possibly for a nested
2228 /// function type within a pointer to function type or similar).
2229 bool hasAutoForTrailingReturnType() const;
2230
2231 /// Member-template getAs<specific type>'. Look through sugar for
2232 /// an instance of \<specific type>. This scheme will eventually
2233 /// replace the specific getAsXXXX methods above.
2234 ///
2235 /// There are some specializations of this member template listed
2236 /// immediately following this class.
2237 template <typename T> const T *getAs() const;
2238
2239 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2240 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2241 /// This is used when you need to walk over sugar nodes that represent some
2242 /// kind of type adjustment from a type that was written as a \<specific type>
2243 /// to another type that is still canonically a \<specific type>.
2244 template <typename T> const T *getAsAdjusted() const;
2245
2246 /// A variant of getAs<> for array types which silently discards
2247 /// qualifiers from the outermost type.
2248 const ArrayType *getAsArrayTypeUnsafe() const;
2249
2250 /// Member-template castAs<specific type>. Look through sugar for
2251 /// the underlying instance of \<specific type>.
2252 ///
2253 /// This method has the same relationship to getAs<T> as cast<T> has
2254 /// to dyn_cast<T>; which is to say, the underlying type *must*
2255 /// have the intended type, and this method will never return null.
2256 template <typename T> const T *castAs() const;
2257
2258 /// A variant of castAs<> for array type which silently discards
2259 /// qualifiers from the outermost type.
2260 const ArrayType *castAsArrayTypeUnsafe() const;
2261
2262 /// Determine whether this type had the specified attribute applied to it
2263 /// (looking through top-level type sugar).
2264 bool hasAttr(attr::Kind AK) const;
2265
2266 /// Get the base element type of this type, potentially discarding type
2267 /// qualifiers. This should never be used when type qualifiers
2268 /// are meaningful.
2269 const Type *getBaseElementTypeUnsafe() const;
2270
2271 /// If this is an array type, return the element type of the array,
2272 /// potentially with type qualifiers missing.
2273 /// This should never be used when type qualifiers are meaningful.
2274 const Type *getArrayElementTypeNoTypeQual() const;
2275
2276 /// If this is a pointer type, return the pointee type.
2277 /// If this is an array type, return the array element type.
2278 /// This should never be used when type qualifiers are meaningful.
2279 const Type *getPointeeOrArrayElementType() const;
2280
2281 /// If this is a pointer, ObjC object pointer, or block
2282 /// pointer, this returns the respective pointee.
2283 QualType getPointeeType() const;
2284
2285 /// Return the specified type with any "sugar" removed from the type,
2286 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2287 const Type *getUnqualifiedDesugaredType() const;
2288
2289 /// More type predicates useful for type checking/promotion
2290 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2291
2292 /// Return true if this is an integer type that is
2293 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2294 /// or an enum decl which has a signed representation.
2295 bool isSignedIntegerType() const;
2296
2297 /// Return true if this is an integer type that is
2298 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2299 /// or an enum decl which has an unsigned representation.
2300 bool isUnsignedIntegerType() const;
2301
2302 /// Determines whether this is an integer type that is signed or an
2303 /// enumeration types whose underlying type is a signed integer type.
2304 bool isSignedIntegerOrEnumerationType() const;
2305
2306 /// Determines whether this is an integer type that is unsigned or an
2307 /// enumeration types whose underlying type is a unsigned integer type.
2308 bool isUnsignedIntegerOrEnumerationType() const;
2309
2310 /// Return true if this is a fixed point type according to
2311 /// ISO/IEC JTC1 SC22 WG14 N1169.
2312 bool isFixedPointType() const;
2313
2314 /// Return true if this is a fixed point or integer type.
2315 bool isFixedPointOrIntegerType() const;
2316
2317 /// Return true if this is a saturated fixed point type according to
2318 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2319 bool isSaturatedFixedPointType() const;
2320
2321 /// Return true if this is a saturated fixed point type according to
2322 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2323 bool isUnsaturatedFixedPointType() const;
2324
2325 /// Return true if this is a fixed point type that is signed according
2326 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2327 bool isSignedFixedPointType() const;
2328
2329 /// Return true if this is a fixed point type that is unsigned according
2330 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2331 bool isUnsignedFixedPointType() const;
2332
2333 /// Return true if this is not a variable sized type,
2334 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2335 /// incomplete types.
2336 bool isConstantSizeType() const;
2337
2338 /// Returns true if this type can be represented by some
2339 /// set of type specifiers.
2340 bool isSpecifierType() const;
2341
2342 /// Determine the linkage of this type.
2343 Linkage getLinkage() const;
2344
2345 /// Determine the visibility of this type.
2346 Visibility getVisibility() const {
2347 return getLinkageAndVisibility().getVisibility();
2348 }
2349
2350 /// Return true if the visibility was explicitly set is the code.
2351 bool isVisibilityExplicit() const {
2352 return getLinkageAndVisibility().isVisibilityExplicit();
2353 }
2354
2355 /// Determine the linkage and visibility of this type.
2356 LinkageInfo getLinkageAndVisibility() const;
2357
2358 /// True if the computed linkage is valid. Used for consistency
2359 /// checking. Should always return true.
2360 bool isLinkageValid() const;
2361
2362 /// Determine the nullability of the given type.
2363 ///
2364 /// Note that nullability is only captured as sugar within the type
2365 /// system, not as part of the canonical type, so nullability will
2366 /// be lost by canonicalization and desugaring.
2367 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2368
2369 /// Determine whether the given type can have a nullability
2370 /// specifier applied to it, i.e., if it is any kind of pointer type.
2371 ///
2372 /// \param ResultIfUnknown The value to return if we don't yet know whether
2373 /// this type can have nullability because it is dependent.
2374 bool canHaveNullability(bool ResultIfUnknown = true) const;
2375
2376 /// Retrieve the set of substitutions required when accessing a member
2377 /// of the Objective-C receiver type that is declared in the given context.
2378 ///
2379 /// \c *this is the type of the object we're operating on, e.g., the
2380 /// receiver for a message send or the base of a property access, and is
2381 /// expected to be of some object or object pointer type.
2382 ///
2383 /// \param dc The declaration context for which we are building up a
2384 /// substitution mapping, which should be an Objective-C class, extension,
2385 /// category, or method within.
2386 ///
2387 /// \returns an array of type arguments that can be substituted for
2388 /// the type parameters of the given declaration context in any type described
2389 /// within that context, or an empty optional to indicate that no
2390 /// substitution is required.
2391 Optional<ArrayRef<QualType>>
2392 getObjCSubstitutions(const DeclContext *dc) const;
2393
2394 /// Determines if this is an ObjC interface type that may accept type
2395 /// parameters.
2396 bool acceptsObjCTypeParams() const;
2397
2398 const char *getTypeClassName() const;
2399
2400 QualType getCanonicalTypeInternal() const {
2401 return CanonicalType;
2402 }
2403
2404 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2405 void dump() const;
2406 void dump(llvm::raw_ostream &OS) const;
2407};
2408
2409/// This will check for a TypedefType by removing any existing sugar
2410/// until it reaches a TypedefType or a non-sugared type.
2411template <> const TypedefType *Type::getAs() const;
2412
2413/// This will check for a TemplateSpecializationType by removing any
2414/// existing sugar until it reaches a TemplateSpecializationType or a
2415/// non-sugared type.
2416template <> const TemplateSpecializationType *Type::getAs() const;
2417
2418/// This will check for an AttributedType by removing any existing sugar
2419/// until it reaches an AttributedType or a non-sugared type.
2420template <> const AttributedType *Type::getAs() const;
2421
2422// We can do canonical leaf types faster, because we don't have to
2423// worry about preserving child type decoration.
2424#define TYPE(Class, Base)
2425#define LEAF_TYPE(Class) \
2426template <> inline const Class##Type *Type::getAs() const { \
2427 return dyn_cast<Class##Type>(CanonicalType); \
2428} \
2429template <> inline const Class##Type *Type::castAs() const { \
2430 return cast<Class##Type>(CanonicalType); \
2431}
2432#include "clang/AST/TypeNodes.inc"
2433
2434/// This class is used for builtin types like 'int'. Builtin
2435/// types are always canonical and have a literal name field.
2436class BuiltinType : public Type {
2437public:
2438 enum Kind {
2439// OpenCL image types
2440#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2441#include "clang/Basic/OpenCLImageTypes.def"
2442// OpenCL extension types
2443#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2444#include "clang/Basic/OpenCLExtensionTypes.def"
2445// SVE Types
2446#define SVE_TYPE(Name, Id, SingletonId) Id,
2447#include "clang/Basic/AArch64SVEACLETypes.def"
2448// All other builtin types
2449#define BUILTIN_TYPE(Id, SingletonId) Id,
2450#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2451#include "clang/AST/BuiltinTypes.def"
2452 };
2453
2454private:
2455 friend class ASTContext; // ASTContext creates these.
2456
2457 BuiltinType(Kind K)
2458 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2459 /*InstantiationDependent=*/(K == Dependent),
2460 /*VariablyModified=*/false,
2461 /*Unexpanded parameter pack=*/false) {
2462 BuiltinTypeBits.Kind = K;
2463 }
2464
2465public:
2466 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2467 StringRef getName(const PrintingPolicy &Policy) const;
2468
2469 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2470 // The StringRef is null-terminated.
2471 StringRef str = getName(Policy);
2472 assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast
<void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 2472, __PRETTY_FUNCTION__))
;
2473 return str.data();
2474 }
2475
2476 bool isSugared() const { return false; }
2477 QualType desugar() const { return QualType(this, 0); }
2478
2479 bool isInteger() const {
2480 return getKind() >= Bool && getKind() <= Int128;
2481 }
2482
2483 bool isSignedInteger() const {
2484 return getKind() >= Char_S && getKind() <= Int128;
2485 }
2486
2487 bool isUnsignedInteger() const {
2488 return getKind() >= Bool && getKind() <= UInt128;
2489 }
2490
2491 bool isFloatingPoint() const {
2492 return getKind() >= Half && getKind() <= Float128;
2493 }
2494
2495 /// Determines whether the given kind corresponds to a placeholder type.
2496 static bool isPlaceholderTypeKind(Kind K) {
2497 return K >= Overload;
2498 }
2499
2500 /// Determines whether this type is a placeholder type, i.e. a type
2501 /// which cannot appear in arbitrary positions in a fully-formed
2502 /// expression.
2503 bool isPlaceholderType() const {
2504 return isPlaceholderTypeKind(getKind());
2505 }
2506
2507 /// Determines whether this type is a placeholder type other than
2508 /// Overload. Most placeholder types require only syntactic
2509 /// information about their context in order to be resolved (e.g.
2510 /// whether it is a call expression), which means they can (and
2511 /// should) be resolved in an earlier "phase" of analysis.
2512 /// Overload expressions sometimes pick up further information
2513 /// from their context, like whether the context expects a
2514 /// specific function-pointer type, and so frequently need
2515 /// special treatment.
2516 bool isNonOverloadPlaceholderType() const {
2517 return getKind() > Overload;
2518 }
2519
2520 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2521};
2522
2523/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2524/// types (_Complex float etc) as well as the GCC integer complex extensions.
2525class ComplexType : public Type, public llvm::FoldingSetNode {
2526 friend class ASTContext; // ASTContext creates these.
2527
2528 QualType ElementType;
2529
2530 ComplexType(QualType Element, QualType CanonicalPtr)
2531 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2532 Element->isInstantiationDependentType(),
2533 Element->isVariablyModifiedType(),
2534 Element->containsUnexpandedParameterPack()),
2535 ElementType(Element) {}
2536
2537public:
2538 QualType getElementType() const { return ElementType; }
2539
2540 bool isSugared() const { return false; }
2541 QualType desugar() const { return QualType(this, 0); }
2542
2543 void Profile(llvm::FoldingSetNodeID &ID) {
2544 Profile(ID, getElementType());
2545 }
2546
2547 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2548 ID.AddPointer(Element.getAsOpaquePtr());
2549 }
2550
2551 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2552};
2553
2554/// Sugar for parentheses used when specifying types.
2555class ParenType : public Type, public llvm::FoldingSetNode {
2556 friend class ASTContext; // ASTContext creates these.
2557
2558 QualType Inner;
2559
2560 ParenType(QualType InnerType, QualType CanonType)
2561 : Type(Paren, CanonType, InnerType->isDependentType(),
2562 InnerType->isInstantiationDependentType(),
2563 InnerType->isVariablyModifiedType(),
2564 InnerType->containsUnexpandedParameterPack()),
2565 Inner(InnerType) {}
2566
2567public:
2568 QualType getInnerType() const { return Inner; }
2569
2570 bool isSugared() const { return true; }
2571 QualType desugar() const { return getInnerType(); }
2572
2573 void Profile(llvm::FoldingSetNodeID &ID) {
2574 Profile(ID, getInnerType());
2575 }
2576
2577 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2578 Inner.Profile(ID);
2579 }
2580
2581 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2582};
2583
2584/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2585class PointerType : public Type, public llvm::FoldingSetNode {
2586 friend class ASTContext; // ASTContext creates these.
2587
2588 QualType PointeeType;
2589
2590 PointerType(QualType Pointee, QualType CanonicalPtr)
2591 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2592 Pointee->isInstantiationDependentType(),
2593 Pointee->isVariablyModifiedType(),
2594 Pointee->containsUnexpandedParameterPack()),
2595 PointeeType(Pointee) {}
2596
2597public:
2598 QualType getPointeeType() const { return PointeeType; }
2599
2600 /// Returns true if address spaces of pointers overlap.
2601 /// OpenCL v2.0 defines conversion rules for pointers to different
2602 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2603 /// address spaces.
2604 /// CL1.1 or CL1.2:
2605 /// address spaces overlap iff they are they same.
2606 /// CL2.0 adds:
2607 /// __generic overlaps with any address space except for __constant.
2608 bool isAddressSpaceOverlapping(const PointerType &other) const {
2609 Qualifiers thisQuals = PointeeType.getQualifiers();
2610 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2611 // Address spaces overlap if at least one of them is a superset of another
2612 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2613 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2614 }
2615
2616 bool isSugared() const { return false; }
2617 QualType desugar() const { return QualType(this, 0); }
2618
2619 void Profile(llvm::FoldingSetNodeID &ID) {
2620 Profile(ID, getPointeeType());
2621 }
2622
2623 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2624 ID.AddPointer(Pointee.getAsOpaquePtr());
2625 }
2626
2627 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2628};
2629
2630/// Represents a type which was implicitly adjusted by the semantic
2631/// engine for arbitrary reasons. For example, array and function types can
2632/// decay, and function types can have their calling conventions adjusted.
2633class AdjustedType : public Type, public llvm::FoldingSetNode {
2634 QualType OriginalTy;
2635 QualType AdjustedTy;
2636
2637protected:
2638 friend class ASTContext; // ASTContext creates these.
2639
2640 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2641 QualType CanonicalPtr)
2642 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2643 OriginalTy->isInstantiationDependentType(),
2644 OriginalTy->isVariablyModifiedType(),
2645 OriginalTy->containsUnexpandedParameterPack()),
2646 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2647
2648public:
2649 QualType getOriginalType() const { return OriginalTy; }
2650 QualType getAdjustedType() const { return AdjustedTy; }
2651
2652 bool isSugared() const { return true; }
2653 QualType desugar() const { return AdjustedTy; }
2654
2655 void Profile(llvm::FoldingSetNodeID &ID) {
2656 Profile(ID, OriginalTy, AdjustedTy);
2657 }
2658
2659 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2660 ID.AddPointer(Orig.getAsOpaquePtr());
2661 ID.AddPointer(New.getAsOpaquePtr());
2662 }
2663
2664 static bool classof(const Type *T) {
2665 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2666 }
2667};
2668
2669/// Represents a pointer type decayed from an array or function type.
2670class DecayedType : public AdjustedType {
2671 friend class ASTContext; // ASTContext creates these.
2672
2673 inline
2674 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2675
2676public:
2677 QualType getDecayedType() const { return getAdjustedType(); }
2678
2679 inline QualType getPointeeType() const;
2680
2681 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2682};
2683
2684/// Pointer to a block type.
2685/// This type is to represent types syntactically represented as
2686/// "void (^)(int)", etc. Pointee is required to always be a function type.
2687class BlockPointerType : public Type, public llvm::FoldingSetNode {
2688 friend class ASTContext; // ASTContext creates these.
2689
2690 // Block is some kind of pointer type
2691 QualType PointeeType;
2692
2693 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2694 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2695 Pointee->isInstantiationDependentType(),
2696 Pointee->isVariablyModifiedType(),
2697 Pointee->containsUnexpandedParameterPack()),
2698 PointeeType(Pointee) {}
2699
2700public:
2701 // Get the pointee type. Pointee is required to always be a function type.
2702 QualType getPointeeType() const { return PointeeType; }
2703
2704 bool isSugared() const { return false; }
2705 QualType desugar() const { return QualType(this, 0); }
2706
2707 void Profile(llvm::FoldingSetNodeID &ID) {
2708 Profile(ID, getPointeeType());
2709 }
2710
2711 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2712 ID.AddPointer(Pointee.getAsOpaquePtr());
2713 }
2714
2715 static bool classof(const Type *T) {
2716 return T->getTypeClass() == BlockPointer;
2717 }
2718};
2719
2720/// Base for LValueReferenceType and RValueReferenceType
2721class ReferenceType : public Type, public llvm::FoldingSetNode {
2722 QualType PointeeType;
2723
2724protected:
2725 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2726 bool SpelledAsLValue)
2727 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2728 Referencee->isInstantiationDependentType(),
2729 Referencee->isVariablyModifiedType(),
2730 Referencee->containsUnexpandedParameterPack()),
2731 PointeeType(Referencee) {
2732 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2733 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2734 }
2735
2736public:
2737 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2738 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2739
2740 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2741
2742 QualType getPointeeType() const {
2743 // FIXME: this might strip inner qualifiers; okay?
2744 const ReferenceType *T = this;
2745 while (T->isInnerRef())
2746 T = T->PointeeType->castAs<ReferenceType>();
2747 return T->PointeeType;
2748 }
2749
2750 void Profile(llvm::FoldingSetNodeID &ID) {
2751 Profile(ID, PointeeType, isSpelledAsLValue());
2752 }
2753
2754 static void Profile(llvm::FoldingSetNodeID &ID,
2755 QualType Referencee,
2756 bool SpelledAsLValue) {
2757 ID.AddPointer(Referencee.getAsOpaquePtr());
2758 ID.AddBoolean(SpelledAsLValue);
2759 }
2760
2761 static bool classof(const Type *T) {
2762 return T->getTypeClass() == LValueReference ||
2763 T->getTypeClass() == RValueReference;
2764 }
2765};
2766
2767/// An lvalue reference type, per C++11 [dcl.ref].
2768class LValueReferenceType : public ReferenceType {
2769 friend class ASTContext; // ASTContext creates these
2770
2771 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2772 bool SpelledAsLValue)
2773 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2774 SpelledAsLValue) {}
2775
2776public:
2777 bool isSugared() const { return false; }
2778 QualType desugar() const { return QualType(this, 0); }
2779
2780 static bool classof(const Type *T) {
2781 return T->getTypeClass() == LValueReference;
2782 }
2783};
2784
2785/// An rvalue reference type, per C++11 [dcl.ref].
2786class RValueReferenceType : public ReferenceType {
2787 friend class ASTContext; // ASTContext creates these
2788
2789 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2790 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2791
2792public:
2793 bool isSugared() const { return false; }
2794 QualType desugar() const { return QualType(this, 0); }
2795
2796 static bool classof(const Type *T) {
2797 return T->getTypeClass() == RValueReference;
2798 }
2799};
2800
2801/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2802///
2803/// This includes both pointers to data members and pointer to member functions.
2804class MemberPointerType : public Type, public llvm::FoldingSetNode {
2805 friend class ASTContext; // ASTContext creates these.
2806
2807 QualType PointeeType;
2808
2809 /// The class of which the pointee is a member. Must ultimately be a
2810 /// RecordType, but could be a typedef or a template parameter too.
2811 const Type *Class;
2812
2813 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2814 : Type(MemberPointer, CanonicalPtr,
2815 Cls->isDependentType() || Pointee->isDependentType(),
2816 (Cls->isInstantiationDependentType() ||
2817 Pointee->isInstantiationDependentType()),
2818 Pointee->isVariablyModifiedType(),
2819 (Cls->containsUnexpandedParameterPack() ||
2820 Pointee->containsUnexpandedParameterPack())),
2821 PointeeType(Pointee), Class(Cls) {}
2822
2823public:
2824 QualType getPointeeType() const { return PointeeType; }
2825
2826 /// Returns true if the member type (i.e. the pointee type) is a
2827 /// function type rather than a data-member type.
2828 bool isMemberFunctionPointer() const {
2829 return PointeeType->isFunctionProtoType();
2830 }
2831
2832 /// Returns true if the member type (i.e. the pointee type) is a
2833 /// data type rather than a function type.
2834 bool isMemberDataPointer() const {
2835 return !PointeeType->isFunctionProtoType();
2836 }
2837
2838 const Type *getClass() const { return Class; }
2839 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2840
2841 bool isSugared() const { return false; }
2842 QualType desugar() const { return QualType(this, 0); }
2843
2844 void Profile(llvm::FoldingSetNodeID &ID) {
2845 Profile(ID, getPointeeType(), getClass());
2846 }
2847
2848 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2849 const Type *Class) {
2850 ID.AddPointer(Pointee.getAsOpaquePtr());
2851 ID.AddPointer(Class);
2852 }
2853
2854 static bool classof(const Type *T) {
2855 return T->getTypeClass() == MemberPointer;
2856 }
2857};
2858
2859/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2860class ArrayType : public Type, public llvm::FoldingSetNode {
2861public:
2862 /// Capture whether this is a normal array (e.g. int X[4])
2863 /// an array with a static size (e.g. int X[static 4]), or an array
2864 /// with a star size (e.g. int X[*]).
2865 /// 'static' is only allowed on function parameters.
2866 enum ArraySizeModifier {
2867 Normal, Static, Star
2868 };
2869
2870private:
2871 /// The element type of the array.
2872 QualType ElementType;
2873
2874protected:
2875 friend class ASTContext; // ASTContext creates these.
2876
2877 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2878 unsigned tq, const Expr *sz = nullptr);
2879
2880public:
2881 QualType getElementType() const { return ElementType; }
2882
2883 ArraySizeModifier getSizeModifier() const {
2884 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2885 }
2886
2887 Qualifiers getIndexTypeQualifiers() const {
2888 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2889 }
2890
2891 unsigned getIndexTypeCVRQualifiers() const {
2892 return ArrayTypeBits.IndexTypeQuals;
2893 }
2894
2895 static bool classof(const Type *T) {
2896 return T->getTypeClass() == ConstantArray ||
2897 T->getTypeClass() == VariableArray ||
2898 T->getTypeClass() == IncompleteArray ||
2899 T->getTypeClass() == DependentSizedArray;
2900 }
2901};
2902
2903/// Represents the canonical version of C arrays with a specified constant size.
2904/// For example, the canonical type for 'int A[4 + 4*100]' is a
2905/// ConstantArrayType where the element type is 'int' and the size is 404.
2906class ConstantArrayType final
2907 : public ArrayType,
2908 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2909 friend class ASTContext; // ASTContext creates these.
2910 friend TrailingObjects;
2911
2912 llvm::APInt Size; // Allows us to unique the type.
2913
2914 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2915 const Expr *sz, ArraySizeModifier sm, unsigned tq)
2916 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2917 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2918 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2919 assert(!can.isNull() && "canonical constant array should not have size")((!can.isNull() && "canonical constant array should not have size"
) ? static_cast<void> (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 2919, __PRETTY_FUNCTION__))
;
2920 *getTrailingObjects<const Expr*>() = sz;
2921 }
2922 }
2923
2924 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2925 return ConstantArrayTypeBits.HasStoredSizeExpr;
2926 }
2927
2928public:
2929 const llvm::APInt &getSize() const { return Size; }
2930 const Expr *getSizeExpr() const {
2931 return ConstantArrayTypeBits.HasStoredSizeExpr
2932 ? *getTrailingObjects<const Expr *>()
2933 : nullptr;
2934 }
2935 bool isSugared() const { return false; }
2936 QualType desugar() const { return QualType(this, 0); }
2937
2938 /// Determine the number of bits required to address a member of
2939 // an array with the given element type and number of elements.
2940 static unsigned getNumAddressingBits(const ASTContext &Context,
2941 QualType ElementType,
2942 const llvm::APInt &NumElements);
2943
2944 /// Determine the maximum number of active bits that an array's size
2945 /// can require, which limits the maximum size of the array.
2946 static unsigned getMaxSizeBits(const ASTContext &Context);
2947
2948 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
2949 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
2950 getSizeModifier(), getIndexTypeCVRQualifiers());
2951 }
2952
2953 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
2954 QualType ET, const llvm::APInt &ArraySize,
2955 const Expr *SizeExpr, ArraySizeModifier SizeMod,
2956 unsigned TypeQuals);
2957
2958 static bool classof(const Type *T) {
2959 return T->getTypeClass() == ConstantArray;
2960 }
2961};
2962
2963/// Represents a C array with an unspecified size. For example 'int A[]' has
2964/// an IncompleteArrayType where the element type is 'int' and the size is
2965/// unspecified.
2966class IncompleteArrayType : public ArrayType {
2967 friend class ASTContext; // ASTContext creates these.
2968
2969 IncompleteArrayType(QualType et, QualType can,
2970 ArraySizeModifier sm, unsigned tq)
2971 : ArrayType(IncompleteArray, et, can, sm, tq) {}
2972
2973public:
2974 friend class StmtIteratorBase;
2975
2976 bool isSugared() const { return false; }
2977 QualType desugar() const { return QualType(this, 0); }
2978
2979 static bool classof(const Type *T) {
2980 return T->getTypeClass() == IncompleteArray;
2981 }
2982
2983 void Profile(llvm::FoldingSetNodeID &ID) {
2984 Profile(ID, getElementType(), getSizeModifier(),
2985 getIndexTypeCVRQualifiers());
2986 }
2987
2988 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2989 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2990 ID.AddPointer(ET.getAsOpaquePtr());
2991 ID.AddInteger(SizeMod);
2992 ID.AddInteger(TypeQuals);
2993 }
2994};
2995
2996/// Represents a C array with a specified size that is not an
2997/// integer-constant-expression. For example, 'int s[x+foo()]'.
2998/// Since the size expression is an arbitrary expression, we store it as such.
2999///
3000/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3001/// should not be: two lexically equivalent variable array types could mean
3002/// different things, for example, these variables do not have the same type
3003/// dynamically:
3004///
3005/// void foo(int x) {
3006/// int Y[x];
3007/// ++x;
3008/// int Z[x];
3009/// }
3010class VariableArrayType : public ArrayType {
3011 friend class ASTContext; // ASTContext creates these.
3012
3013 /// An assignment-expression. VLA's are only permitted within
3014 /// a function block.
3015 Stmt *SizeExpr;
3016
3017 /// The range spanned by the left and right array brackets.
3018 SourceRange Brackets;
3019
3020 VariableArrayType(QualType et, QualType can, Expr *e,
3021 ArraySizeModifier sm, unsigned tq,
3022 SourceRange brackets)
3023 : ArrayType(VariableArray, et, can, sm, tq, e),
3024 SizeExpr((Stmt*) e), Brackets(brackets) {}
3025
3026public:
3027 friend class StmtIteratorBase;
3028
3029 Expr *getSizeExpr() const {
3030 // We use C-style casts instead of cast<> here because we do not wish
3031 // to have a dependency of Type.h on Stmt.h/Expr.h.
3032 return (Expr*) SizeExpr;
3033 }
3034
3035 SourceRange getBracketsRange() const { return Brackets; }
3036 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3037 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3038
3039 bool isSugared() const { return false; }
3040 QualType desugar() const { return QualType(this, 0); }
3041
3042 static bool classof(const Type *T) {
3043 return T->getTypeClass() == VariableArray;
3044 }
3045
3046 void Profile(llvm::FoldingSetNodeID &ID) {
3047 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 3047)
;
3048 }
3049};
3050
3051/// Represents an array type in C++ whose size is a value-dependent expression.
3052///
3053/// For example:
3054/// \code
3055/// template<typename T, int Size>
3056/// class array {
3057/// T data[Size];
3058/// };
3059/// \endcode
3060///
3061/// For these types, we won't actually know what the array bound is
3062/// until template instantiation occurs, at which point this will
3063/// become either a ConstantArrayType or a VariableArrayType.
3064class DependentSizedArrayType : public ArrayType {
3065 friend class ASTContext; // ASTContext creates these.
3066
3067 const ASTContext &Context;
3068
3069 /// An assignment expression that will instantiate to the
3070 /// size of the array.
3071 ///
3072 /// The expression itself might be null, in which case the array
3073 /// type will have its size deduced from an initializer.
3074 Stmt *SizeExpr;
3075
3076 /// The range spanned by the left and right array brackets.
3077 SourceRange Brackets;
3078
3079 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3080 Expr *e, ArraySizeModifier sm, unsigned tq,
3081 SourceRange brackets);
3082
3083public:
3084 friend class StmtIteratorBase;
3085
3086 Expr *getSizeExpr() const {
3087 // We use C-style casts instead of cast<> here because we do not wish
3088 // to have a dependency of Type.h on Stmt.h/Expr.h.
3089 return (Expr*) SizeExpr;
3090 }
3091
3092 SourceRange getBracketsRange() const { return Brackets; }
3093 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3094 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3095
3096 bool isSugared() const { return false; }
3097 QualType desugar() const { return QualType(this, 0); }
3098
3099 static bool classof(const Type *T) {
3100 return T->getTypeClass() == DependentSizedArray;
3101 }
3102
3103 void Profile(llvm::FoldingSetNodeID &ID) {
3104 Profile(ID, Context, getElementType(),
3105 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3106 }
3107
3108 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3109 QualType ET, ArraySizeModifier SizeMod,
3110 unsigned TypeQuals, Expr *E);
3111};
3112
3113/// Represents an extended address space qualifier where the input address space
3114/// value is dependent. Non-dependent address spaces are not represented with a
3115/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3116///
3117/// For example:
3118/// \code
3119/// template<typename T, int AddrSpace>
3120/// class AddressSpace {
3121/// typedef T __attribute__((address_space(AddrSpace))) type;
3122/// }
3123/// \endcode
3124class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3125 friend class ASTContext;
3126
3127 const ASTContext &Context;
3128 Expr *AddrSpaceExpr;
3129 QualType PointeeType;
3130 SourceLocation loc;
3131
3132 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3133 QualType can, Expr *AddrSpaceExpr,
3134 SourceLocation loc);
3135
3136public:
3137 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3138 QualType getPointeeType() const { return PointeeType; }
3139 SourceLocation getAttributeLoc() const { return loc; }
3140
3141 bool isSugared() const { return false; }
3142 QualType desugar() const { return QualType(this, 0); }
3143
3144 static bool classof(const Type *T) {
3145 return T->getTypeClass() == DependentAddressSpace;
3146 }
3147
3148 void Profile(llvm::FoldingSetNodeID &ID) {
3149 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3150 }
3151
3152 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3153 QualType PointeeType, Expr *AddrSpaceExpr);
3154};
3155
3156/// Represents an extended vector type where either the type or size is
3157/// dependent.
3158///
3159/// For example:
3160/// \code
3161/// template<typename T, int Size>
3162/// class vector {
3163/// typedef T __attribute__((ext_vector_type(Size))) type;
3164/// }
3165/// \endcode
3166class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3167 friend class ASTContext;
3168
3169 const ASTContext &Context;
3170 Expr *SizeExpr;
3171
3172 /// The element type of the array.
3173 QualType ElementType;
3174
3175 SourceLocation loc;
3176
3177 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3178 QualType can, Expr *SizeExpr, SourceLocation loc);
3179
3180public:
3181 Expr *getSizeExpr() const { return SizeExpr; }
3182 QualType getElementType() const { return ElementType; }
3183 SourceLocation getAttributeLoc() const { return loc; }
3184
3185 bool isSugared() const { return false; }
3186 QualType desugar() const { return QualType(this, 0); }
3187
3188 static bool classof(const Type *T) {
3189 return T->getTypeClass() == DependentSizedExtVector;
3190 }
3191
3192 void Profile(llvm::FoldingSetNodeID &ID) {
3193 Profile(ID, Context, getElementType(), getSizeExpr());
3194 }
3195
3196 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3197 QualType ElementType, Expr *SizeExpr);
3198};
3199
3200
3201/// Represents a GCC generic vector type. This type is created using
3202/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3203/// bytes; or from an Altivec __vector or vector declaration.
3204/// Since the constructor takes the number of vector elements, the
3205/// client is responsible for converting the size into the number of elements.
3206class VectorType : public Type, public llvm::FoldingSetNode {
3207public:
3208 enum VectorKind {
3209 /// not a target-specific vector type
3210 GenericVector,
3211
3212 /// is AltiVec vector
3213 AltiVecVector,
3214
3215 /// is AltiVec 'vector Pixel'
3216 AltiVecPixel,
3217
3218 /// is AltiVec 'vector bool ...'
3219 AltiVecBool,
3220
3221 /// is ARM Neon vector
3222 NeonVector,
3223
3224 /// is ARM Neon polynomial vector
3225 NeonPolyVector
3226 };
3227
3228protected:
3229 friend class ASTContext; // ASTContext creates these.
3230
3231 /// The element type of the vector.
3232 QualType ElementType;
3233
3234 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3235 VectorKind vecKind);
3236
3237 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3238 QualType canonType, VectorKind vecKind);
3239
3240public:
3241 QualType getElementType() const { return ElementType; }
3242 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3243
3244 static bool isVectorSizeTooLarge(unsigned NumElements) {
3245 return NumElements > VectorTypeBitfields::MaxNumElements;
3246 }
3247
3248 bool isSugared() const { return false; }
3249 QualType desugar() const { return QualType(this, 0); }
3250
3251 VectorKind getVectorKind() const {
3252 return VectorKind(VectorTypeBits.VecKind);
3253 }
3254
3255 void Profile(llvm::FoldingSetNodeID &ID) {
3256 Profile(ID, getElementType(), getNumElements(),
3257 getTypeClass(), getVectorKind());
3258 }
3259
3260 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3261 unsigned NumElements, TypeClass TypeClass,
3262 VectorKind VecKind) {
3263 ID.AddPointer(ElementType.getAsOpaquePtr());
3264 ID.AddInteger(NumElements);
3265 ID.AddInteger(TypeClass);
3266 ID.AddInteger(VecKind);
3267 }
3268
3269 static bool classof(const Type *T) {
3270 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3271 }
3272};
3273
3274/// Represents a vector type where either the type or size is dependent.
3275////
3276/// For example:
3277/// \code
3278/// template<typename T, int Size>
3279/// class vector {
3280/// typedef T __attribute__((vector_size(Size))) type;
3281/// }
3282/// \endcode
3283class DependentVectorType : public Type, public llvm::FoldingSetNode {
3284 friend class ASTContext;
3285
3286 const ASTContext &Context;
3287 QualType ElementType;
3288 Expr *SizeExpr;
3289 SourceLocation Loc;
3290
3291 DependentVectorType(const ASTContext &Context, QualType ElementType,
3292 QualType CanonType, Expr *SizeExpr,
3293 SourceLocation Loc, VectorType::VectorKind vecKind);
3294
3295public:
3296 Expr *getSizeExpr() const { return SizeExpr; }
3297 QualType getElementType() const { return ElementType; }
3298 SourceLocation getAttributeLoc() const { return Loc; }
3299 VectorType::VectorKind getVectorKind() const {
3300 return VectorType::VectorKind(VectorTypeBits.VecKind);
3301 }
3302
3303 bool isSugared() const { return false; }
3304 QualType desugar() const { return QualType(this, 0); }
3305
3306 static bool classof(const Type *T) {
3307 return T->getTypeClass() == DependentVector;
3308 }
3309
3310 void Profile(llvm::FoldingSetNodeID &ID) {
3311 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3312 }
3313
3314 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3315 QualType ElementType, const Expr *SizeExpr,
3316 VectorType::VectorKind VecKind);
3317};
3318
3319/// ExtVectorType - Extended vector type. This type is created using
3320/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3321/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3322/// class enables syntactic extensions, like Vector Components for accessing
3323/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3324/// Shading Language).
3325class ExtVectorType : public VectorType {
3326 friend class ASTContext; // ASTContext creates these.
3327
3328 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3329 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3330
3331public:
3332 static int getPointAccessorIdx(char c) {
3333 switch (c) {
3334 default: return -1;
3335 case 'x': case 'r': return 0;
3336 case 'y': case 'g': return 1;
3337 case 'z': case 'b': return 2;
3338 case 'w': case 'a': return 3;
3339 }
3340 }
3341
3342 static int getNumericAccessorIdx(char c) {
3343 switch (c) {
3344 default: return -1;
3345 case '0': return 0;
3346 case '1': return 1;
3347 case '2': return 2;
3348 case '3': return 3;
3349 case '4': return 4;
3350 case '5': return 5;
3351 case '6': return 6;
3352 case '7': return 7;
3353 case '8': return 8;
3354 case '9': return 9;
3355 case 'A':
3356 case 'a': return 10;
3357 case 'B':
3358 case 'b': return 11;
3359 case 'C':
3360 case 'c': return 12;
3361 case 'D':
3362 case 'd': return 13;
3363 case 'E':
3364 case 'e': return 14;
3365 case 'F':
3366 case 'f': return 15;
3367 }
3368 }
3369
3370 static int getAccessorIdx(char c, bool isNumericAccessor) {
3371 if (isNumericAccessor)
3372 return getNumericAccessorIdx(c);
3373 else
3374 return getPointAccessorIdx(c);
3375 }
3376
3377 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3378 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3379 return unsigned(idx-1) < getNumElements();
3380 return false;
3381 }
3382
3383 bool isSugared() const { return false; }
3384 QualType desugar() const { return QualType(this, 0); }
3385
3386 static bool classof(const Type *T) {
3387 return T->getTypeClass() == ExtVector;
3388 }
3389};
3390
3391/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3392/// class of FunctionNoProtoType and FunctionProtoType.
3393class FunctionType : public Type {
3394 // The type returned by the function.
3395 QualType ResultType;
3396
3397public:
3398 /// Interesting information about a specific parameter that can't simply
3399 /// be reflected in parameter's type. This is only used by FunctionProtoType
3400 /// but is in FunctionType to make this class available during the
3401 /// specification of the bases of FunctionProtoType.
3402 ///
3403 /// It makes sense to model language features this way when there's some
3404 /// sort of parameter-specific override (such as an attribute) that
3405 /// affects how the function is called. For example, the ARC ns_consumed
3406 /// attribute changes whether a parameter is passed at +0 (the default)
3407 /// or +1 (ns_consumed). This must be reflected in the function type,
3408 /// but isn't really a change to the parameter type.
3409 ///
3410 /// One serious disadvantage of modelling language features this way is
3411 /// that they generally do not work with language features that attempt
3412 /// to destructure types. For example, template argument deduction will
3413 /// not be able to match a parameter declared as
3414 /// T (*)(U)
3415 /// against an argument of type
3416 /// void (*)(__attribute__((ns_consumed)) id)
3417 /// because the substitution of T=void, U=id into the former will
3418 /// not produce the latter.
3419 class ExtParameterInfo {
3420 enum {
3421 ABIMask = 0x0F,
3422 IsConsumed = 0x10,
3423 HasPassObjSize = 0x20,
3424 IsNoEscape = 0x40,
3425 };
3426 unsigned char Data = 0;
3427
3428 public:
3429 ExtParameterInfo() = default;
3430
3431 /// Return the ABI treatment of this parameter.
3432 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3433 ExtParameterInfo withABI(ParameterABI kind) const {
3434 ExtParameterInfo copy = *this;
3435 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3436 return copy;
3437 }
3438
3439 /// Is this parameter considered "consumed" by Objective-C ARC?
3440 /// Consumed parameters must have retainable object type.
3441 bool isConsumed() const { return (Data & IsConsumed); }
3442 ExtParameterInfo withIsConsumed(bool consumed) const {
3443 ExtParameterInfo copy = *this;
3444 if (consumed)
3445 copy.Data |= IsConsumed;
3446 else
3447 copy.Data &= ~IsConsumed;
3448 return copy;
3449 }
3450
3451 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3452 ExtParameterInfo withHasPassObjectSize() const {
3453 ExtParameterInfo Copy = *this;
3454 Copy.Data |= HasPassObjSize;
3455 return Copy;
3456 }
3457
3458 bool isNoEscape() const { return Data & IsNoEscape; }
3459 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3460 ExtParameterInfo Copy = *this;
3461 if (NoEscape)
3462 Copy.Data |= IsNoEscape;
3463 else
3464 Copy.Data &= ~IsNoEscape;
3465 return Copy;
3466 }
3467
3468 unsigned char getOpaqueValue() const { return Data; }
3469 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3470 ExtParameterInfo result;
3471 result.Data = data;
3472 return result;
3473 }
3474
3475 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3476 return lhs.Data == rhs.Data;
3477 }
3478
3479 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3480 return lhs.Data != rhs.Data;
3481 }
3482 };
3483
3484 /// A class which abstracts out some details necessary for
3485 /// making a call.
3486 ///
3487 /// It is not actually used directly for storing this information in
3488 /// a FunctionType, although FunctionType does currently use the
3489 /// same bit-pattern.
3490 ///
3491 // If you add a field (say Foo), other than the obvious places (both,
3492 // constructors, compile failures), what you need to update is
3493 // * Operator==
3494 // * getFoo
3495 // * withFoo
3496 // * functionType. Add Foo, getFoo.
3497 // * ASTContext::getFooType
3498 // * ASTContext::mergeFunctionTypes
3499 // * FunctionNoProtoType::Profile
3500 // * FunctionProtoType::Profile
3501 // * TypePrinter::PrintFunctionProto
3502 // * AST read and write
3503 // * Codegen
3504 class ExtInfo {
3505 friend class FunctionType;
3506
3507 // Feel free to rearrange or add bits, but if you go over 12,
3508 // you'll need to adjust both the Bits field below and
3509 // Type::FunctionTypeBitfields.
3510
3511 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3512 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3513 //
3514 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3515 enum { CallConvMask = 0x1F };
3516 enum { NoReturnMask = 0x20 };
3517 enum { ProducesResultMask = 0x40 };
3518 enum { NoCallerSavedRegsMask = 0x80 };
3519 enum { NoCfCheckMask = 0x800 };
3520 enum {
3521 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3522 NoCallerSavedRegsMask | NoCfCheckMask),
3523 RegParmOffset = 8
3524 }; // Assumed to be the last field
3525 uint16_t Bits = CC_C;
3526
3527 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3528
3529 public:
3530 // Constructor with no defaults. Use this when you know that you
3531 // have all the elements (when reading an AST file for example).
3532 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3533 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3534 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value"
) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 3534, __PRETTY_FUNCTION__))
;
3535 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3536 (producesResult ? ProducesResultMask : 0) |
3537 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3538 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3539 (NoCfCheck ? NoCfCheckMask : 0);
3540 }
3541
3542 // Constructor with all defaults. Use when for example creating a
3543 // function known to use defaults.
3544 ExtInfo() = default;
3545
3546 // Constructor with just the calling convention, which is an important part
3547 // of the canonical type.
3548 ExtInfo(CallingConv CC) : Bits(CC) {}
3549
3550 bool getNoReturn() const { return Bits & NoReturnMask; }
3551 bool getProducesResult() const { return Bits & ProducesResultMask; }
3552 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3553 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3554 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3555
3556 unsigned getRegParm() const {
3557 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3558 if (RegParm > 0)
3559 --RegParm;
3560 return RegParm;
3561 }
3562
3563 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3564
3565 bool operator==(ExtInfo Other) const {
3566 return Bits == Other.Bits;
3567 }
3568 bool operator!=(ExtInfo Other) const {
3569 return Bits != Other.Bits;
3570 }
3571
3572 // Note that we don't have setters. That is by design, use
3573 // the following with methods instead of mutating these objects.
3574
3575 ExtInfo withNoReturn(bool noReturn) const {
3576 if (noReturn)
3577 return ExtInfo(Bits | NoReturnMask);
3578 else
3579 return ExtInfo(Bits & ~NoReturnMask);
3580 }
3581
3582 ExtInfo withProducesResult(bool producesResult) const {
3583 if (producesResult)
3584 return ExtInfo(Bits | ProducesResultMask);
3585 else
3586 return ExtInfo(Bits & ~ProducesResultMask);
3587 }
3588
3589 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3590 if (noCallerSavedRegs)
3591 return ExtInfo(Bits | NoCallerSavedRegsMask);
3592 else
3593 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3594 }
3595
3596 ExtInfo withNoCfCheck(bool noCfCheck) const {
3597 if (noCfCheck)
3598 return ExtInfo(Bits | NoCfCheckMask);
3599 else
3600 return ExtInfo(Bits & ~NoCfCheckMask);
3601 }
3602
3603 ExtInfo withRegParm(unsigned RegParm) const {
3604 assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast
<void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 3604, __PRETTY_FUNCTION__))
;
3605 return ExtInfo((Bits & ~RegParmMask) |
3606 ((RegParm + 1) << RegParmOffset));
3607 }
3608
3609 ExtInfo withCallingConv(CallingConv cc) const {
3610 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3611 }
3612
3613 void Profile(llvm::FoldingSetNodeID &ID) const {
3614 ID.AddInteger(Bits);
3615 }
3616 };
3617
3618 /// A simple holder for a QualType representing a type in an
3619 /// exception specification. Unfortunately needed by FunctionProtoType
3620 /// because TrailingObjects cannot handle repeated types.
3621 struct ExceptionType { QualType Type; };
3622
3623 /// A simple holder for various uncommon bits which do not fit in
3624 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3625 /// alignment of subsequent objects in TrailingObjects. You must update
3626 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3627 struct alignas(void *) FunctionTypeExtraBitfields {
3628 /// The number of types in the exception specification.
3629 /// A whole unsigned is not needed here and according to
3630 /// [implimits] 8 bits would be enough here.
3631 unsigned NumExceptionType;
3632 };
3633
3634protected:
3635 FunctionType(TypeClass tc, QualType res,
3636 QualType Canonical, bool Dependent,
3637 bool InstantiationDependent,
3638 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3639 ExtInfo Info)
3640 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3641 ContainsUnexpandedParameterPack),
3642 ResultType(res) {
3643 FunctionTypeBits.ExtInfo = Info.Bits;
3644 }
3645
3646 Qualifiers getFastTypeQuals() const {
3647 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3648 }
3649
3650public:
3651 QualType getReturnType() const { return ResultType; }
3652
3653 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3654 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3655
3656 /// Determine whether this function type includes the GNU noreturn
3657 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3658 /// type.
3659 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3660
3661 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3662 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3663
3664 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3665 "Const, volatile and restrict are assumed to be a subset of "
3666 "the fast qualifiers.");
3667
3668 bool isConst() const { return getFastTypeQuals().hasConst(); }
3669 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3670 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3671
3672 /// Determine the type of an expression that calls a function of
3673 /// this type.
3674 QualType getCallResultType(const ASTContext &Context) const {
3675 return getReturnType().getNonLValueExprType(Context);
3676 }
3677
3678 static StringRef getNameForCallConv(CallingConv CC);
3679
3680 static bool classof(const Type *T) {
3681 return T->getTypeClass() == FunctionNoProto ||
3682 T->getTypeClass() == FunctionProto;
3683 }
3684};
3685
3686/// Represents a K&R-style 'int foo()' function, which has
3687/// no information available about its arguments.
3688class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3689 friend class ASTContext; // ASTContext creates these.
3690
3691 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3692 : FunctionType(FunctionNoProto, Result, Canonical,
3693 /*Dependent=*/false, /*InstantiationDependent=*/false,
3694 Result->isVariablyModifiedType(),
3695 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3696
3697public:
3698 // No additional state past what FunctionType provides.
3699
3700 bool isSugared() const { return false; }
3701 QualType desugar() const { return QualType(this, 0); }
3702
3703 void Profile(llvm::FoldingSetNodeID &ID) {
3704 Profile(ID, getReturnType(), getExtInfo());
3705 }
3706
3707 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3708 ExtInfo Info) {
3709 Info.Profile(ID);
3710 ID.AddPointer(ResultType.getAsOpaquePtr());
3711 }
3712
3713 static bool classof(const Type *T) {
3714 return T->getTypeClass() == FunctionNoProto;
3715 }
3716};
3717
3718/// Represents a prototype with parameter type info, e.g.
3719/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3720/// parameters, not as having a single void parameter. Such a type can have
3721/// an exception specification, but this specification is not part of the
3722/// canonical type. FunctionProtoType has several trailing objects, some of
3723/// which optional. For more information about the trailing objects see
3724/// the first comment inside FunctionProtoType.
3725class FunctionProtoType final
3726 : public FunctionType,
3727 public llvm::FoldingSetNode,
3728 private llvm::TrailingObjects<
3729 FunctionProtoType, QualType, FunctionType::FunctionTypeExtraBitfields,
3730 FunctionType::ExceptionType, Expr *, FunctionDecl *,
3731 FunctionType::ExtParameterInfo, Qualifiers> {
3732 friend class ASTContext; // ASTContext creates these.
3733 friend TrailingObjects;
3734
3735 // FunctionProtoType is followed by several trailing objects, some of
3736 // which optional. They are in order:
3737 //
3738 // * An array of getNumParams() QualType holding the parameter types.
3739 // Always present. Note that for the vast majority of FunctionProtoType,
3740 // these will be the only trailing objects.
3741 //
3742 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3743 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3744 // a single FunctionTypeExtraBitfields. Present if and only if
3745 // hasExtraBitfields() is true.
3746 //
3747 // * Optionally exactly one of:
3748 // * an array of getNumExceptions() ExceptionType,
3749 // * a single Expr *,
3750 // * a pair of FunctionDecl *,
3751 // * a single FunctionDecl *
3752 // used to store information about the various types of exception
3753 // specification. See getExceptionSpecSize for the details.
3754 //
3755 // * Optionally an array of getNumParams() ExtParameterInfo holding
3756 // an ExtParameterInfo for each of the parameters. Present if and
3757 // only if hasExtParameterInfos() is true.
3758 //
3759 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3760 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3761 // if hasExtQualifiers() is true.
3762 //
3763 // The optional FunctionTypeExtraBitfields has to be before the data
3764 // related to the exception specification since it contains the number
3765 // of exception types.
3766 //
3767 // We put the ExtParameterInfos last. If all were equal, it would make
3768 // more sense to put these before the exception specification, because
3769 // it's much easier to skip past them compared to the elaborate switch
3770 // required to skip the exception specification. However, all is not
3771 // equal; ExtParameterInfos are used to model very uncommon features,
3772 // and it's better not to burden the more common paths.
3773
3774public:
3775 /// Holds information about the various types of exception specification.
3776 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3777 /// used to group together the various bits of information about the
3778 /// exception specification.
3779 struct ExceptionSpecInfo {
3780 /// The kind of exception specification this is.
3781 ExceptionSpecificationType Type = EST_None;
3782
3783 /// Explicitly-specified list of exception types.
3784 ArrayRef<QualType> Exceptions;
3785
3786 /// Noexcept expression, if this is a computed noexcept specification.
3787 Expr *NoexceptExpr = nullptr;
3788
3789 /// The function whose exception specification this is, for
3790 /// EST_Unevaluated and EST_Uninstantiated.
3791 FunctionDecl *SourceDecl = nullptr;
3792
3793 /// The function template whose exception specification this is instantiated
3794 /// from, for EST_Uninstantiated.
3795 FunctionDecl *SourceTemplate = nullptr;
3796
3797 ExceptionSpecInfo() = default;
3798
3799 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3800 };
3801
3802 /// Extra information about a function prototype. ExtProtoInfo is not
3803 /// stored as such in FunctionProtoType but is used to group together
3804 /// the various bits of extra information about a function prototype.
3805 struct ExtProtoInfo {
3806 FunctionType::ExtInfo ExtInfo;
3807 bool Variadic : 1;
3808 bool HasTrailingReturn : 1;
3809 Qualifiers TypeQuals;
3810 RefQualifierKind RefQualifier = RQ_None;
3811 ExceptionSpecInfo ExceptionSpec;
3812 const ExtParameterInfo *ExtParameterInfos = nullptr;
3813
3814 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3815
3816 ExtProtoInfo(CallingConv CC)
3817 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3818
3819 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3820 ExtProtoInfo Result(*this);
3821 Result.ExceptionSpec = ESI;
3822 return Result;
3823 }
3824 };
3825
3826private:
3827 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3828 return getNumParams();
3829 }
3830
3831 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3832 return hasExtraBitfields();
3833 }
3834
3835 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3836 return getExceptionSpecSize().NumExceptionType;
3837 }
3838
3839 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3840 return getExceptionSpecSize().NumExprPtr;
3841 }
3842
3843 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
3844 return getExceptionSpecSize().NumFunctionDeclPtr;
3845 }
3846
3847 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
3848 return hasExtParameterInfos() ? getNumParams() : 0;
3849 }
3850
3851 /// Determine whether there are any argument types that
3852 /// contain an unexpanded parameter pack.
3853 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3854 unsigned numArgs) {
3855 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3856 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3857 return true;
3858
3859 return false;
3860 }
3861
3862 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3863 QualType canonical, const ExtProtoInfo &epi);
3864
3865 /// This struct is returned by getExceptionSpecSize and is used to
3866 /// translate an ExceptionSpecificationType to the number and kind
3867 /// of trailing objects related to the exception specification.
3868 struct ExceptionSpecSizeHolder {
3869 unsigned NumExceptionType;
3870 unsigned NumExprPtr;
3871 unsigned NumFunctionDeclPtr;
3872 };
3873
3874 /// Return the number and kind of trailing objects
3875 /// related to the exception specification.
3876 static ExceptionSpecSizeHolder
3877 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
3878 switch (EST) {
3879 case EST_None:
3880 case EST_DynamicNone:
3881 case EST_MSAny:
3882 case EST_BasicNoexcept:
3883 case EST_Unparsed:
3884 case EST_NoThrow:
3885 return {0, 0, 0};
3886
3887 case EST_Dynamic:
3888 return {NumExceptions, 0, 0};
3889
3890 case EST_DependentNoexcept:
3891 case EST_NoexceptFalse:
3892 case EST_NoexceptTrue:
3893 return {0, 1, 0};
3894
3895 case EST_Uninstantiated:
3896 return {0, 0, 2};
3897
3898 case EST_Unevaluated:
3899 return {0, 0, 1};
3900 }
3901 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 3901)
;
3902 }
3903
3904 /// Return the number and kind of trailing objects
3905 /// related to the exception specification.
3906 ExceptionSpecSizeHolder getExceptionSpecSize() const {
3907 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3908 }
3909
3910 /// Whether the trailing FunctionTypeExtraBitfields is present.
3911 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
3912 // If the exception spec type is EST_Dynamic then we have > 0 exception
3913 // types and the exact number is stored in FunctionTypeExtraBitfields.
3914 return EST == EST_Dynamic;
3915 }
3916
3917 /// Whether the trailing FunctionTypeExtraBitfields is present.
3918 bool hasExtraBitfields() const {
3919 return hasExtraBitfields(getExceptionSpecType());
3920 }
3921
3922 bool hasExtQualifiers() const {
3923 return FunctionTypeBits.HasExtQuals;
3924 }
3925
3926public:
3927 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
3928
3929 QualType getParamType(unsigned i) const {
3930 assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index")
? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 3930, __PRETTY_FUNCTION__))
;
3931 return param_type_begin()[i];
3932 }
3933
3934 ArrayRef<QualType> getParamTypes() const {
3935 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3936 }
3937
3938 ExtProtoInfo getExtProtoInfo() const {
3939 ExtProtoInfo EPI;
3940 EPI.ExtInfo = getExtInfo();
3941 EPI.Variadic = isVariadic();
3942 EPI.HasTrailingReturn = hasTrailingReturn();
3943 EPI.ExceptionSpec.Type = getExceptionSpecType();
3944 EPI.TypeQuals = getMethodQuals();
3945 EPI.RefQualifier = getRefQualifier();
3946 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3947 EPI.ExceptionSpec.Exceptions = exceptions();
3948 } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) {
3949 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3950 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3951 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3952 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3953 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3954 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3955 }
3956 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
3957 return EPI;
3958 }
3959
3960 /// Get the kind of exception specification on this function.
3961 ExceptionSpecificationType getExceptionSpecType() const {
3962 return static_cast<ExceptionSpecificationType>(
3963 FunctionTypeBits.ExceptionSpecType);
3964 }
3965
3966 /// Return whether this function has any kind of exception spec.
3967 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
3968
3969 /// Return whether this function has a dynamic (throw) exception spec.
3970 bool hasDynamicExceptionSpec() const {
3971 return isDynamicExceptionSpec(getExceptionSpecType());
3972 }
3973
3974 /// Return whether this function has a noexcept exception spec.
3975 bool hasNoexceptExceptionSpec() const {
3976 return isNoexceptExceptionSpec(getExceptionSpecType());
3977 }
3978
3979 /// Return whether this function has a dependent exception spec.
3980 bool hasDependentExceptionSpec() const;
3981
3982 /// Return whether this function has an instantiation-dependent exception
3983 /// spec.
3984 bool hasInstantiationDependentExceptionSpec() const;
3985
3986 /// Return the number of types in the exception specification.
3987 unsigned getNumExceptions() const {
3988 return getExceptionSpecType() == EST_Dynamic
3989 ? getTrailingObjects<FunctionTypeExtraBitfields>()
3990 ->NumExceptionType
3991 : 0;
3992 }
3993
3994 /// Return the ith exception type, where 0 <= i < getNumExceptions().
3995 QualType getExceptionType(unsigned i) const {
3996 assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 3996, __PRETTY_FUNCTION__))
;
3997 return exception_begin()[i];
3998 }
3999
4000 /// Return the expression inside noexcept(expression), or a null pointer
4001 /// if there is none (because the exception spec is not of this form).
4002 Expr *getNoexceptExpr() const {
4003 if (!isComputedNoexcept(getExceptionSpecType()))
4004 return nullptr;
4005 return *getTrailingObjects<Expr *>();
4006 }
4007
4008 /// If this function type has an exception specification which hasn't
4009 /// been determined yet (either because it has not been evaluated or because
4010 /// it has not been instantiated), this is the function whose exception
4011 /// specification is represented by this type.
4012 FunctionDecl *getExceptionSpecDecl() const {
4013 if (getExceptionSpecType() != EST_Uninstantiated &&
4014 getExceptionSpecType() != EST_Unevaluated)
4015 return nullptr;
4016 return getTrailingObjects<FunctionDecl *>()[0];
4017 }
4018
4019 /// If this function type has an uninstantiated exception
4020 /// specification, this is the function whose exception specification
4021 /// should be instantiated to find the exception specification for
4022 /// this type.
4023 FunctionDecl *getExceptionSpecTemplate() const {
4024 if (getExceptionSpecType() != EST_Uninstantiated)
4025 return nullptr;
4026 return getTrailingObjects<FunctionDecl *>()[1];
4027 }
4028
4029 /// Determine whether this function type has a non-throwing exception
4030 /// specification.
4031 CanThrowResult canThrow() const;
4032
4033 /// Determine whether this function type has a non-throwing exception
4034 /// specification. If this depends on template arguments, returns
4035 /// \c ResultIfDependent.
4036 bool isNothrow(bool ResultIfDependent = false) const {
4037 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4038 }
4039
4040 /// Whether this function prototype is variadic.
4041 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4042
4043 /// Determines whether this function prototype contains a
4044 /// parameter pack at the end.
4045 ///
4046 /// A function template whose last parameter is a parameter pack can be
4047 /// called with an arbitrary number of arguments, much like a variadic
4048 /// function.
4049 bool isTemplateVariadic() const;
4050
4051 /// Whether this function prototype has a trailing return type.
4052 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4053
4054 Qualifiers getMethodQuals() const {
4055 if (hasExtQualifiers())
4056 return *getTrailingObjects<Qualifiers>();
4057 else
4058 return getFastTypeQuals();
4059 }
4060
4061 /// Retrieve the ref-qualifier associated with this function type.
4062 RefQualifierKind getRefQualifier() const {
4063 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4064 }
4065
4066 using param_type_iterator = const QualType *;
4067 using param_type_range = llvm::iterator_range<param_type_iterator>;
4068
4069 param_type_range param_types() const {
4070 return param_type_range(param_type_begin(), param_type_end());
4071 }
4072
4073 param_type_iterator param_type_begin() const {
4074 return getTrailingObjects<QualType>();
4075 }
4076
4077 param_type_iterator param_type_end() const {
4078 return param_type_begin() + getNumParams();
4079 }
4080
4081 using exception_iterator = const QualType *;
4082
4083 ArrayRef<QualType> exceptions() const {
4084 return llvm::makeArrayRef(exception_begin(), exception_end());
4085 }
4086
4087 exception_iterator exception_begin() const {
4088 return reinterpret_cast<exception_iterator>(
4089 getTrailingObjects<ExceptionType>());
4090 }
4091
4092 exception_iterator exception_end() const {
4093 return exception_begin() + getNumExceptions();
4094 }
4095
4096 /// Is there any interesting extra information for any of the parameters
4097 /// of this function type?
4098 bool hasExtParameterInfos() const {
4099 return FunctionTypeBits.HasExtParameterInfos;
4100 }
4101
4102 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4103 assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail
("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4103, __PRETTY_FUNCTION__))
;
4104 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4105 getNumParams());
4106 }
4107
4108 /// Return a pointer to the beginning of the array of extra parameter
4109 /// information, if present, or else null if none of the parameters
4110 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4111 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4112 if (!hasExtParameterInfos())
4113 return nullptr;
4114 return getTrailingObjects<ExtParameterInfo>();
4115 }
4116
4117 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4118 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4118, __PRETTY_FUNCTION__))
;
4119 if (hasExtParameterInfos())
4120 return getTrailingObjects<ExtParameterInfo>()[I];
4121 return ExtParameterInfo();
4122 }
4123
4124 ParameterABI getParameterABI(unsigned I) const {
4125 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4125, __PRETTY_FUNCTION__))
;
4126 if (hasExtParameterInfos())
4127 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4128 return ParameterABI::Ordinary;
4129 }
4130
4131 bool isParamConsumed(unsigned I) const {
4132 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4132, __PRETTY_FUNCTION__))
;
4133 if (hasExtParameterInfos())
4134 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4135 return false;
4136 }
4137
4138 bool isSugared() const { return false; }
4139 QualType desugar() const { return QualType(this, 0); }
4140
4141 void printExceptionSpecification(raw_ostream &OS,
4142 const PrintingPolicy &Policy) const;
4143
4144 static bool classof(const Type *T) {
4145 return T->getTypeClass() == FunctionProto;
4146 }
4147
4148 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4149 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4150 param_type_iterator ArgTys, unsigned NumArgs,
4151 const ExtProtoInfo &EPI, const ASTContext &Context,
4152 bool Canonical);
4153};
4154
4155/// Represents the dependent type named by a dependently-scoped
4156/// typename using declaration, e.g.
4157/// using typename Base<T>::foo;
4158///
4159/// Template instantiation turns these into the underlying type.
4160class UnresolvedUsingType : public Type {
4161 friend class ASTContext; // ASTContext creates these.
4162
4163 UnresolvedUsingTypenameDecl *Decl;
4164
4165 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4166 : Type(UnresolvedUsing, QualType(), true, true, false,
4167 /*ContainsUnexpandedParameterPack=*/false),
4168 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
4169
4170public:
4171 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4172
4173 bool isSugared() const { return false; }
4174 QualType desugar() const { return QualType(this, 0); }
4175
4176 static bool classof(const Type *T) {
4177 return T->getTypeClass() == UnresolvedUsing;
4178 }
4179
4180 void Profile(llvm::FoldingSetNodeID &ID) {
4181 return Profile(ID, Decl);
4182 }
4183
4184 static void Profile(llvm::FoldingSetNodeID &ID,
4185 UnresolvedUsingTypenameDecl *D) {
4186 ID.AddPointer(D);
4187 }
4188};
4189
4190class TypedefType : public Type {
4191 TypedefNameDecl *Decl;
4192
4193protected:
4194 friend class ASTContext; // ASTContext creates these.
4195
4196 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
4197 : Type(tc, can, can->isDependentType(),
4198 can->isInstantiationDependentType(),
4199 can->isVariablyModifiedType(),
4200 /*ContainsUnexpandedParameterPack=*/false),
4201 Decl(const_cast<TypedefNameDecl*>(D)) {
4202 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4202, __PRETTY_FUNCTION__))
;
4203 }
4204
4205public:
4206 TypedefNameDecl *getDecl() const { return Decl; }
4207
4208 bool isSugared() const { return true; }
4209 QualType desugar() const;
4210
4211 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4212};
4213
4214/// Sugar type that represents a type that was qualified by a qualifier written
4215/// as a macro invocation.
4216class MacroQualifiedType : public Type {
4217 friend class ASTContext; // ASTContext creates these.
4218
4219 QualType UnderlyingTy;
4220 const IdentifierInfo *MacroII;
4221
4222 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4223 const IdentifierInfo *MacroII)
4224 : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(),
4225 UnderlyingTy->isInstantiationDependentType(),
4226 UnderlyingTy->isVariablyModifiedType(),
4227 UnderlyingTy->containsUnexpandedParameterPack()),
4228 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4229 assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4230, __PRETTY_FUNCTION__))
4230 "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4230, __PRETTY_FUNCTION__))
;
4231 }
4232
4233public:
4234 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4235 QualType getUnderlyingType() const { return UnderlyingTy; }
4236
4237 /// Return this attributed type's modified type with no qualifiers attached to
4238 /// it.
4239 QualType getModifiedType() const;
4240
4241 bool isSugared() const { return true; }
4242 QualType desugar() const;
4243
4244 static bool classof(const Type *T) {
4245 return T->getTypeClass() == MacroQualified;
4246 }
4247};
4248
4249/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4250class TypeOfExprType : public Type {
4251 Expr *TOExpr;
4252
4253protected:
4254 friend class ASTContext; // ASTContext creates these.
4255
4256 TypeOfExprType(Expr *E, QualType can = QualType());
4257
4258public:
4259 Expr *getUnderlyingExpr() const { return TOExpr; }
4260
4261 /// Remove a single level of sugar.
4262 QualType desugar() const;
4263
4264 /// Returns whether this type directly provides sugar.
4265 bool isSugared() const;
4266
4267 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4268};
4269
4270/// Internal representation of canonical, dependent
4271/// `typeof(expr)` types.
4272///
4273/// This class is used internally by the ASTContext to manage
4274/// canonical, dependent types, only. Clients will only see instances
4275/// of this class via TypeOfExprType nodes.
4276class DependentTypeOfExprType
4277 : public TypeOfExprType, public llvm::FoldingSetNode {
4278 const ASTContext &Context;
4279
4280public:
4281 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4282 : TypeOfExprType(E), Context(Context) {}
4283
4284 void Profile(llvm::FoldingSetNodeID &ID) {
4285 Profile(ID, Context, getUnderlyingExpr());
4286 }
4287
4288 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4289 Expr *E);
4290};
4291
4292/// Represents `typeof(type)`, a GCC extension.
4293class TypeOfType : public Type {
4294 friend class ASTContext; // ASTContext creates these.
4295
4296 QualType TOType;
4297
4298 TypeOfType(QualType T, QualType can)
4299 : Type(TypeOf, can, T->isDependentType(),
4300 T->isInstantiationDependentType(),
4301 T->isVariablyModifiedType(),
4302 T->containsUnexpandedParameterPack()),
4303 TOType(T) {
4304 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4304, __PRETTY_FUNCTION__))
;
4305 }
4306
4307public:
4308 QualType getUnderlyingType() const { return TOType; }
4309
4310 /// Remove a single level of sugar.
4311 QualType desugar() const { return getUnderlyingType(); }
4312
4313 /// Returns whether this type directly provides sugar.
4314 bool isSugared() const { return true; }
4315
4316 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4317};
4318
4319/// Represents the type `decltype(expr)` (C++11).
4320class DecltypeType : public Type {
4321 Expr *E;
4322 QualType UnderlyingType;
4323
4324protected:
4325 friend class ASTContext; // ASTContext creates these.
4326
4327 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4328
4329public:
4330 Expr *getUnderlyingExpr() const { return E; }
4331 QualType getUnderlyingType() const { return UnderlyingType; }
4332
4333 /// Remove a single level of sugar.
4334 QualType desugar() const;
4335
4336 /// Returns whether this type directly provides sugar.
4337 bool isSugared() const;
4338
4339 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4340};
4341
4342/// Internal representation of canonical, dependent
4343/// decltype(expr) types.
4344///
4345/// This class is used internally by the ASTContext to manage
4346/// canonical, dependent types, only. Clients will only see instances
4347/// of this class via DecltypeType nodes.
4348class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4349 const ASTContext &Context;
4350
4351public:
4352 DependentDecltypeType(const ASTContext &Context, Expr *E);
4353
4354 void Profile(llvm::FoldingSetNodeID &ID) {
4355 Profile(ID, Context, getUnderlyingExpr());
4356 }
4357
4358 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4359 Expr *E);
4360};
4361
4362/// A unary type transform, which is a type constructed from another.
4363class UnaryTransformType : public Type {
4364public:
4365 enum UTTKind {
4366 EnumUnderlyingType
4367 };
4368
4369private:
4370 /// The untransformed type.
4371 QualType BaseType;
4372
4373 /// The transformed type if not dependent, otherwise the same as BaseType.
4374 QualType UnderlyingType;
4375
4376 UTTKind UKind;
4377
4378protected:
4379 friend class ASTContext;
4380
4381 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4382 QualType CanonicalTy);
4383
4384public:
4385 bool isSugared() const { return !isDependentType(); }
4386 QualType desugar() const { return UnderlyingType; }
4387
4388 QualType getUnderlyingType() const { return UnderlyingType; }
4389 QualType getBaseType() const { return BaseType; }
4390
4391 UTTKind getUTTKind() const { return UKind; }
4392
4393 static bool classof(const Type *T) {
4394 return T->getTypeClass() == UnaryTransform;
4395 }
4396};
4397
4398/// Internal representation of canonical, dependent
4399/// __underlying_type(type) types.
4400///
4401/// This class is used internally by the ASTContext to manage
4402/// canonical, dependent types, only. Clients will only see instances
4403/// of this class via UnaryTransformType nodes.
4404class DependentUnaryTransformType : public UnaryTransformType,
4405 public llvm::FoldingSetNode {
4406public:
4407 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4408 UTTKind UKind);
4409
4410 void Profile(llvm::FoldingSetNodeID &ID) {
4411 Profile(ID, getBaseType(), getUTTKind());
4412 }
4413
4414 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4415 UTTKind UKind) {
4416 ID.AddPointer(BaseType.getAsOpaquePtr());
4417 ID.AddInteger((unsigned)UKind);
4418 }
4419};
4420
4421class TagType : public Type {
4422 friend class ASTReader;
4423
4424 /// Stores the TagDecl associated with this type. The decl may point to any
4425 /// TagDecl that declares the entity.
4426 TagDecl *decl;
4427
4428protected:
4429 TagType(TypeClass TC, const TagDecl *D, QualType can);
4430
4431public:
4432 TagDecl *getDecl() const;
4433
4434 /// Determines whether this type is in the process of being defined.
4435 bool isBeingDefined() const;
4436
4437 static bool classof(const Type *T) {
4438 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4439 }
4440};
4441
4442/// A helper class that allows the use of isa/cast/dyncast
4443/// to detect TagType objects of structs/unions/classes.
4444class RecordType : public TagType {
4445protected:
4446 friend class ASTContext; // ASTContext creates these.
4447
4448 explicit RecordType(const RecordDecl *D)
4449 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4450 explicit RecordType(TypeClass TC, RecordDecl *D)
4451 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4452
4453public:
4454 RecordDecl *getDecl() const {
4455 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4456 }
4457
4458 /// Recursively check all fields in the record for const-ness. If any field
4459 /// is declared const, return true. Otherwise, return false.
4460 bool hasConstFields() const;
4461
4462 bool isSugared() const { return false; }
4463 QualType desugar() const { return QualType(this, 0); }
4464
4465 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4466};
4467
4468/// A helper class that allows the use of isa/cast/dyncast
4469/// to detect TagType objects of enums.
4470class EnumType : public TagType {
4471 friend class ASTContext; // ASTContext creates these.
4472
4473 explicit EnumType(const EnumDecl *D)
4474 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4475
4476public:
4477 EnumDecl *getDecl() const {
4478 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4479 }
4480
4481 bool isSugared() const { return false; }
4482 QualType desugar() const { return QualType(this, 0); }
4483
4484 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4485};
4486
4487/// An attributed type is a type to which a type attribute has been applied.
4488///
4489/// The "modified type" is the fully-sugared type to which the attributed
4490/// type was applied; generally it is not canonically equivalent to the
4491/// attributed type. The "equivalent type" is the minimally-desugared type
4492/// which the type is canonically equivalent to.
4493///
4494/// For example, in the following attributed type:
4495/// int32_t __attribute__((vector_size(16)))
4496/// - the modified type is the TypedefType for int32_t
4497/// - the equivalent type is VectorType(16, int32_t)
4498/// - the canonical type is VectorType(16, int)
4499class AttributedType : public Type, public llvm::FoldingSetNode {
4500public:
4501 using Kind = attr::Kind;
4502
4503private:
4504 friend class ASTContext; // ASTContext creates these
4505
4506 QualType ModifiedType;
4507 QualType EquivalentType;
4508
4509 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4510 QualType equivalent)
4511 : Type(Attributed, canon, equivalent->isDependentType(),
4512 equivalent->isInstantiationDependentType(),
4513 equivalent->isVariablyModifiedType(),
4514 equivalent->containsUnexpandedParameterPack()),
4515 ModifiedType(modified), EquivalentType(equivalent) {
4516 AttributedTypeBits.AttrKind = attrKind;
4517 }
4518
4519public:
4520 Kind getAttrKind() const {
4521 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4522 }
4523
4524 QualType getModifiedType() const { return ModifiedType; }
4525 QualType getEquivalentType() const { return EquivalentType; }
4526
4527 bool isSugared() const { return true; }
4528 QualType desugar() const { return getEquivalentType(); }
4529
4530 /// Does this attribute behave like a type qualifier?
4531 ///
4532 /// A type qualifier adjusts a type to provide specialized rules for
4533 /// a specific object, like the standard const and volatile qualifiers.
4534 /// This includes attributes controlling things like nullability,
4535 /// address spaces, and ARC ownership. The value of the object is still
4536 /// largely described by the modified type.
4537 ///
4538 /// In contrast, many type attributes "rewrite" their modified type to
4539 /// produce a fundamentally different type, not necessarily related in any
4540 /// formalizable way to the original type. For example, calling convention
4541 /// and vector attributes are not simple type qualifiers.
4542 ///
4543 /// Type qualifiers are often, but not always, reflected in the canonical
4544 /// type.
4545 bool isQualifier() const;
4546
4547 bool isMSTypeSpec() const;
4548
4549 bool isCallingConv() const;
4550
4551 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4552
4553 /// Retrieve the attribute kind corresponding to the given
4554 /// nullability kind.
4555 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4556 switch (kind) {
4557 case NullabilityKind::NonNull:
4558 return attr::TypeNonNull;
4559
4560 case NullabilityKind::Nullable:
4561 return attr::TypeNullable;
4562
4563 case NullabilityKind::Unspecified:
4564 return attr::TypeNullUnspecified;
4565 }
4566 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4566)
;
4567 }
4568
4569 /// Strip off the top-level nullability annotation on the given
4570 /// type, if it's there.
4571 ///
4572 /// \param T The type to strip. If the type is exactly an
4573 /// AttributedType specifying nullability (without looking through
4574 /// type sugar), the nullability is returned and this type changed
4575 /// to the underlying modified type.
4576 ///
4577 /// \returns the top-level nullability, if present.
4578 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4579
4580 void Profile(llvm::FoldingSetNodeID &ID) {
4581 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4582 }
4583
4584 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4585 QualType modified, QualType equivalent) {
4586 ID.AddInteger(attrKind);
4587 ID.AddPointer(modified.getAsOpaquePtr());
4588 ID.AddPointer(equivalent.getAsOpaquePtr());
4589 }
4590
4591 static bool classof(const Type *T) {
4592 return T->getTypeClass() == Attributed;
4593 }
4594};
4595
4596class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4597 friend class ASTContext; // ASTContext creates these
4598
4599 // Helper data collector for canonical types.
4600 struct CanonicalTTPTInfo {
4601 unsigned Depth : 15;
4602 unsigned ParameterPack : 1;
4603 unsigned Index : 16;
4604 };
4605
4606 union {
4607 // Info for the canonical type.
4608 CanonicalTTPTInfo CanTTPTInfo;
4609
4610 // Info for the non-canonical type.
4611 TemplateTypeParmDecl *TTPDecl;
4612 };
4613
4614 /// Build a non-canonical type.
4615 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4616 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4617 /*InstantiationDependent=*/true,
4618 /*VariablyModified=*/false,
4619 Canon->containsUnexpandedParameterPack()),
4620 TTPDecl(TTPDecl) {}
4621
4622 /// Build the canonical type.
4623 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4624 : Type(TemplateTypeParm, QualType(this, 0),
4625 /*Dependent=*/true,
4626 /*InstantiationDependent=*/true,
4627 /*VariablyModified=*/false, PP) {
4628 CanTTPTInfo.Depth = D;
4629 CanTTPTInfo.Index = I;
4630 CanTTPTInfo.ParameterPack = PP;
4631 }
4632
4633 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4634 QualType Can = getCanonicalTypeInternal();
4635 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4636 }
4637
4638public:
4639 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4640 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4641 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4642
4643 TemplateTypeParmDecl *getDecl() const {
4644 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4645 }
4646
4647 IdentifierInfo *getIdentifier() const;
4648
4649 bool isSugared() const { return false; }
4650 QualType desugar() const { return QualType(this, 0); }
4651
4652 void Profile(llvm::FoldingSetNodeID &ID) {
4653 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4654 }
4655
4656 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4657 unsigned Index, bool ParameterPack,
4658 TemplateTypeParmDecl *TTPDecl) {
4659 ID.AddInteger(Depth);
4660 ID.AddInteger(Index);
4661 ID.AddBoolean(ParameterPack);
4662 ID.AddPointer(TTPDecl);
4663 }
4664
4665 static bool classof(const Type *T) {
4666 return T->getTypeClass() == TemplateTypeParm;
4667 }
4668};
4669
4670/// Represents the result of substituting a type for a template
4671/// type parameter.
4672///
4673/// Within an instantiated template, all template type parameters have
4674/// been replaced with these. They are used solely to record that a
4675/// type was originally written as a template type parameter;
4676/// therefore they are never canonical.
4677class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4678 friend class ASTContext;
4679
4680 // The original type parameter.
4681 const TemplateTypeParmType *Replaced;
4682
4683 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4684 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4685 Canon->isInstantiationDependentType(),
4686 Canon->isVariablyModifiedType(),
4687 Canon->containsUnexpandedParameterPack()),
4688 Replaced(Param) {}
4689
4690public:
4691 /// Gets the template parameter that was substituted for.
4692 const TemplateTypeParmType *getReplacedParameter() const {
4693 return Replaced;
4694 }
4695
4696 /// Gets the type that was substituted for the template
4697 /// parameter.
4698 QualType getReplacementType() const {
4699 return getCanonicalTypeInternal();
4700 }
4701
4702 bool isSugared() const { return true; }
4703 QualType desugar() const { return getReplacementType(); }
4704
4705 void Profile(llvm::FoldingSetNodeID &ID) {
4706 Profile(ID, getReplacedParameter(), getReplacementType());
4707 }
4708
4709 static void Profile(llvm::FoldingSetNodeID &ID,
4710 const TemplateTypeParmType *Replaced,
4711 QualType Replacement) {
4712 ID.AddPointer(Replaced);
4713 ID.AddPointer(Replacement.getAsOpaquePtr());
4714 }
4715
4716 static bool classof(const Type *T) {
4717 return T->getTypeClass() == SubstTemplateTypeParm;
4718 }
4719};
4720
4721/// Represents the result of substituting a set of types for a template
4722/// type parameter pack.
4723///
4724/// When a pack expansion in the source code contains multiple parameter packs
4725/// and those parameter packs correspond to different levels of template
4726/// parameter lists, this type node is used to represent a template type
4727/// parameter pack from an outer level, which has already had its argument pack
4728/// substituted but that still lives within a pack expansion that itself
4729/// could not be instantiated. When actually performing a substitution into
4730/// that pack expansion (e.g., when all template parameters have corresponding
4731/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4732/// at the current pack substitution index.
4733class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4734 friend class ASTContext;
4735
4736 /// The original type parameter.
4737 const TemplateTypeParmType *Replaced;
4738
4739 /// A pointer to the set of template arguments that this
4740 /// parameter pack is instantiated with.
4741 const TemplateArgument *Arguments;
4742
4743 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4744 QualType Canon,
4745 const TemplateArgument &ArgPack);
4746
4747public:
4748 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4749
4750 /// Gets the template parameter that was substituted for.
4751 const TemplateTypeParmType *getReplacedParameter() const {
4752 return Replaced;
4753 }
4754
4755 unsigned getNumArgs() const {
4756 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4757 }
4758
4759 bool isSugared() const { return false; }
4760 QualType desugar() const { return QualType(this, 0); }
4761
4762 TemplateArgument getArgumentPack() const;
4763
4764 void Profile(llvm::FoldingSetNodeID &ID);
4765 static void Profile(llvm::FoldingSetNodeID &ID,
4766 const TemplateTypeParmType *Replaced,
4767 const TemplateArgument &ArgPack);
4768
4769 static bool classof(const Type *T) {
4770 return T->getTypeClass() == SubstTemplateTypeParmPack;
4771 }
4772};
4773
4774/// Common base class for placeholders for types that get replaced by
4775/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4776/// class template types, and (eventually) constrained type names from the C++
4777/// Concepts TS.
4778///
4779/// These types are usually a placeholder for a deduced type. However, before
4780/// the initializer is attached, or (usually) if the initializer is
4781/// type-dependent, there is no deduced type and the type is canonical. In
4782/// the latter case, it is also a dependent type.
4783class DeducedType : public Type {
4784protected:
4785 DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4786 bool IsInstantiationDependent, bool ContainsParameterPack)
4787 : Type(TC,
4788 // FIXME: Retain the sugared deduced type?
4789 DeducedAsType.isNull() ? QualType(this, 0)
4790 : DeducedAsType.getCanonicalType(),
4791 IsDependent, IsInstantiationDependent,
4792 /*VariablyModified=*/false, ContainsParameterPack) {
4793 if (!DeducedAsType.isNull()) {
4794 if (DeducedAsType->isDependentType())
4795 setDependent();
4796 if (DeducedAsType->isInstantiationDependentType())
4797 setInstantiationDependent();
4798 if (DeducedAsType->containsUnexpandedParameterPack())
4799 setContainsUnexpandedParameterPack();
4800 }
4801 }
4802
4803public:
4804 bool isSugared() const { return !isCanonicalUnqualified(); }
4805 QualType desugar() const { return getCanonicalTypeInternal(); }
4806
4807 /// Get the type deduced for this placeholder type, or null if it's
4808 /// either not been deduced or was deduced to a dependent type.
4809 QualType getDeducedType() const {
4810 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4811 }
4812 bool isDeduced() const {
4813 return !isCanonicalUnqualified() || isDependentType();
4814 }
4815
4816 static bool classof(const Type *T) {
4817 return T->getTypeClass() == Auto ||
4818 T->getTypeClass() == DeducedTemplateSpecialization;
4819 }
4820};
4821
4822/// Represents a C++11 auto or C++14 decltype(auto) type.
4823class AutoType : public DeducedType, public llvm::FoldingSetNode {
4824 friend class ASTContext; // ASTContext creates these
4825
4826 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4827 bool IsDeducedAsDependent, bool IsDeducedAsPack)
4828 : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4829 IsDeducedAsDependent, IsDeducedAsPack) {
4830 AutoTypeBits.Keyword = (unsigned)Keyword;
4831 }
4832
4833public:
4834 bool isDecltypeAuto() const {
4835 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4836 }
4837
4838 AutoTypeKeyword getKeyword() const {
4839 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4840 }
4841
4842 void Profile(llvm::FoldingSetNodeID &ID) {
4843 Profile(ID, getDeducedType(), getKeyword(), isDependentType(),
4844 containsUnexpandedParameterPack());
4845 }
4846
4847 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4848 AutoTypeKeyword Keyword, bool IsDependent, bool IsPack) {
4849 ID.AddPointer(Deduced.getAsOpaquePtr());
4850 ID.AddInteger((unsigned)Keyword);
4851 ID.AddBoolean(IsDependent);
4852 ID.AddBoolean(IsPack);
4853 }
4854
4855 static bool classof(const Type *T) {
4856 return T->getTypeClass() == Auto;
4857 }
4858};
4859
4860/// Represents a C++17 deduced template specialization type.
4861class DeducedTemplateSpecializationType : public DeducedType,
4862 public llvm::FoldingSetNode {
4863 friend class ASTContext; // ASTContext creates these
4864
4865 /// The name of the template whose arguments will be deduced.
4866 TemplateName Template;
4867
4868 DeducedTemplateSpecializationType(TemplateName Template,
4869 QualType DeducedAsType,
4870 bool IsDeducedAsDependent)
4871 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4872 IsDeducedAsDependent || Template.isDependent(),
4873 IsDeducedAsDependent || Template.isInstantiationDependent(),
4874 Template.containsUnexpandedParameterPack()),
4875 Template(Template) {}
4876
4877public:
4878 /// Retrieve the name of the template that we are deducing.
4879 TemplateName getTemplateName() const { return Template;}
4880
4881 void Profile(llvm::FoldingSetNodeID &ID) {
4882 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4883 }
4884
4885 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4886 QualType Deduced, bool IsDependent) {
4887 Template.Profile(ID);
4888 ID.AddPointer(Deduced.getAsOpaquePtr());
4889 ID.AddBoolean(IsDependent);
4890 }
4891
4892 static bool classof(const Type *T) {
4893 return T->getTypeClass() == DeducedTemplateSpecialization;
4894 }
4895};
4896
4897/// Represents a type template specialization; the template
4898/// must be a class template, a type alias template, or a template
4899/// template parameter. A template which cannot be resolved to one of
4900/// these, e.g. because it is written with a dependent scope
4901/// specifier, is instead represented as a
4902/// @c DependentTemplateSpecializationType.
4903///
4904/// A non-dependent template specialization type is always "sugar",
4905/// typically for a \c RecordType. For example, a class template
4906/// specialization type of \c vector<int> will refer to a tag type for
4907/// the instantiation \c std::vector<int, std::allocator<int>>
4908///
4909/// Template specializations are dependent if either the template or
4910/// any of the template arguments are dependent, in which case the
4911/// type may also be canonical.
4912///
4913/// Instances of this type are allocated with a trailing array of
4914/// TemplateArguments, followed by a QualType representing the
4915/// non-canonical aliased type when the template is a type alias
4916/// template.
4917class alignas(8) TemplateSpecializationType
4918 : public Type,
4919 public llvm::FoldingSetNode {
4920 friend class ASTContext; // ASTContext creates these
4921
4922 /// The name of the template being specialized. This is
4923 /// either a TemplateName::Template (in which case it is a
4924 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4925 /// TypeAliasTemplateDecl*), a
4926 /// TemplateName::SubstTemplateTemplateParmPack, or a
4927 /// TemplateName::SubstTemplateTemplateParm (in which case the
4928 /// replacement must, recursively, be one of these).
4929 TemplateName Template;
4930
4931 TemplateSpecializationType(TemplateName T,
4932 ArrayRef<TemplateArgument> Args,
4933 QualType Canon,
4934 QualType Aliased);
4935
4936public:
4937 /// Determine whether any of the given template arguments are dependent.
4938 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4939 bool &InstantiationDependent);
4940
4941 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4942 bool &InstantiationDependent);
4943
4944 /// True if this template specialization type matches a current
4945 /// instantiation in the context in which it is found.
4946 bool isCurrentInstantiation() const {
4947 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4948 }
4949
4950 /// Determine if this template specialization type is for a type alias
4951 /// template that has been substituted.
4952 ///
4953 /// Nearly every template specialization type whose template is an alias
4954 /// template will be substituted. However, this is not the case when
4955 /// the specialization contains a pack expansion but the template alias
4956 /// does not have a corresponding parameter pack, e.g.,
4957 ///
4958 /// \code
4959 /// template<typename T, typename U, typename V> struct S;
4960 /// template<typename T, typename U> using A = S<T, int, U>;
4961 /// template<typename... Ts> struct X {
4962 /// typedef A<Ts...> type; // not a type alias
4963 /// };
4964 /// \endcode
4965 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
4966
4967 /// Get the aliased type, if this is a specialization of a type alias
4968 /// template.
4969 QualType getAliasedType() const {
4970 assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization"
) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4970, __PRETTY_FUNCTION__))
;
4971 return *reinterpret_cast<const QualType*>(end());
4972 }
4973
4974 using iterator = const TemplateArgument *;
4975
4976 iterator begin() const { return getArgs(); }
4977 iterator end() const; // defined inline in TemplateBase.h
4978
4979 /// Retrieve the name of the template that we are specializing.
4980 TemplateName getTemplateName() const { return Template; }
4981
4982 /// Retrieve the template arguments.
4983 const TemplateArgument *getArgs() const {
4984 return reinterpret_cast<const TemplateArgument *>(this + 1);
4985 }
4986
4987 /// Retrieve the number of template arguments.
4988 unsigned getNumArgs() const {
4989 return TemplateSpecializationTypeBits.NumArgs;
4990 }
4991
4992 /// Retrieve a specific template argument as a type.
4993 /// \pre \c isArgType(Arg)
4994 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4995
4996 ArrayRef<TemplateArgument> template_arguments() const {
4997 return {getArgs(), getNumArgs()};
4998 }
4999
5000 bool isSugared() const {
5001 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5002 }
5003
5004 QualType desugar() const {
5005 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5006 }
5007
5008 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5009 Profile(ID, Template, template_arguments(), Ctx);
5010 if (isTypeAlias())
5011 getAliasedType().Profile(ID);
5012 }
5013
5014 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5015 ArrayRef<TemplateArgument> Args,
5016 const ASTContext &Context);
5017
5018 static bool classof(const Type *T) {
5019 return T->getTypeClass() == TemplateSpecialization;
5020 }
5021};
5022
5023/// Print a template argument list, including the '<' and '>'
5024/// enclosing the template arguments.
5025void printTemplateArgumentList(raw_ostream &OS,
5026 ArrayRef<TemplateArgument> Args,
5027 const PrintingPolicy &Policy);
5028
5029void printTemplateArgumentList(raw_ostream &OS,
5030 ArrayRef<TemplateArgumentLoc> Args,
5031 const PrintingPolicy &Policy);
5032
5033void printTemplateArgumentList(raw_ostream &OS,
5034 const TemplateArgumentListInfo &Args,
5035 const PrintingPolicy &Policy);
5036
5037/// The injected class name of a C++ class template or class
5038/// template partial specialization. Used to record that a type was
5039/// spelled with a bare identifier rather than as a template-id; the
5040/// equivalent for non-templated classes is just RecordType.
5041///
5042/// Injected class name types are always dependent. Template
5043/// instantiation turns these into RecordTypes.
5044///
5045/// Injected class name types are always canonical. This works
5046/// because it is impossible to compare an injected class name type
5047/// with the corresponding non-injected template type, for the same
5048/// reason that it is impossible to directly compare template
5049/// parameters from different dependent contexts: injected class name
5050/// types can only occur within the scope of a particular templated
5051/// declaration, and within that scope every template specialization
5052/// will canonicalize to the injected class name (when appropriate
5053/// according to the rules of the language).
5054class InjectedClassNameType : public Type {
5055 friend class ASTContext; // ASTContext creates these.
5056 friend class ASTNodeImporter;
5057 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5058 // currently suitable for AST reading, too much
5059 // interdependencies.
5060
5061 CXXRecordDecl *Decl;
5062
5063 /// The template specialization which this type represents.
5064 /// For example, in
5065 /// template <class T> class A { ... };
5066 /// this is A<T>, whereas in
5067 /// template <class X, class Y> class A<B<X,Y> > { ... };
5068 /// this is A<B<X,Y> >.
5069 ///
5070 /// It is always unqualified, always a template specialization type,
5071 /// and always dependent.
5072 QualType InjectedType;
5073
5074 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5075 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
5076 /*InstantiationDependent=*/true,
5077 /*VariablyModified=*/false,
5078 /*ContainsUnexpandedParameterPack=*/false),
5079 Decl(D), InjectedType(TST) {
5080 assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast<
void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5080, __PRETTY_FUNCTION__))
;
5081 assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail
("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5081, __PRETTY_FUNCTION__))
;
5082 assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail
("TST->isDependentType()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5082, __PRETTY_FUNCTION__))
;
5083 }
5084
5085public:
5086 QualType getInjectedSpecializationType() const { return InjectedType; }
5087
5088 const TemplateSpecializationType *getInjectedTST() const {
5089 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5090 }
5091
5092 TemplateName getTemplateName() const {
5093 return getInjectedTST()->getTemplateName();
5094 }
5095
5096 CXXRecordDecl *getDecl() const;
5097
5098 bool isSugared() const { return false; }
5099 QualType desugar() const { return QualType(this, 0); }
5100
5101 static bool classof(const Type *T) {
5102 return T->getTypeClass() == InjectedClassName;
5103 }
5104};
5105
5106/// The kind of a tag type.
5107enum TagTypeKind {
5108 /// The "struct" keyword.
5109 TTK_Struct,
5110
5111 /// The "__interface" keyword.
5112 TTK_Interface,
5113
5114 /// The "union" keyword.
5115 TTK_Union,
5116
5117 /// The "class" keyword.
5118 TTK_Class,
5119
5120 /// The "enum" keyword.
5121 TTK_Enum
5122};
5123
5124/// The elaboration keyword that precedes a qualified type name or
5125/// introduces an elaborated-type-specifier.
5126enum ElaboratedTypeKeyword {
5127 /// The "struct" keyword introduces the elaborated-type-specifier.
5128 ETK_Struct,
5129
5130 /// The "__interface" keyword introduces the elaborated-type-specifier.
5131 ETK_Interface,
5132
5133 /// The "union" keyword introduces the elaborated-type-specifier.
5134 ETK_Union,
5135
5136 /// The "class" keyword introduces the elaborated-type-specifier.
5137 ETK_Class,
5138
5139 /// The "enum" keyword introduces the elaborated-type-specifier.
5140 ETK_Enum,
5141
5142 /// The "typename" keyword precedes the qualified type name, e.g.,
5143 /// \c typename T::type.
5144 ETK_Typename,
5145
5146 /// No keyword precedes the qualified type name.
5147 ETK_None
5148};
5149
5150/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5151/// The keyword in stored in the free bits of the base class.
5152/// Also provides a few static helpers for converting and printing
5153/// elaborated type keyword and tag type kind enumerations.
5154class TypeWithKeyword : public Type {
5155protected:
5156 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5157 QualType Canonical, bool Dependent,
5158 bool InstantiationDependent, bool VariablyModified,
5159 bool ContainsUnexpandedParameterPack)
5160 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
5161 ContainsUnexpandedParameterPack) {
5162 TypeWithKeywordBits.Keyword = Keyword;
5163 }
5164
5165public:
5166 ElaboratedTypeKeyword getKeyword() const {
5167 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5168 }
5169
5170 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5171 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5172
5173 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5174 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5175 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5176
5177 /// Converts a TagTypeKind into an elaborated type keyword.
5178 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5179
5180 /// Converts an elaborated type keyword into a TagTypeKind.
5181 /// It is an error to provide an elaborated type keyword
5182 /// which *isn't* a tag kind here.
5183 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5184
5185 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5186
5187 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5188
5189 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5190 return getKeywordName(getKeywordForTagTypeKind(Kind));
5191 }
5192
5193 class CannotCastToThisType {};
5194 static CannotCastToThisType classof(const Type *);
5195};
5196
5197/// Represents a type that was referred to using an elaborated type
5198/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5199/// or both.
5200///
5201/// This type is used to keep track of a type name as written in the
5202/// source code, including tag keywords and any nested-name-specifiers.
5203/// The type itself is always "sugar", used to express what was written
5204/// in the source code but containing no additional semantic information.
5205class ElaboratedType final
5206 : public TypeWithKeyword,
5207 public llvm::FoldingSetNode,
5208 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5209 friend class ASTContext; // ASTContext creates these
5210 friend TrailingObjects;
5211
5212 /// The nested name specifier containing the qualifier.
5213 NestedNameSpecifier *NNS;
5214
5215 /// The type that this qualified name refers to.
5216 QualType NamedType;
5217
5218 /// The (re)declaration of this tag type owned by this occurrence is stored
5219 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5220 /// it, or obtain a null pointer if there is none.
5221
5222 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5223 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5224 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5225 NamedType->isDependentType(),
5226 NamedType->isInstantiationDependentType(),
5227 NamedType->isVariablyModifiedType(),
5228 NamedType->containsUnexpandedParameterPack()),
5229 NNS(NNS), NamedType(NamedType) {
5230 ElaboratedTypeBits.HasOwnedTagDecl = false;
5231 if (OwnedTagDecl) {
5232 ElaboratedTypeBits.HasOwnedTagDecl = true;
5233 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5234 }
5235 assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
5236 "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
5237 "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
;
5238 }
5239
5240public:
5241 /// Retrieve the qualification on this type.
5242 NestedNameSpecifier *getQualifier() const { return NNS; }
5243
5244 /// Retrieve the type named by the qualified-id.
5245 QualType getNamedType() const { return NamedType; }
5246
5247 /// Remove a single level of sugar.
5248 QualType desugar() const { return getNamedType(); }
5249
5250 /// Returns whether this type directly provides sugar.
5251 bool isSugared() const { return true; }
5252
5253 /// Return the (re)declaration of this type owned by this occurrence of this
5254 /// type, or nullptr if there is none.
5255 TagDecl *getOwnedTagDecl() const {
5256 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5257 : nullptr;
5258 }
5259
5260 void Profile(llvm::FoldingSetNodeID &ID) {
5261 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5262 }
5263
5264 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5265 NestedNameSpecifier *NNS, QualType NamedType,
5266 TagDecl *OwnedTagDecl) {
5267 ID.AddInteger(Keyword);
5268 ID.AddPointer(NNS);
5269 NamedType.Profile(ID);
5270 ID.AddPointer(OwnedTagDecl);
5271 }
5272
5273 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5274};
5275
5276/// Represents a qualified type name for which the type name is
5277/// dependent.
5278///
5279/// DependentNameType represents a class of dependent types that involve a
5280/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5281/// name of a type. The DependentNameType may start with a "typename" (for a
5282/// typename-specifier), "class", "struct", "union", or "enum" (for a
5283/// dependent elaborated-type-specifier), or nothing (in contexts where we
5284/// know that we must be referring to a type, e.g., in a base class specifier).
5285/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5286/// mode, this type is used with non-dependent names to delay name lookup until
5287/// instantiation.
5288class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5289 friend class ASTContext; // ASTContext creates these
5290
5291 /// The nested name specifier containing the qualifier.
5292 NestedNameSpecifier *NNS;
5293
5294 /// The type that this typename specifier refers to.
5295 const IdentifierInfo *Name;
5296
5297 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5298 const IdentifierInfo *Name, QualType CanonType)
5299 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
5300 /*InstantiationDependent=*/true,
5301 /*VariablyModified=*/false,
5302 NNS->containsUnexpandedParameterPack()),
5303 NNS(NNS), Name(Name) {}
5304
5305public:
5306 /// Retrieve the qualification on this type.
5307 NestedNameSpecifier *getQualifier() const { return NNS; }
5308
5309 /// Retrieve the type named by the typename specifier as an identifier.
5310 ///
5311 /// This routine will return a non-NULL identifier pointer when the
5312 /// form of the original typename was terminated by an identifier,
5313 /// e.g., "typename T::type".
5314 const IdentifierInfo *getIdentifier() const {
5315 return Name;
5316 }
5317
5318 bool isSugared() const { return false; }
5319 QualType desugar() const { return QualType(this, 0); }
5320
5321 void Profile(llvm::FoldingSetNodeID &ID) {
5322 Profile(ID, getKeyword(), NNS, Name);
5323 }
5324
5325 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5326 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5327 ID.AddInteger(Keyword);
5328 ID.AddPointer(NNS);
5329 ID.AddPointer(Name);
5330 }
5331
5332 static bool classof(const Type *T) {
5333 return T->getTypeClass() == DependentName;
5334 }
5335};
5336
5337/// Represents a template specialization type whose template cannot be
5338/// resolved, e.g.
5339/// A<T>::template B<T>
5340class alignas(8) DependentTemplateSpecializationType
5341 : public TypeWithKeyword,
5342 public llvm::FoldingSetNode {
5343 friend class ASTContext; // ASTContext creates these
5344
5345 /// The nested name specifier containing the qualifier.
5346 NestedNameSpecifier *NNS;
5347
5348 /// The identifier of the template.
5349 const IdentifierInfo *Name;
5350
5351 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5352 NestedNameSpecifier *NNS,
5353 const IdentifierInfo *Name,
5354 ArrayRef<TemplateArgument> Args,
5355 QualType Canon);
5356
5357 const TemplateArgument *getArgBuffer() const {
5358 return reinterpret_cast<const TemplateArgument*>(this+1);
5359 }
5360
5361 TemplateArgument *getArgBuffer() {
5362 return reinterpret_cast<TemplateArgument*>(this+1);
5363 }
5364
5365public:
5366 NestedNameSpecifier *getQualifier() const { return NNS; }
5367 const IdentifierInfo *getIdentifier() const { return Name; }
5368
5369 /// Retrieve the template arguments.
5370 const TemplateArgument *getArgs() const {
5371 return getArgBuffer();
5372 }
5373
5374 /// Retrieve the number of template arguments.
5375 unsigned getNumArgs() const {
5376 return DependentTemplateSpecializationTypeBits.NumArgs;
5377 }
5378
5379 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5380
5381 ArrayRef<TemplateArgument> template_arguments() const {
5382 return {getArgs(), getNumArgs()};
5383 }
5384
5385 using iterator = const TemplateArgument *;
5386
5387 iterator begin() const { return getArgs(); }
5388 iterator end() const; // inline in TemplateBase.h
5389
5390 bool isSugared() const { return false; }
5391 QualType desugar() const { return QualType(this, 0); }
5392
5393 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5394 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5395 }
5396
5397 static void Profile(llvm::FoldingSetNodeID &ID,
5398 const ASTContext &Context,
5399 ElaboratedTypeKeyword Keyword,
5400 NestedNameSpecifier *Qualifier,
5401 const IdentifierInfo *Name,
5402 ArrayRef<TemplateArgument> Args);
5403
5404 static bool classof(const Type *T) {
5405 return T->getTypeClass() == DependentTemplateSpecialization;
5406 }
5407};
5408
5409/// Represents a pack expansion of types.
5410///
5411/// Pack expansions are part of C++11 variadic templates. A pack
5412/// expansion contains a pattern, which itself contains one or more
5413/// "unexpanded" parameter packs. When instantiated, a pack expansion
5414/// produces a series of types, each instantiated from the pattern of
5415/// the expansion, where the Ith instantiation of the pattern uses the
5416/// Ith arguments bound to each of the unexpanded parameter packs. The
5417/// pack expansion is considered to "expand" these unexpanded
5418/// parameter packs.
5419///
5420/// \code
5421/// template<typename ...Types> struct tuple;
5422///
5423/// template<typename ...Types>
5424/// struct tuple_of_references {
5425/// typedef tuple<Types&...> type;
5426/// };
5427/// \endcode
5428///
5429/// Here, the pack expansion \c Types&... is represented via a
5430/// PackExpansionType whose pattern is Types&.
5431class PackExpansionType : public Type, public llvm::FoldingSetNode {
5432 friend class ASTContext; // ASTContext creates these
5433
5434 /// The pattern of the pack expansion.
5435 QualType Pattern;
5436
5437 PackExpansionType(QualType Pattern, QualType Canon,
5438 Optional<unsigned> NumExpansions)
5439 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5440 /*InstantiationDependent=*/true,
5441 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5442 /*ContainsUnexpandedParameterPack=*/false),
5443 Pattern(Pattern) {
5444 PackExpansionTypeBits.NumExpansions =
5445 NumExpansions ? *NumExpansions + 1 : 0;
5446 }
5447
5448public:
5449 /// Retrieve the pattern of this pack expansion, which is the
5450 /// type that will be repeatedly instantiated when instantiating the
5451 /// pack expansion itself.
5452 QualType getPattern() const { return Pattern; }
5453
5454 /// Retrieve the number of expansions that this pack expansion will
5455 /// generate, if known.
5456 Optional<unsigned> getNumExpansions() const {
5457 if (PackExpansionTypeBits.NumExpansions)
5458 return PackExpansionTypeBits.NumExpansions - 1;
5459 return None;
5460 }
5461
5462 bool isSugared() const { return !Pattern->isDependentType(); }
5463 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5464
5465 void Profile(llvm::FoldingSetNodeID &ID) {
5466 Profile(ID, getPattern(), getNumExpansions());
5467 }
5468
5469 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5470 Optional<unsigned> NumExpansions) {
5471 ID.AddPointer(Pattern.getAsOpaquePtr());
5472 ID.AddBoolean(NumExpansions.hasValue());
5473 if (NumExpansions)
5474 ID.AddInteger(*NumExpansions);
5475 }
5476
5477 static bool classof(const Type *T) {
5478 return T->getTypeClass() == PackExpansion;
5479 }
5480};
5481
5482/// This class wraps the list of protocol qualifiers. For types that can
5483/// take ObjC protocol qualifers, they can subclass this class.
5484template <class T>
5485class ObjCProtocolQualifiers {
5486protected:
5487 ObjCProtocolQualifiers() = default;
5488
5489 ObjCProtocolDecl * const *getProtocolStorage() const {
5490 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5491 }
5492
5493 ObjCProtocolDecl **getProtocolStorage() {
5494 return static_cast<T*>(this)->getProtocolStorageImpl();
5495 }
5496
5497 void setNumProtocols(unsigned N) {
5498 static_cast<T*>(this)->setNumProtocolsImpl(N);
5499 }
5500
5501 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5502 setNumProtocols(protocols.size());
5503 assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5504, __PRETTY_FUNCTION__))
5504 "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5504, __PRETTY_FUNCTION__))
;
5505 if (!protocols.empty())
5506 memcpy(getProtocolStorage(), protocols.data(),
5507 protocols.size() * sizeof(ObjCProtocolDecl*));
5508 }
5509
5510public:
5511 using qual_iterator = ObjCProtocolDecl * const *;
5512 using qual_range = llvm::iterator_range<qual_iterator>;
5513
5514 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5515 qual_iterator qual_begin() const { return getProtocolStorage(); }
5516 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5517
5518 bool qual_empty() const { return getNumProtocols() == 0; }
5519
5520 /// Return the number of qualifying protocols in this type, or 0 if
5521 /// there are none.
5522 unsigned getNumProtocols() const {
5523 return static_cast<const T*>(this)->getNumProtocolsImpl();
5524 }
5525
5526 /// Fetch a protocol by index.
5527 ObjCProtocolDecl *getProtocol(unsigned I) const {
5528 assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access"
) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5528, __PRETTY_FUNCTION__))
;
5529 return qual_begin()[I];
5530 }
5531
5532 /// Retrieve all of the protocol qualifiers.
5533 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5534 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5535 }
5536};
5537
5538/// Represents a type parameter type in Objective C. It can take
5539/// a list of protocols.
5540class ObjCTypeParamType : public Type,
5541 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5542 public llvm::FoldingSetNode {
5543 friend class ASTContext;
5544 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5545
5546 /// The number of protocols stored on this type.
5547 unsigned NumProtocols : 6;
5548
5549 ObjCTypeParamDecl *OTPDecl;
5550
5551 /// The protocols are stored after the ObjCTypeParamType node. In the
5552 /// canonical type, the list of protocols are sorted alphabetically
5553 /// and uniqued.
5554 ObjCProtocolDecl **getProtocolStorageImpl();
5555
5556 /// Return the number of qualifying protocols in this interface type,
5557 /// or 0 if there are none.
5558 unsigned getNumProtocolsImpl() const {
5559 return NumProtocols;
5560 }
5561
5562 void setNumProtocolsImpl(unsigned N) {
5563 NumProtocols = N;
5564 }
5565
5566 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5567 QualType can,
5568 ArrayRef<ObjCProtocolDecl *> protocols);
5569
5570public:
5571 bool isSugared() const { return true; }
5572 QualType desugar() const;
5573
5574 static bool classof(const Type *T) {
5575 return T->getTypeClass() == ObjCTypeParam;
5576 }
5577
5578 void Profile(llvm::FoldingSetNodeID &ID);
5579 static void Profile(llvm::FoldingSetNodeID &ID,
5580 const ObjCTypeParamDecl *OTPDecl,
5581 ArrayRef<ObjCProtocolDecl *> protocols);
5582
5583 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5584};
5585
5586/// Represents a class type in Objective C.
5587///
5588/// Every Objective C type is a combination of a base type, a set of
5589/// type arguments (optional, for parameterized classes) and a list of
5590/// protocols.
5591///
5592/// Given the following declarations:
5593/// \code
5594/// \@class C<T>;
5595/// \@protocol P;
5596/// \endcode
5597///
5598/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5599/// with base C and no protocols.
5600///
5601/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5602/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5603/// protocol list.
5604/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5605/// and protocol list [P].
5606///
5607/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5608/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5609/// and no protocols.
5610///
5611/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5612/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5613/// this should get its own sugar class to better represent the source.
5614class ObjCObjectType : public Type,
5615 public ObjCProtocolQualifiers<ObjCObjectType> {
5616 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5617
5618 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5619 // after the ObjCObjectPointerType node.
5620 // ObjCObjectType.NumProtocols - the number of protocols stored
5621 // after the type arguments of ObjCObjectPointerType node.
5622 //
5623 // These protocols are those written directly on the type. If
5624 // protocol qualifiers ever become additive, the iterators will need
5625 // to get kindof complicated.
5626 //
5627 // In the canonical object type, these are sorted alphabetically
5628 // and uniqued.
5629
5630 /// Either a BuiltinType or an InterfaceType or sugar for either.
5631 QualType BaseType;
5632
5633 /// Cached superclass type.
5634 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5635 CachedSuperClassType;
5636
5637 QualType *getTypeArgStorage();
5638 const QualType *getTypeArgStorage() const {
5639 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5640 }
5641
5642 ObjCProtocolDecl **getProtocolStorageImpl();
5643 /// Return the number of qualifying protocols in this interface type,
5644 /// or 0 if there are none.
5645 unsigned getNumProtocolsImpl() const {
5646 return ObjCObjectTypeBits.NumProtocols;
5647 }
5648 void setNumProtocolsImpl(unsigned N) {
5649 ObjCObjectTypeBits.NumProtocols = N;
5650 }
5651
5652protected:
5653 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5654
5655 ObjCObjectType(QualType Canonical, QualType Base,
5656 ArrayRef<QualType> typeArgs,
5657 ArrayRef<ObjCProtocolDecl *> protocols,
5658 bool isKindOf);
5659
5660 ObjCObjectType(enum Nonce_ObjCInterface)
5661 : Type(ObjCInterface, QualType(), false, false, false, false),
5662 BaseType(QualType(this_(), 0)) {
5663 ObjCObjectTypeBits.NumProtocols = 0;
5664 ObjCObjectTypeBits.NumTypeArgs = 0;
5665 ObjCObjectTypeBits.IsKindOf = 0;
5666 }
5667
5668 void computeSuperClassTypeSlow() const;
5669
5670public:
5671 /// Gets the base type of this object type. This is always (possibly
5672 /// sugar for) one of:
5673 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5674 /// user, which is a typedef for an ObjCObjectPointerType)
5675 /// - the 'Class' builtin type (same caveat)
5676 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5677 QualType getBaseType() const { return BaseType; }
5678
5679 bool isObjCId() const {
5680 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5681 }
5682
5683 bool isObjCClass() const {
5684 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5685 }
5686
5687 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5688 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5689 bool isObjCUnqualifiedIdOrClass() const {
5690 if (!qual_empty()) return false;
5691 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5692 return T->getKind() == BuiltinType::ObjCId ||
5693 T->getKind() == BuiltinType::ObjCClass;
5694 return false;
5695 }
5696 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5697 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5698
5699 /// Gets the interface declaration for this object type, if the base type
5700 /// really is an interface.
5701 ObjCInterfaceDecl *getInterface() const;
5702
5703 /// Determine whether this object type is "specialized", meaning
5704 /// that it has type arguments.
5705 bool isSpecialized() const;
5706
5707 /// Determine whether this object type was written with type arguments.
5708 bool isSpecializedAsWritten() const {
5709 return ObjCObjectTypeBits.NumTypeArgs > 0;
5710 }
5711
5712 /// Determine whether this object type is "unspecialized", meaning
5713 /// that it has no type arguments.
5714 bool isUnspecialized() const { return !isSpecialized(); }
5715
5716 /// Determine whether this object type is "unspecialized" as
5717 /// written, meaning that it has no type arguments.
5718 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5719
5720 /// Retrieve the type arguments of this object type (semantically).
5721 ArrayRef<QualType> getTypeArgs() const;
5722
5723 /// Retrieve the type arguments of this object type as they were
5724 /// written.
5725 ArrayRef<QualType> getTypeArgsAsWritten() const {
5726 return llvm::makeArrayRef(getTypeArgStorage(),
5727 ObjCObjectTypeBits.NumTypeArgs);
5728 }
5729
5730 /// Whether this is a "__kindof" type as written.
5731 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5732
5733 /// Whether this ia a "__kindof" type (semantically).
5734 bool isKindOfType() const;
5735
5736 /// Retrieve the type of the superclass of this object type.
5737 ///
5738 /// This operation substitutes any type arguments into the
5739 /// superclass of the current class type, potentially producing a
5740 /// specialization of the superclass type. Produces a null type if
5741 /// there is no superclass.
5742 QualType getSuperClassType() const {
5743 if (!CachedSuperClassType.getInt())
5744 computeSuperClassTypeSlow();
5745
5746 assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?"
) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5746, __PRETTY_FUNCTION__))
;
5747 return QualType(CachedSuperClassType.getPointer(), 0);
5748 }
5749
5750 /// Strip off the Objective-C "kindof" type and (with it) any
5751 /// protocol qualifiers.
5752 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5753
5754 bool isSugared() const { return false; }
5755 QualType desugar() const { return QualType(this, 0); }
5756
5757 static bool classof(const Type *T) {
5758 return T->getTypeClass() == ObjCObject ||
5759 T->getTypeClass() == ObjCInterface;
5760 }
5761};
5762
5763/// A class providing a concrete implementation
5764/// of ObjCObjectType, so as to not increase the footprint of
5765/// ObjCInterfaceType. Code outside of ASTContext and the core type
5766/// system should not reference this type.
5767class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5768 friend class ASTContext;
5769
5770 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5771 // will need to be modified.
5772
5773 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5774 ArrayRef<QualType> typeArgs,
5775 ArrayRef<ObjCProtocolDecl *> protocols,
5776 bool isKindOf)
5777 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5778
5779public:
5780 void Profile(llvm::FoldingSetNodeID &ID);
5781 static void Profile(llvm::FoldingSetNodeID &ID,
5782 QualType Base,
5783 ArrayRef<QualType> typeArgs,
5784 ArrayRef<ObjCProtocolDecl *> protocols,
5785 bool isKindOf);
5786};
5787
5788inline QualType *ObjCObjectType::getTypeArgStorage() {
5789 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5790}
5791
5792inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5793 return reinterpret_cast<ObjCProtocolDecl**>(
5794 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5795}
5796
5797inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5798 return reinterpret_cast<ObjCProtocolDecl**>(
5799 static_cast<ObjCTypeParamType*>(this)+1);
5800}
5801
5802/// Interfaces are the core concept in Objective-C for object oriented design.
5803/// They basically correspond to C++ classes. There are two kinds of interface
5804/// types: normal interfaces like `NSString`, and qualified interfaces, which
5805/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5806///
5807/// ObjCInterfaceType guarantees the following properties when considered
5808/// as a subtype of its superclass, ObjCObjectType:
5809/// - There are no protocol qualifiers. To reinforce this, code which
5810/// tries to invoke the protocol methods via an ObjCInterfaceType will
5811/// fail to compile.
5812/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5813/// T->getBaseType() == QualType(T, 0).
5814class ObjCInterfaceType : public ObjCObjectType {
5815 friend class ASTContext; // ASTContext creates these.
5816 friend class ASTReader;
5817 friend class ObjCInterfaceDecl;
5818
5819 mutable ObjCInterfaceDecl *Decl;
5820
5821 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5822 : ObjCObjectType(Nonce_ObjCInterface),
5823 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5824
5825public:
5826 /// Get the declaration of this interface.
5827 ObjCInterfaceDecl *getDecl() const { return Decl; }
5828
5829 bool isSugared() const { return false; }
5830 QualType desugar() const { return QualType(this, 0); }
5831
5832 static bool classof(const Type *T) {
5833 return T->getTypeClass() == ObjCInterface;
5834 }
5835
5836 // Nonsense to "hide" certain members of ObjCObjectType within this
5837 // class. People asking for protocols on an ObjCInterfaceType are
5838 // not going to get what they want: ObjCInterfaceTypes are
5839 // guaranteed to have no protocols.
5840 enum {
5841 qual_iterator,
5842 qual_begin,
5843 qual_end,
5844 getNumProtocols,
5845 getProtocol
5846 };
5847};
5848
5849inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5850 QualType baseType = getBaseType();
5851 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
5852 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
5853 return T->getDecl();
5854
5855 baseType = ObjT->getBaseType();
5856 }
5857
5858 return nullptr;
5859}
5860
5861/// Represents a pointer to an Objective C object.
5862///
5863/// These are constructed from pointer declarators when the pointee type is
5864/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5865/// types are typedefs for these, and the protocol-qualified types 'id<P>'
5866/// and 'Class<P>' are translated into these.
5867///
5868/// Pointers to pointers to Objective C objects are still PointerTypes;
5869/// only the first level of pointer gets it own type implementation.
5870class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5871 friend class ASTContext; // ASTContext creates these.
5872
5873 QualType PointeeType;
5874
5875 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5876 : Type(ObjCObjectPointer, Canonical,
5877 Pointee->isDependentType(),
5878 Pointee->isInstantiationDependentType(),
5879 Pointee->isVariablyModifiedType(),
5880 Pointee->containsUnexpandedParameterPack()),
5881 PointeeType(Pointee) {}
5882
5883public:
5884 /// Gets the type pointed to by this ObjC pointer.
5885 /// The result will always be an ObjCObjectType or sugar thereof.
5886 QualType getPointeeType() const { return PointeeType; }
5887
5888 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5889 ///
5890 /// This method is equivalent to getPointeeType() except that
5891 /// it discards any typedefs (or other sugar) between this
5892 /// type and the "outermost" object type. So for:
5893 /// \code
5894 /// \@class A; \@protocol P; \@protocol Q;
5895 /// typedef A<P> AP;
5896 /// typedef A A1;
5897 /// typedef A1<P> A1P;
5898 /// typedef A1P<Q> A1PQ;
5899 /// \endcode
5900 /// For 'A*', getObjectType() will return 'A'.
5901 /// For 'A<P>*', getObjectType() will return 'A<P>'.
5902 /// For 'AP*', getObjectType() will return 'A<P>'.
5903 /// For 'A1*', getObjectType() will return 'A'.
5904 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5905 /// For 'A1P*', getObjectType() will return 'A1<P>'.
5906 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5907 /// adding protocols to a protocol-qualified base discards the
5908 /// old qualifiers (for now). But if it didn't, getObjectType()
5909 /// would return 'A1P<Q>' (and we'd have to make iterating over
5910 /// qualifiers more complicated).
5911 const ObjCObjectType *getObjectType() const {
5912 return PointeeType->castAs<ObjCObjectType>();
5913 }
5914
5915 /// If this pointer points to an Objective C
5916 /// \@interface type, gets the type for that interface. Any protocol
5917 /// qualifiers on the interface are ignored.
5918 ///
5919 /// \return null if the base type for this pointer is 'id' or 'Class'
5920 const ObjCInterfaceType *getInterfaceType() const;
5921
5922 /// If this pointer points to an Objective \@interface
5923 /// type, gets the declaration for that interface.
5924 ///
5925 /// \return null if the base type for this pointer is 'id' or 'Class'
5926 ObjCInterfaceDecl *getInterfaceDecl() const {
5927 return getObjectType()->getInterface();
5928 }
5929
5930 /// True if this is equivalent to the 'id' type, i.e. if
5931 /// its object type is the primitive 'id' type with no protocols.
5932 bool isObjCIdType() const {
5933 return getObjectType()->isObjCUnqualifiedId();
5934 }
5935
5936 /// True if this is equivalent to the 'Class' type,
5937 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5938 bool isObjCClassType() const {
5939 return getObjectType()->isObjCUnqualifiedClass();
5940 }
5941
5942 /// True if this is equivalent to the 'id' or 'Class' type,
5943 bool isObjCIdOrClassType() const {
5944 return getObjectType()->isObjCUnqualifiedIdOrClass();
5945 }
5946
5947 /// True if this is equivalent to 'id<P>' for some non-empty set of
5948 /// protocols.
5949 bool isObjCQualifiedIdType() const {
5950 return getObjectType()->isObjCQualifiedId();
5951 }
5952
5953 /// True if this is equivalent to 'Class<P>' for some non-empty set of
5954 /// protocols.
5955 bool isObjCQualifiedClassType() const {
5956 return getObjectType()->isObjCQualifiedClass();
5957 }
5958
5959 /// Whether this is a "__kindof" type.
5960 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5961
5962 /// Whether this type is specialized, meaning that it has type arguments.
5963 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5964
5965 /// Whether this type is specialized, meaning that it has type arguments.
5966 bool isSpecializedAsWritten() const {
5967 return getObjectType()->isSpecializedAsWritten();
5968 }
5969
5970 /// Whether this type is unspecialized, meaning that is has no type arguments.
5971 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5972
5973 /// Determine whether this object type is "unspecialized" as
5974 /// written, meaning that it has no type arguments.
5975 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5976
5977 /// Retrieve the type arguments for this type.
5978 ArrayRef<QualType> getTypeArgs() const {
5979 return getObjectType()->getTypeArgs();
5980 }
5981
5982 /// Retrieve the type arguments for this type.
5983 ArrayRef<QualType> getTypeArgsAsWritten() const {
5984 return getObjectType()->getTypeArgsAsWritten();
5985 }
5986
5987 /// An iterator over the qualifiers on the object type. Provided
5988 /// for convenience. This will always iterate over the full set of
5989 /// protocols on a type, not just those provided directly.
5990 using qual_iterator = ObjCObjectType::qual_iterator;
5991 using qual_range = llvm::iterator_range<qual_iterator>;
5992
5993 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5994
5995 qual_iterator qual_begin() const {
5996 return getObjectType()->qual_begin();
5997 }
5998
5999 qual_iterator qual_end() const {
6000 return getObjectType()->qual_end();
6001 }
6002
6003 bool qual_empty() const { return getObjectType()->qual_empty(); }
6004
6005 /// Return the number of qualifying protocols on the object type.
6006 unsigned getNumProtocols() const {
6007 return getObjectType()->getNumProtocols();
6008 }
6009
6010 /// Retrieve a qualifying protocol by index on the object type.
6011 ObjCProtocolDecl *getProtocol(unsigned I) const {
6012 return getObjectType()->getProtocol(I);
6013 }
6014
6015 bool isSugared() const { return false; }
6016 QualType desugar() const { return QualType(this, 0); }
6017
6018 /// Retrieve the type of the superclass of this object pointer type.
6019 ///
6020 /// This operation substitutes any type arguments into the
6021 /// superclass of the current class type, potentially producing a
6022 /// pointer to a specialization of the superclass type. Produces a
6023 /// null type if there is no superclass.
6024 QualType getSuperClassType() const;
6025
6026 /// Strip off the Objective-C "kindof" type and (with it) any
6027 /// protocol qualifiers.
6028 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6029 const ASTContext &ctx) const;
6030
6031 void Profile(llvm::FoldingSetNodeID &ID) {
6032 Profile(ID, getPointeeType());
6033 }
6034
6035 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6036 ID.AddPointer(T.getAsOpaquePtr());
6037 }
6038
6039 static bool classof(const Type *T) {
6040 return T->getTypeClass() == ObjCObjectPointer;
6041 }
6042};
6043
6044class AtomicType : public Type, public llvm::FoldingSetNode {
6045 friend class ASTContext; // ASTContext creates these.
6046
6047 QualType ValueType;
6048
6049 AtomicType(QualType ValTy, QualType Canonical)
6050 : Type(Atomic, Canonical, ValTy->isDependentType(),
6051 ValTy->isInstantiationDependentType(),
6052 ValTy->isVariablyModifiedType(),
6053 ValTy->containsUnexpandedParameterPack()),
6054 ValueType(ValTy) {}
6055
6056public:
6057 /// Gets the type contained by this atomic type, i.e.
6058 /// the type returned by performing an atomic load of this atomic type.
6059 QualType getValueType() const { return ValueType; }
6060
6061 bool isSugared() const { return false; }
6062 QualType desugar() const { return QualType(this, 0); }
6063
6064 void Profile(llvm::FoldingSetNodeID &ID) {
6065 Profile(ID, getValueType());
6066 }
6067
6068 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6069 ID.AddPointer(T.getAsOpaquePtr());
6070 }
6071
6072 static bool classof(const Type *T) {
6073 return T->getTypeClass() == Atomic;
6074 }
6075};
6076
6077/// PipeType - OpenCL20.
6078class PipeType : public Type, public llvm::FoldingSetNode {
6079 friend class ASTContext; // ASTContext creates these.
6080
6081 QualType ElementType;
6082 bool isRead;
6083
6084 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6085 : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
6086 elemType->isInstantiationDependentType(),
6087 elemType->isVariablyModifiedType(),
6088 elemType->containsUnexpandedParameterPack()),
6089 ElementType(elemType), isRead(isRead) {}
6090
6091public:
6092 QualType getElementType() const { return ElementType; }
6093
6094 bool isSugared() const { return false; }
6095
6096 QualType desugar() const { return QualType(this, 0); }
6097
6098 void Profile(llvm::FoldingSetNodeID &ID) {
6099 Profile(ID, getElementType(), isReadOnly());
6100 }
6101
6102 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6103 ID.AddPointer(T.getAsOpaquePtr());
6104 ID.AddBoolean(isRead);
6105 }
6106
6107 static bool classof(const Type *T) {
6108 return T->getTypeClass() == Pipe;
6109 }
6110
6111 bool isReadOnly() const { return isRead; }
6112};
6113
6114/// A qualifier set is used to build a set of qualifiers.
6115class QualifierCollector : public Qualifiers {
6116public:
6117 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6118
6119 /// Collect any qualifiers on the given type and return an
6120 /// unqualified type. The qualifiers are assumed to be consistent
6121 /// with those already in the type.
6122 const Type *strip(QualType type) {
6123 addFastQualifiers(type.getLocalFastQualifiers());
6124 if (!type.hasLocalNonFastQualifiers())
6125 return type.getTypePtrUnsafe();
6126
6127 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6128 addConsistentQualifiers(extQuals->getQualifiers());
6129 return extQuals->getBaseType();
6130 }
6131
6132 /// Apply the collected qualifiers to the given type.
6133 QualType apply(const ASTContext &Context, QualType QT) const;
6134
6135 /// Apply the collected qualifiers to the given type.
6136 QualType apply(const ASTContext &Context, const Type* T) const;
6137};
6138
6139// Inline function definitions.
6140
6141inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6142 SplitQualType desugar =
6143 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6144 desugar.Quals.addConsistentQualifiers(Quals);
6145 return desugar;
6146}
6147
6148inline const Type *QualType::getTypePtr() const {
6149 return getCommonPtr()->BaseType;
6150}
6151
6152inline const Type *QualType::getTypePtrOrNull() const {
6153 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6154}
6155
6156inline SplitQualType QualType::split() const {
6157 if (!hasLocalNonFastQualifiers())
6158 return SplitQualType(getTypePtrUnsafe(),
6159 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6160
6161 const ExtQuals *eq = getExtQualsUnsafe();
6162 Qualifiers qs = eq->getQualifiers();
6163 qs.addFastQualifiers(getLocalFastQualifiers());
6164 return SplitQualType(eq->getBaseType(), qs);
6165}
6166
6167inline Qualifiers QualType::getLocalQualifiers() const {
6168 Qualifiers Quals;
6169 if (hasLocalNonFastQualifiers())
6170 Quals = getExtQualsUnsafe()->getQualifiers();
6171 Quals.addFastQualifiers(getLocalFastQualifiers());
6172 return Quals;
6173}
6174
6175inline Qualifiers QualType::getQualifiers() const {
6176 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6177 quals.addFastQualifiers(getLocalFastQualifiers());
6178 return quals;
6179}
6180
6181inline unsigned QualType::getCVRQualifiers() const {
6182 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6183 cvr |= getLocalCVRQualifiers();
6184 return cvr;
6185}
6186
6187inline QualType QualType::getCanonicalType() const {
6188 QualType canon = getCommonPtr()->CanonicalType;
6189 return canon.withFastQualifiers(getLocalFastQualifiers());
6190}
6191
6192inline bool QualType::isCanonical() const {
6193 return getTypePtr()->isCanonicalUnqualified();
6194}
6195
6196inline bool QualType::isCanonicalAsParam() const {
6197 if (!isCanonical()) return false;
6198 if (hasLocalQualifiers()) return false;
6199
6200 const Type *T = getTypePtr();
6201 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6202 return false;
6203
6204 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6205}
6206
6207inline bool QualType::isConstQualified() const {
6208 return isLocalConstQualified() ||
6209 getCommonPtr()->CanonicalType.isLocalConstQualified();
6210}
6211
6212inline bool QualType::isRestrictQualified() const {
6213 return isLocalRestrictQualified() ||
6214 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6215}
6216
6217
6218inline bool QualType::isVolatileQualified() const {
6219 return isLocalVolatileQualified() ||
6220 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6221}
6222
6223inline bool QualType::hasQualifiers() const {
6224 return hasLocalQualifiers() ||
6225 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6226}
6227
6228inline QualType QualType::getUnqualifiedType() const {
6229 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6230 return QualType(getTypePtr(), 0);
6231
6232 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6233}
6234
6235inline SplitQualType QualType::getSplitUnqualifiedType() const {
6236 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6237 return split();
6238
6239 return getSplitUnqualifiedTypeImpl(*this);
6240}
6241
6242inline void QualType::removeLocalConst() {
6243 removeLocalFastQualifiers(Qualifiers::Const);
6244}
6245
6246inline void QualType::removeLocalRestrict() {
6247 removeLocalFastQualifiers(Qualifiers::Restrict);
6248}
6249
6250inline void QualType::removeLocalVolatile() {
6251 removeLocalFastQualifiers(Qualifiers::Volatile);
6252}
6253
6254inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6255 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 6255, __PRETTY_FUNCTION__))
;
6256 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6257 "Fast bits differ from CVR bits!");
6258
6259 // Fast path: we don't need to touch the slow qualifiers.
6260 removeLocalFastQualifiers(Mask);
6261}
6262
6263/// Return the address space of this type.
6264inline LangAS QualType::getAddressSpace() const {
6265 return getQualifiers().getAddressSpace();
6266}
6267
6268/// Return the gc attribute of this type.
6269inline Qualifiers::GC QualType::getObjCGCAttr() const {
6270 return getQualifiers().getObjCGCAttr();
6271}
6272
6273inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6274 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6275 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6276 return false;
6277}
6278
6279inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6280 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6281 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6282 return false;
6283}
6284
6285inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6286 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6287 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6288 return false;
6289}
6290
6291inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6292 if (const auto *PT = t.getAs<PointerType>()) {
6293 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6294 return FT->getExtInfo();
6295 } else if (const auto *FT = t.getAs<FunctionType>())
6296 return FT->getExtInfo();
6297
6298 return FunctionType::ExtInfo();
6299}
6300
6301inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6302 return getFunctionExtInfo(*t);
6303}
6304
6305/// Determine whether this type is more
6306/// qualified than the Other type. For example, "const volatile int"
6307/// is more qualified than "const int", "volatile int", and
6308/// "int". However, it is not more qualified than "const volatile
6309/// int".
6310inline bool QualType::isMoreQualifiedThan(QualType other) const {
6311 Qualifiers MyQuals = getQualifiers();
6312 Qualifiers OtherQuals = other.getQualifiers();
6313 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6314}
6315
6316/// Determine whether this type is at last
6317/// as qualified as the Other type. For example, "const volatile
6318/// int" is at least as qualified as "const int", "volatile int",
6319/// "int", and "const volatile int".
6320inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6321 Qualifiers OtherQuals = other.getQualifiers();
6322
6323 // Ignore __unaligned qualifier if this type is a void.
6324 if (getUnqualifiedType()->isVoidType())
6325 OtherQuals.removeUnaligned();
6326
6327 return getQualifiers().compatiblyIncludes(OtherQuals);
6328}
6329
6330/// If Type is a reference type (e.g., const
6331/// int&), returns the type that the reference refers to ("const
6332/// int"). Otherwise, returns the type itself. This routine is used
6333/// throughout Sema to implement C++ 5p6:
6334///
6335/// If an expression initially has the type "reference to T" (8.3.2,
6336/// 8.5.3), the type is adjusted to "T" prior to any further
6337/// analysis, the expression designates the object or function
6338/// denoted by the reference, and the expression is an lvalue.
6339inline QualType QualType::getNonReferenceType() const {
6340 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6341 return RefType->getPointeeType();
6342 else
6343 return *this;
6344}
6345
6346inline bool QualType::isCForbiddenLValueType() const {
6347 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6348 getTypePtr()->isFunctionType());
6349}
6350
6351/// Tests whether the type is categorized as a fundamental type.
6352///
6353/// \returns True for types specified in C++0x [basic.fundamental].
6354inline bool Type::isFundamentalType() const {
6355 return isVoidType() ||
6356 isNullPtrType() ||
6357 // FIXME: It's really annoying that we don't have an
6358 // 'isArithmeticType()' which agrees with the standard definition.
6359 (isArithmeticType() && !isEnumeralType());
6360}
6361
6362/// Tests whether the type is categorized as a compound type.
6363///
6364/// \returns True for types specified in C++0x [basic.compound].
6365inline bool Type::isCompoundType() const {
6366 // C++0x [basic.compound]p1:
6367 // Compound types can be constructed in the following ways:
6368 // -- arrays of objects of a given type [...];
6369 return isArrayType() ||
6370 // -- functions, which have parameters of given types [...];
6371 isFunctionType() ||
6372 // -- pointers to void or objects or functions [...];
6373 isPointerType() ||
6374 // -- references to objects or functions of a given type. [...]
6375 isReferenceType() ||
6376 // -- classes containing a sequence of objects of various types, [...];
6377 isRecordType() ||
6378 // -- unions, which are classes capable of containing objects of different
6379 // types at different times;
6380 isUnionType() ||
6381 // -- enumerations, which comprise a set of named constant values. [...];
6382 isEnumeralType() ||
6383 // -- pointers to non-static class members, [...].
6384 isMemberPointerType();
6385}
6386
6387inline bool Type::isFunctionType() const {
6388 return isa<FunctionType>(CanonicalType);
6389}
6390
6391inline bool Type::isPointerType() const {
6392 return isa<PointerType>(CanonicalType);
6393}
6394
6395inline bool Type::isAnyPointerType() const {
6396 return isPointerType() || isObjCObjectPointerType();
6397}
6398
6399inline bool Type::isBlockPointerType() const {
6400 return isa<BlockPointerType>(CanonicalType);
6401}
6402
6403inline bool Type::isReferenceType() const {
6404 return isa<ReferenceType>(CanonicalType);
6405}
6406
6407inline bool Type::isLValueReferenceType() const {
6408 return isa<LValueReferenceType>(CanonicalType);
6409}
6410
6411inline bool Type::isRValueReferenceType() const {
6412 return isa<RValueReferenceType>(CanonicalType);
6413}
6414
6415inline bool Type::isFunctionPointerType() const {
6416 if (const auto *T = getAs<PointerType>())
6417 return T->getPointeeType()->isFunctionType();
6418 else
6419 return false;
6420}
6421
6422inline bool Type::isFunctionReferenceType() const {
6423 if (const auto *T = getAs<ReferenceType>())
6424 return T->getPointeeType()->isFunctionType();
6425 else
6426 return false;
6427}
6428
6429inline bool Type::isMemberPointerType() const {
6430 return isa<MemberPointerType>(CanonicalType);
6431}
6432
6433inline bool Type::isMemberFunctionPointerType() const {
6434 if (const auto *T = getAs<MemberPointerType>())
6435 return T->isMemberFunctionPointer();
6436 else
6437 return false;
6438}
6439
6440inline bool Type::isMemberDataPointerType() const {
6441 if (const auto *T = getAs<MemberPointerType>())
6442 return T->isMemberDataPointer();
6443 else
6444 return false;
6445}
6446
6447inline bool Type::isArrayType() const {
6448 return isa<ArrayType>(CanonicalType);
6449}
6450
6451inline bool Type::isConstantArrayType() const {
6452 return isa<ConstantArrayType>(CanonicalType);
6453}
6454
6455inline bool Type::isIncompleteArrayType() const {
6456 return isa<IncompleteArrayType>(CanonicalType);
6457}
6458
6459inline bool Type::isVariableArrayType() const {
6460 return isa<VariableArrayType>(CanonicalType);
6461}
6462
6463inline bool Type::isDependentSizedArrayType() const {
6464 return isa<DependentSizedArrayType>(CanonicalType);
6465}
6466
6467inline bool Type::isBuiltinType() const {
6468 return isa<BuiltinType>(CanonicalType);
6469}
6470
6471inline bool Type::isRecordType() const {
6472 return isa<RecordType>(CanonicalType);
6473}
6474
6475inline bool Type::isEnumeralType() const {
6476 return isa<EnumType>(CanonicalType);
6477}
6478
6479inline bool Type::isAnyComplexType() const {
6480 return isa<ComplexType>(CanonicalType);
6481}
6482
6483inline bool Type::isVectorType() const {
6484 return isa<VectorType>(CanonicalType);
6485}
6486
6487inline bool Type::isExtVectorType() const {
6488 return isa<ExtVectorType>(CanonicalType);
6489}
6490
6491inline bool Type::isDependentAddressSpaceType() const {
6492 return isa<DependentAddressSpaceType>(CanonicalType);
6493}
6494
6495inline bool Type::isObjCObjectPointerType() const {
6496 return isa<ObjCObjectPointerType>(CanonicalType);
35
Assuming field 'CanonicalType' is a 'ObjCObjectPointerType'
36
Returning the value 1, which participates in a condition later
6497}
6498
6499inline bool Type::isObjCObjectType() const {
6500 return isa<ObjCObjectType>(CanonicalType);
6501}
6502
6503inline bool Type::isObjCObjectOrInterfaceType() const {
6504 return isa<ObjCInterfaceType>(CanonicalType) ||
6505 isa<ObjCObjectType>(CanonicalType);
6506}
6507
6508inline bool Type::isAtomicType() const {
6509 return isa<AtomicType>(CanonicalType);
6510}
6511
6512inline bool Type::isObjCQualifiedIdType() const {
6513 if (const auto *OPT
23.1
'OPT' is null
23.1
'OPT' is null
23.1
'OPT' is null
= getAs<ObjCObjectPointerType>())
23
Assuming the object is not a 'ObjCObjectPointerType'
24
Taking false branch
6514 return OPT->isObjCQualifiedIdType();
6515 return false;
25
Returning zero, which participates in a condition later
6516}
6517
6518inline bool Type::isObjCQualifiedClassType() const {
6519 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6520 return OPT->isObjCQualifiedClassType();
6521 return false;
6522}
6523
6524inline bool Type::isObjCIdType() const {
6525 if (const auto *OPT
29.1
'OPT' is null
29.1
'OPT' is null
29.1
'OPT' is null
= getAs<ObjCObjectPointerType>())
29
Assuming the object is not a 'ObjCObjectPointerType'
30
Taking false branch
6526 return OPT->isObjCIdType();
6527 return false;
31
Returning zero, which participates in a condition later
6528}
6529
6530inline bool Type::isObjCClassType() const {
6531 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6532 return OPT->isObjCClassType();
6533 return false;
6534}
6535
6536inline bool Type::isObjCSelType() const {
6537 if (const auto *OPT = getAs<PointerType>())
6538 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6539 return false;
6540}
6541
6542inline bool Type::isObjCBuiltinType() const {
6543 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6544}
6545
6546inline bool Type::isDecltypeType() const {
6547 return isa<DecltypeType>(this);
6548}
6549
6550#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6551 inline bool Type::is##Id##Type() const { \
6552 return isSpecificBuiltinType(BuiltinType::Id); \
6553 }
6554#include "clang/Basic/OpenCLImageTypes.def"
6555
6556inline bool Type::isSamplerT() const {
6557 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6558}
6559
6560inline bool Type::isEventT() const {
6561 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6562}
6563
6564inline bool Type::isClkEventT() const {
6565 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6566}
6567
6568inline bool Type::isQueueT() const {
6569 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6570}
6571
6572inline bool Type::isReserveIDT() const {
6573 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6574}
6575
6576inline bool Type::isImageType() const {
6577#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6578 return
6579#include "clang/Basic/OpenCLImageTypes.def"
6580 false; // end boolean or operation
6581}
6582
6583inline bool Type::isPipeType() const {
6584 return isa<PipeType>(CanonicalType);
6585}
6586
6587#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6588 inline bool Type::is##Id##Type() const { \
6589 return isSpecificBuiltinType(BuiltinType::Id); \
6590 }
6591#include "clang/Basic/OpenCLExtensionTypes.def"
6592
6593inline bool Type::isOCLIntelSubgroupAVCType() const {
6594#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6595 isOCLIntelSubgroupAVC##Id##Type() ||
6596 return
6597#include "clang/Basic/OpenCLExtensionTypes.def"
6598 false; // end of boolean or operation
6599}
6600
6601inline bool Type::isOCLExtOpaqueType() const {
6602#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6603 return
6604#include "clang/Basic/OpenCLExtensionTypes.def"
6605 false; // end of boolean or operation
6606}
6607
6608inline bool Type::isOpenCLSpecificType() const {
6609 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6610 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6611}
6612
6613inline bool Type::isTemplateTypeParmType() const {
6614 return isa<TemplateTypeParmType>(CanonicalType);
6615}
6616
6617inline bool Type::isSpecificBuiltinType(unsigned K) const {
6618 if (const BuiltinType *BT = getAs<BuiltinType>())
6619 if (BT->getKind() == (BuiltinType::Kind) K)
6620 return true;
6621 return false;
6622}
6623
6624inline bool Type::isPlaceholderType() const {
6625 if (const auto *BT = dyn_cast<BuiltinType>(this))
6626 return BT->isPlaceholderType();
6627 return false;
6628}
6629
6630inline const BuiltinType *Type::getAsPlaceholderType() const {
6631 if (const auto *BT = dyn_cast<BuiltinType>(this))
6632 if (BT->isPlaceholderType())
6633 return BT;
6634 return nullptr;
6635}
6636
6637inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6638 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ?
static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 6638, __PRETTY_FUNCTION__))
;
6639 if (const auto *BT = dyn_cast<BuiltinType>(this))
6640 return (BT->getKind() == (BuiltinType::Kind) K);
6641 return false;
6642}
6643
6644inline bool Type::isNonOverloadPlaceholderType() const {
6645 if (const auto *BT = dyn_cast<BuiltinType>(this))
6646 return BT->isNonOverloadPlaceholderType();
6647 return false;
6648}
6649
6650inline bool Type::isVoidType() const {
6651 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6652 return BT->getKind() == BuiltinType::Void;
6653 return false;
6654}
6655
6656inline bool Type::isHalfType() const {
6657 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6658 return BT->getKind() == BuiltinType::Half;
6659 // FIXME: Should we allow complex __fp16? Probably not.
6660 return false;
6661}
6662
6663inline bool Type::isFloat16Type() const {
6664 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6665 return BT->getKind() == BuiltinType::Float16;
6666 return false;
6667}
6668
6669inline bool Type::isFloat128Type() const {
6670 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6671 return BT->getKind() == BuiltinType::Float128;
6672 return false;
6673}
6674
6675inline bool Type::isNullPtrType() const {
6676 if (const auto *BT = getAs<BuiltinType>())
6677 return BT->getKind() == BuiltinType::NullPtr;
6678 return false;
6679}
6680
6681bool IsEnumDeclComplete(EnumDecl *);
6682bool IsEnumDeclScoped(EnumDecl *);
6683
6684inline bool Type::isIntegerType() const {
6685 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6686 return BT->getKind() >= BuiltinType::Bool &&
6687 BT->getKind() <= BuiltinType::Int128;
6688 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6689 // Incomplete enum types are not treated as integer types.
6690 // FIXME: In C++, enum types are never integer types.
6691 return IsEnumDeclComplete(ET->getDecl()) &&
6692 !IsEnumDeclScoped(ET->getDecl());
6693 }
6694 return false;
6695}
6696
6697inline bool Type::isFixedPointType() const {
6698 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6699 return BT->getKind() >= BuiltinType::ShortAccum &&
6700 BT->getKind() <= BuiltinType::SatULongFract;
6701 }
6702 return false;
6703}
6704
6705inline bool Type::isFixedPointOrIntegerType() const {
6706 return isFixedPointType() || isIntegerType();
6707}
6708
6709inline bool Type::isSaturatedFixedPointType() const {
6710 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6711 return BT->getKind() >= BuiltinType::SatShortAccum &&
6712 BT->getKind() <= BuiltinType::SatULongFract;
6713 }
6714 return false;
6715}
6716
6717inline bool Type::isUnsaturatedFixedPointType() const {
6718 return isFixedPointType() && !isSaturatedFixedPointType();
6719}
6720
6721inline bool Type::isSignedFixedPointType() const {
6722 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6723 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6724 BT->getKind() <= BuiltinType::LongAccum) ||
6725 (BT->getKind() >= BuiltinType::ShortFract &&
6726 BT->getKind() <= BuiltinType::LongFract) ||
6727 (BT->getKind() >= BuiltinType::SatShortAccum &&
6728 BT->getKind() <= BuiltinType::SatLongAccum) ||
6729 (BT->getKind() >= BuiltinType::SatShortFract &&
6730 BT->getKind() <= BuiltinType::SatLongFract));
6731 }
6732 return false;
6733}
6734
6735inline bool Type::isUnsignedFixedPointType() const {
6736 return isFixedPointType() && !isSignedFixedPointType();
6737}
6738
6739inline bool Type::isScalarType() const {
6740 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6741 return BT->getKind() > BuiltinType::Void &&
6742 BT->getKind() <= BuiltinType::NullPtr;
6743 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6744 // Enums are scalar types, but only if they are defined. Incomplete enums
6745 // are not treated as scalar types.
6746 return IsEnumDeclComplete(ET->getDecl());
6747 return isa<PointerType>(CanonicalType) ||
6748 isa<BlockPointerType>(CanonicalType) ||
6749 isa<MemberPointerType>(CanonicalType) ||
6750 isa<ComplexType>(CanonicalType) ||
6751 isa<ObjCObjectPointerType>(CanonicalType);
6752}
6753
6754inline bool Type::isIntegralOrEnumerationType() const {
6755 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6756 return BT->getKind() >= BuiltinType::Bool &&
6757 BT->getKind() <= BuiltinType::Int128;
6758
6759 // Check for a complete enum type; incomplete enum types are not properly an
6760 // enumeration type in the sense required here.
6761 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
6762 return IsEnumDeclComplete(ET->getDecl());
6763
6764 return false;
6765}
6766
6767inline bool Type::isBooleanType() const {
6768 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6769 return BT->getKind() == BuiltinType::Bool;
6770 return false;
6771}
6772
6773inline bool Type::isUndeducedType() const {
6774 auto *DT = getContainedDeducedType();
6775 return DT && !DT->isDeduced();
6776}
6777
6778/// Determines whether this is a type for which one can define
6779/// an overloaded operator.
6780inline bool Type::isOverloadableType() const {
6781 return isDependentType() || isRecordType() || isEnumeralType();
6782}
6783
6784/// Determines whether this type can decay to a pointer type.
6785inline bool Type::canDecayToPointerType() const {
6786 return isFunctionType() || isArrayType();
6787}
6788
6789inline bool Type::hasPointerRepresentation() const {
6790 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6791 isObjCObjectPointerType() || isNullPtrType());
6792}
6793
6794inline bool Type::hasObjCPointerRepresentation() const {
6795 return isObjCObjectPointerType();
6796}
6797
6798inline const Type *Type::getBaseElementTypeUnsafe() const {
6799 const Type *type = this;
6800 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6801 type = arrayType->getElementType().getTypePtr();
6802 return type;
6803}
6804
6805inline const Type *Type::getPointeeOrArrayElementType() const {
6806 const Type *type = this;
6807 if (type->isAnyPointerType())
6808 return type->getPointeeType().getTypePtr();
6809 else if (type->isArrayType())
6810 return type->getBaseElementTypeUnsafe();
6811 return type;
6812}
6813
6814/// Insertion operator for diagnostics. This allows sending Qualifiers into a
6815/// diagnostic with <<.
6816inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6817 Qualifiers Q) {
6818 DB.AddTaggedVal(Q.getAsOpaqueValue(),
6819 DiagnosticsEngine::ArgumentKind::ak_qual);
6820 return DB;
6821}
6822
6823/// Insertion operator for partial diagnostics. This allows sending Qualifiers
6824/// into a diagnostic with <<.
6825inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6826 Qualifiers Q) {
6827 PD.AddTaggedVal(Q.getAsOpaqueValue(),
6828 DiagnosticsEngine::ArgumentKind::ak_qual);
6829 return PD;
6830}
6831
6832/// Insertion operator for diagnostics. This allows sending QualType's into a
6833/// diagnostic with <<.
6834inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6835 QualType T) {
6836 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6837 DiagnosticsEngine::ak_qualtype);
6838 return DB;
6839}
6840
6841/// Insertion operator for partial diagnostics. This allows sending QualType's
6842/// into a diagnostic with <<.
6843inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6844 QualType T) {
6845 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6846 DiagnosticsEngine::ak_qualtype);
6847 return PD;
6848}
6849
6850// Helper class template that is used by Type::getAs to ensure that one does
6851// not try to look through a qualified type to get to an array type.
6852template <typename T>
6853using TypeIsArrayType =
6854 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
6855 std::is_base_of<ArrayType, T>::value>;
6856
6857// Member-template getAs<specific type>'.
6858template <typename T> const T *Type::getAs() const {
6859 static_assert(!TypeIsArrayType<T>::value,
6860 "ArrayType cannot be used with getAs!");
6861
6862 // If this is directly a T type, return it.
6863 if (const auto *Ty = dyn_cast<T>(this))
6864 return Ty;
6865
6866 // If the canonical form of this type isn't the right kind, reject it.
6867 if (!isa<T>(CanonicalType))
6868 return nullptr;
6869
6870 // If this is a typedef for the type, strip the typedef off without
6871 // losing all typedef information.
6872 return cast<T>(getUnqualifiedDesugaredType());
6873}
6874
6875template <typename T> const T *Type::getAsAdjusted() const {
6876 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
6877
6878 // If this is directly a T type, return it.
6879 if (const auto *Ty = dyn_cast<T>(this))
6880 return Ty;
6881
6882 // If the canonical form of this type isn't the right kind, reject it.
6883 if (!isa<T>(CanonicalType))
6884 return nullptr;
6885
6886 // Strip off type adjustments that do not modify the underlying nature of the
6887 // type.
6888 const Type *Ty = this;
6889 while (Ty) {
6890 if (const auto *A = dyn_cast<AttributedType>(Ty))
6891 Ty = A->getModifiedType().getTypePtr();
6892 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
6893 Ty = E->desugar().getTypePtr();
6894 else if (const auto *P = dyn_cast<ParenType>(Ty))
6895 Ty = P->desugar().getTypePtr();
6896 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
6897 Ty = A->desugar().getTypePtr();
6898 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
6899 Ty = M->desugar().getTypePtr();
6900 else
6901 break;
6902 }
6903
6904 // Just because the canonical type is correct does not mean we can use cast<>,
6905 // since we may not have stripped off all the sugar down to the base type.
6906 return dyn_cast<T>(Ty);
6907}
6908
6909inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
6910 // If this is directly an array type, return it.
6911 if (const auto *arr = dyn_cast<ArrayType>(this))
6912 return arr;
6913
6914 // If the canonical form of this type isn't the right kind, reject it.
6915 if (!isa<ArrayType>(CanonicalType))
6916 return nullptr;
6917
6918 // If this is a typedef for the type, strip the typedef off without
6919 // losing all typedef information.
6920 return cast<ArrayType>(getUnqualifiedDesugaredType());
6921}
6922
6923template <typename T> const T *Type::castAs() const {
6924 static_assert(!TypeIsArrayType<T>::value,
6925 "ArrayType cannot be used with castAs!");
6926
6927 if (const auto *ty = dyn_cast<T>(this)) return ty;
6928 assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) :
__assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 6928, __PRETTY_FUNCTION__))
;
6929 return cast<T>(getUnqualifiedDesugaredType());
6930}
6931
6932inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
6933 assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void>
(0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 6933, __PRETTY_FUNCTION__))
;
6934 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
6935 return cast<ArrayType>(getUnqualifiedDesugaredType());
6936}
6937
6938DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
6939 QualType CanonicalPtr)
6940 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
6941#ifndef NDEBUG
6942 QualType Adjusted = getAdjustedType();
6943 (void)AttributedType::stripOuterNullability(Adjusted);
6944 assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void>
(0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 6944, __PRETTY_FUNCTION__))
;
6945#endif
6946}
6947
6948QualType DecayedType::getPointeeType() const {
6949 QualType Decayed = getDecayedType();
6950 (void)AttributedType::stripOuterNullability(Decayed);
6951 return cast<PointerType>(Decayed)->getPointeeType();
6952}
6953
6954// Get the decimal string representation of a fixed point type, represented
6955// as a scaled integer.
6956// TODO: At some point, we should change the arguments to instead just accept an
6957// APFixedPoint instead of APSInt and scale.
6958void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
6959 unsigned Scale);
6960
6961} // namespace clang
6962
6963#endif // LLVM_CLANG_AST_TYPE_H