Bug Summary

File:clang/lib/Sema/SemaDecl.cpp
Warning:line 8719, column 35
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDecl.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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/include -I /build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/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-12/lib/clang/12.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-12~++20201201111133+ea8c8a50976/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-12-02-093253-48256-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp

1//===--- SemaDecl.cpp - Semantic Analysis for 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 declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/CommentDiagnostic.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/NonTrivialTypeVisitor.h"
27#include "clang/AST/StmtCXX.h"
28#include "clang/Basic/Builtins.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36#include "clang/Sema/CXXFieldCollector.h"
37#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/DelayedDiagnostic.h"
39#include "clang/Sema/Initialization.h"
40#include "clang/Sema/Lookup.h"
41#include "clang/Sema/ParsedTemplate.h"
42#include "clang/Sema/Scope.h"
43#include "clang/Sema/ScopeInfo.h"
44#include "clang/Sema/SemaInternal.h"
45#include "clang/Sema/Template.h"
46#include "llvm/ADT/SmallString.h"
47#include "llvm/ADT/Triple.h"
48#include <algorithm>
49#include <cstring>
50#include <functional>
51#include <unordered_map>
52
53using namespace clang;
54using namespace sema;
55
56Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57 if (OwnedType) {
58 Decl *Group[2] = { OwnedType, Ptr };
59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60 }
61
62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63}
64
65namespace {
66
67class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68 public:
69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70 bool AllowTemplates = false,
71 bool AllowNonTemplates = true)
72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74 WantExpressionKeywords = false;
75 WantCXXNamedCasts = false;
76 WantRemainingKeywords = false;
77 }
78
79 bool ValidateCandidate(const TypoCorrection &candidate) override {
80 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81 if (!AllowInvalidDecl && ND->isInvalidDecl())
82 return false;
83
84 if (getAsTypeTemplateDecl(ND))
85 return AllowTemplates;
86
87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88 if (!IsType)
89 return false;
90
91 if (AllowNonTemplates)
92 return true;
93
94 // An injected-class-name of a class template (specialization) is valid
95 // as a template or as a non-template.
96 if (AllowTemplates) {
97 auto *RD = dyn_cast<CXXRecordDecl>(ND);
98 if (!RD || !RD->isInjectedClassName())
99 return false;
100 RD = cast<CXXRecordDecl>(RD->getDeclContext());
101 return RD->getDescribedClassTemplate() ||
102 isa<ClassTemplateSpecializationDecl>(RD);
103 }
104
105 return false;
106 }
107
108 return !WantClassName && candidate.isKeyword();
109 }
110
111 std::unique_ptr<CorrectionCandidateCallback> clone() override {
112 return std::make_unique<TypeNameValidatorCCC>(*this);
113 }
114
115 private:
116 bool AllowInvalidDecl;
117 bool WantClassName;
118 bool AllowTemplates;
119 bool AllowNonTemplates;
120};
121
122} // end anonymous namespace
123
124/// Determine whether the token kind starts a simple-type-specifier.
125bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126 switch (Kind) {
127 // FIXME: Take into account the current language when deciding whether a
128 // token kind is a valid type specifier
129 case tok::kw_short:
130 case tok::kw_long:
131 case tok::kw___int64:
132 case tok::kw___int128:
133 case tok::kw_signed:
134 case tok::kw_unsigned:
135 case tok::kw_void:
136 case tok::kw_char:
137 case tok::kw_int:
138 case tok::kw_half:
139 case tok::kw_float:
140 case tok::kw_double:
141 case tok::kw___bf16:
142 case tok::kw__Float16:
143 case tok::kw___float128:
144 case tok::kw_wchar_t:
145 case tok::kw_bool:
146 case tok::kw___underlying_type:
147 case tok::kw___auto_type:
148 return true;
149
150 case tok::annot_typename:
151 case tok::kw_char16_t:
152 case tok::kw_char32_t:
153 case tok::kw_typeof:
154 case tok::annot_decltype:
155 case tok::kw_decltype:
156 return getLangOpts().CPlusPlus;
157
158 case tok::kw_char8_t:
159 return getLangOpts().Char8;
160
161 default:
162 break;
163 }
164
165 return false;
166}
167
168namespace {
169enum class UnqualifiedTypeNameLookupResult {
170 NotFound,
171 FoundNonType,
172 FoundType
173};
174} // end anonymous namespace
175
176/// Tries to perform unqualified lookup of the type decls in bases for
177/// dependent class.
178/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179/// type decl, \a FoundType if only type decls are found.
180static UnqualifiedTypeNameLookupResult
181lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182 SourceLocation NameLoc,
183 const CXXRecordDecl *RD) {
184 if (!RD->hasDefinition())
185 return UnqualifiedTypeNameLookupResult::NotFound;
186 // Look for type decls in base classes.
187 UnqualifiedTypeNameLookupResult FoundTypeDecl =
188 UnqualifiedTypeNameLookupResult::NotFound;
189 for (const auto &Base : RD->bases()) {
190 const CXXRecordDecl *BaseRD = nullptr;
191 if (auto *BaseTT = Base.getType()->getAs<TagType>())
192 BaseRD = BaseTT->getAsCXXRecordDecl();
193 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
194 // Look for type decls in dependent base classes that have known primary
195 // templates.
196 if (!TST || !TST->isDependentType())
197 continue;
198 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (!TD)
200 continue;
201 if (auto *BasePrimaryTemplate =
202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = BasePrimaryTemplate;
205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206 if (const ClassTemplatePartialSpecializationDecl *PS =
207 CTD->findPartialSpecialization(Base.getType()))
208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = PS;
210 }
211 }
212 }
213 if (BaseRD) {
214 for (NamedDecl *ND : BaseRD->lookup(&II)) {
215 if (!isa<TypeDecl>(ND))
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218 }
219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221 case UnqualifiedTypeNameLookupResult::FoundNonType:
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 case UnqualifiedTypeNameLookupResult::FoundType:
224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 break;
226 case UnqualifiedTypeNameLookupResult::NotFound:
227 break;
228 }
229 }
230 }
231 }
232
233 return FoundTypeDecl;
234}
235
236static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237 const IdentifierInfo &II,
238 SourceLocation NameLoc) {
239 // Lookup in the parent class template context, if any.
240 const CXXRecordDecl *RD = nullptr;
241 UnqualifiedTypeNameLookupResult FoundTypeDecl =
242 UnqualifiedTypeNameLookupResult::NotFound;
243 for (DeclContext *DC = S.CurContext;
244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245 DC = DC->getParent()) {
246 // Look for type decls in dependent base classes that have known primary
247 // templates.
248 RD = dyn_cast<CXXRecordDecl>(DC);
249 if (RD && RD->getDescribedClassTemplate())
250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251 }
252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 return nullptr;
254
255 // We found some types in dependent base classes. Recover as if the user
256 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
257 // lookup during template instantiation.
258 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
259
260 ASTContext &Context = S.Context;
261 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
262 cast<Type>(Context.getRecordType(RD)));
263 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264
265 CXXScopeSpec SS;
266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267
268 TypeLocBuilder Builder;
269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270 DepTL.setNameLoc(NameLoc);
271 DepTL.setElaboratedKeywordLoc(SourceLocation());
272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274}
275
276/// If the identifier refers to a type name within this scope,
277/// return the declaration of that type.
278///
279/// This routine performs ordinary name lookup of the identifier II
280/// within the given scope, with optional C++ scope specifier SS, to
281/// determine whether the name refers to a type. If so, returns an
282/// opaque pointer (actually a QualType) corresponding to that
283/// type. Otherwise, returns NULL.
284ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
285 Scope *S, CXXScopeSpec *SS,
286 bool isClassName, bool HasTrailingDot,
287 ParsedType ObjectTypePtr,
288 bool IsCtorOrDtorName,
289 bool WantNontrivialTypeSourceInfo,
290 bool IsClassTemplateDeductionContext,
291 IdentifierInfo **CorrectedII) {
292 // FIXME: Consider allowing this outside C++1z mode as an extension.
293 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
294 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
295 !isClassName && !HasTrailingDot;
296
297 // Determine where we will perform name lookup.
298 DeclContext *LookupCtx = nullptr;
299 if (ObjectTypePtr) {
300 QualType ObjectType = ObjectTypePtr.get();
301 if (ObjectType->isRecordType())
302 LookupCtx = computeDeclContext(ObjectType);
303 } else if (SS && SS->isNotEmpty()) {
304 LookupCtx = computeDeclContext(*SS, false);
305
306 if (!LookupCtx) {
307 if (isDependentScopeSpecifier(*SS)) {
308 // C++ [temp.res]p3:
309 // A qualified-id that refers to a type and in which the
310 // nested-name-specifier depends on a template-parameter (14.6.2)
311 // shall be prefixed by the keyword typename to indicate that the
312 // qualified-id denotes a type, forming an
313 // elaborated-type-specifier (7.1.5.3).
314 //
315 // We therefore do not perform any name lookup if the result would
316 // refer to a member of an unknown specialization.
317 if (!isClassName && !IsCtorOrDtorName)
318 return nullptr;
319
320 // We know from the grammar that this name refers to a type,
321 // so build a dependent node to describe the type.
322 if (WantNontrivialTypeSourceInfo)
323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
324
325 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
326 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
327 II, NameLoc);
328 return ParsedType::make(T);
329 }
330
331 return nullptr;
332 }
333
334 if (!LookupCtx->isDependentContext() &&
335 RequireCompleteDeclContext(*SS, LookupCtx))
336 return nullptr;
337 }
338
339 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
340 // lookup for class-names.
341 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
342 LookupOrdinaryName;
343 LookupResult Result(*this, &II, NameLoc, Kind);
344 if (LookupCtx) {
345 // Perform "qualified" name lookup into the declaration context we
346 // computed, which is either the type of the base of a member access
347 // expression or the declaration context associated with a prior
348 // nested-name-specifier.
349 LookupQualifiedName(Result, LookupCtx);
350
351 if (ObjectTypePtr && Result.empty()) {
352 // C++ [basic.lookup.classref]p3:
353 // If the unqualified-id is ~type-name, the type-name is looked up
354 // in the context of the entire postfix-expression. If the type T of
355 // the object expression is of a class type C, the type-name is also
356 // looked up in the scope of class C. At least one of the lookups shall
357 // find a name that refers to (possibly cv-qualified) T.
358 LookupName(Result, S);
359 }
360 } else {
361 // Perform unqualified name lookup.
362 LookupName(Result, S);
363
364 // For unqualified lookup in a class template in MSVC mode, look into
365 // dependent base classes where the primary class template is known.
366 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
367 if (ParsedType TypeInBase =
368 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
369 return TypeInBase;
370 }
371 }
372
373 NamedDecl *IIDecl = nullptr;
374 switch (Result.getResultKind()) {
375 case LookupResult::NotFound:
376 case LookupResult::NotFoundInCurrentInstantiation:
377 if (CorrectedII) {
378 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
379 AllowDeducedTemplate);
380 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
381 S, SS, CCC, CTK_ErrorRecovery);
382 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
383 TemplateTy Template;
384 bool MemberOfUnknownSpecialization;
385 UnqualifiedId TemplateName;
386 TemplateName.setIdentifier(NewII, NameLoc);
387 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
388 CXXScopeSpec NewSS, *NewSSPtr = SS;
389 if (SS && NNS) {
390 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391 NewSSPtr = &NewSS;
392 }
393 if (Correction && (NNS || NewII != &II) &&
394 // Ignore a correction to a template type as the to-be-corrected
395 // identifier is not a template (typo correction for template names
396 // is handled elsewhere).
397 !(getLangOpts().CPlusPlus && NewSSPtr &&
398 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
399 Template, MemberOfUnknownSpecialization))) {
400 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
401 isClassName, HasTrailingDot, ObjectTypePtr,
402 IsCtorOrDtorName,
403 WantNontrivialTypeSourceInfo,
404 IsClassTemplateDeductionContext);
405 if (Ty) {
406 diagnoseTypo(Correction,
407 PDiag(diag::err_unknown_type_or_class_name_suggest)
408 << Result.getLookupName() << isClassName);
409 if (SS && NNS)
410 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
411 *CorrectedII = NewII;
412 return Ty;
413 }
414 }
415 }
416 // If typo correction failed or was not performed, fall through
417 LLVM_FALLTHROUGH[[gnu::fallthrough]];
418 case LookupResult::FoundOverloaded:
419 case LookupResult::FoundUnresolvedValue:
420 Result.suppressDiagnostics();
421 return nullptr;
422
423 case LookupResult::Ambiguous:
424 // Recover from type-hiding ambiguities by hiding the type. We'll
425 // do the lookup again when looking for an object, and we can
426 // diagnose the error then. If we don't do this, then the error
427 // about hiding the type will be immediately followed by an error
428 // that only makes sense if the identifier was treated like a type.
429 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
430 Result.suppressDiagnostics();
431 return nullptr;
432 }
433
434 // Look to see if we have a type anywhere in the list of results.
435 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
436 Res != ResEnd; ++Res) {
437 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
438 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
439 if (!IIDecl ||
440 (*Res)->getLocation().getRawEncoding() <
441 IIDecl->getLocation().getRawEncoding())
442 IIDecl = *Res;
443 }
444 }
445
446 if (!IIDecl) {
447 // None of the entities we found is a type, so there is no way
448 // to even assume that the result is a type. In this case, don't
449 // complain about the ambiguity. The parser will either try to
450 // perform this lookup again (e.g., as an object name), which
451 // will produce the ambiguity, or will complain that it expected
452 // a type name.
453 Result.suppressDiagnostics();
454 return nullptr;
455 }
456
457 // We found a type within the ambiguous lookup; diagnose the
458 // ambiguity and then return that type. This might be the right
459 // answer, or it might not be, but it suppresses any attempt to
460 // perform the name lookup again.
461 break;
462
463 case LookupResult::Found:
464 IIDecl = Result.getFoundDecl();
465 break;
466 }
467
468 assert(IIDecl && "Didn't find decl")((IIDecl && "Didn't find decl") ? static_cast<void
> (0) : __assert_fail ("IIDecl && \"Didn't find decl\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 468, __PRETTY_FUNCTION__))
;
469
470 QualType T;
471 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
472 // C++ [class.qual]p2: A lookup that would find the injected-class-name
473 // instead names the constructors of the class, except when naming a class.
474 // This is ill-formed when we're not actually forming a ctor or dtor name.
475 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
476 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
477 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
478 FoundRD->isInjectedClassName() &&
479 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
480 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
481 << &II << /*Type*/1;
482
483 DiagnoseUseOfDecl(IIDecl, NameLoc);
484
485 T = Context.getTypeDeclType(TD);
486 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
487 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
488 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
489 if (!HasTrailingDot)
490 T = Context.getObjCInterfaceType(IDecl);
491 } else if (AllowDeducedTemplate) {
492 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
493 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
494 QualType(), false);
495 }
496
497 if (T.isNull()) {
498 // If it's not plausibly a type, suppress diagnostics.
499 Result.suppressDiagnostics();
500 return nullptr;
501 }
502
503 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
504 // constructor or destructor name (in such a case, the scope specifier
505 // will be attached to the enclosing Expr or Decl node).
506 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
507 !isa<ObjCInterfaceDecl>(IIDecl)) {
508 if (WantNontrivialTypeSourceInfo) {
509 // Construct a type with type-source information.
510 TypeLocBuilder Builder;
511 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
512
513 T = getElaboratedType(ETK_None, *SS, T);
514 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
515 ElabTL.setElaboratedKeywordLoc(SourceLocation());
516 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
517 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
518 } else {
519 T = getElaboratedType(ETK_None, *SS, T);
520 }
521 }
522
523 return ParsedType::make(T);
524}
525
526// Builds a fake NNS for the given decl context.
527static NestedNameSpecifier *
528synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
529 for (;; DC = DC->getLookupParent()) {
530 DC = DC->getPrimaryContext();
531 auto *ND = dyn_cast<NamespaceDecl>(DC);
532 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
533 return NestedNameSpecifier::Create(Context, nullptr, ND);
534 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
535 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
536 RD->getTypeForDecl());
537 else if (isa<TranslationUnitDecl>(DC))
538 return NestedNameSpecifier::GlobalSpecifier(Context);
539 }
540 llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 540)
;
541}
542
543/// Find the parent class with dependent bases of the innermost enclosing method
544/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
545/// up allowing unqualified dependent type names at class-level, which MSVC
546/// correctly rejects.
547static const CXXRecordDecl *
548findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
549 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
550 DC = DC->getPrimaryContext();
551 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
552 if (MD->getParent()->hasAnyDependentBases())
553 return MD->getParent();
554 }
555 return nullptr;
556}
557
558ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
559 SourceLocation NameLoc,
560 bool IsTemplateTypeArg) {
561 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")((getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 561, __PRETTY_FUNCTION__))
;
562
563 NestedNameSpecifier *NNS = nullptr;
564 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
565 // If we weren't able to parse a default template argument, delay lookup
566 // until instantiation time by making a non-dependent DependentTypeName. We
567 // pretend we saw a NestedNameSpecifier referring to the current scope, and
568 // lookup is retried.
569 // FIXME: This hurts our diagnostic quality, since we get errors like "no
570 // type named 'Foo' in 'current_namespace'" when the user didn't write any
571 // name specifiers.
572 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
573 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
574 } else if (const CXXRecordDecl *RD =
575 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
576 // Build a DependentNameType that will perform lookup into RD at
577 // instantiation time.
578 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
579 RD->getTypeForDecl());
580
581 // Diagnose that this identifier was undeclared, and retry the lookup during
582 // template instantiation.
583 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
584 << RD;
585 } else {
586 // This is not a situation that we should recover from.
587 return ParsedType();
588 }
589
590 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
591
592 // Build type location information. We synthesized the qualifier, so we have
593 // to build a fake NestedNameSpecifierLoc.
594 NestedNameSpecifierLocBuilder NNSLocBuilder;
595 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
596 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
597
598 TypeLocBuilder Builder;
599 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
600 DepTL.setNameLoc(NameLoc);
601 DepTL.setElaboratedKeywordLoc(SourceLocation());
602 DepTL.setQualifierLoc(QualifierLoc);
603 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
604}
605
606/// isTagName() - This method is called *for error recovery purposes only*
607/// to determine if the specified name is a valid tag name ("struct foo"). If
608/// so, this returns the TST for the tag corresponding to it (TST_enum,
609/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
610/// cases in C where the user forgot to specify the tag.
611DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
612 // Do a tag name lookup in this scope.
613 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
614 LookupName(R, S, false);
615 R.suppressDiagnostics();
616 if (R.getResultKind() == LookupResult::Found)
617 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
618 switch (TD->getTagKind()) {
619 case TTK_Struct: return DeclSpec::TST_struct;
620 case TTK_Interface: return DeclSpec::TST_interface;
621 case TTK_Union: return DeclSpec::TST_union;
622 case TTK_Class: return DeclSpec::TST_class;
623 case TTK_Enum: return DeclSpec::TST_enum;
624 }
625 }
626
627 return DeclSpec::TST_unspecified;
628}
629
630/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
631/// if a CXXScopeSpec's type is equal to the type of one of the base classes
632/// then downgrade the missing typename error to a warning.
633/// This is needed for MSVC compatibility; Example:
634/// @code
635/// template<class T> class A {
636/// public:
637/// typedef int TYPE;
638/// };
639/// template<class T> class B : public A<T> {
640/// public:
641/// A<T>::TYPE a; // no typename required because A<T> is a base class.
642/// };
643/// @endcode
644bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
645 if (CurContext->isRecord()) {
646 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
647 return true;
648
649 const Type *Ty = SS->getScopeRep()->getAsType();
650
651 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
652 for (const auto &Base : RD->bases())
653 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
654 return true;
655 return S->isFunctionPrototypeScope();
656 }
657 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
658}
659
660void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
661 SourceLocation IILoc,
662 Scope *S,
663 CXXScopeSpec *SS,
664 ParsedType &SuggestedType,
665 bool IsTemplateName) {
666 // Don't report typename errors for editor placeholders.
667 if (II->isEditorPlaceholder())
668 return;
669 // We don't have anything to suggest (yet).
670 SuggestedType = nullptr;
671
672 // There may have been a typo in the name of the type. Look up typo
673 // results, in case we have something that we can suggest.
674 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
675 /*AllowTemplates=*/IsTemplateName,
676 /*AllowNonTemplates=*/!IsTemplateName);
677 if (TypoCorrection Corrected =
678 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
679 CCC, CTK_ErrorRecovery)) {
680 // FIXME: Support error recovery for the template-name case.
681 bool CanRecover = !IsTemplateName;
682 if (Corrected.isKeyword()) {
683 // We corrected to a keyword.
684 diagnoseTypo(Corrected,
685 PDiag(IsTemplateName ? diag::err_no_template_suggest
686 : diag::err_unknown_typename_suggest)
687 << II);
688 II = Corrected.getCorrectionAsIdentifierInfo();
689 } else {
690 // We found a similarly-named type or interface; suggest that.
691 if (!SS || !SS->isSet()) {
692 diagnoseTypo(Corrected,
693 PDiag(IsTemplateName ? diag::err_no_template_suggest
694 : diag::err_unknown_typename_suggest)
695 << II, CanRecover);
696 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
697 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
698 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
699 II->getName().equals(CorrectedStr);
700 diagnoseTypo(Corrected,
701 PDiag(IsTemplateName
702 ? diag::err_no_member_template_suggest
703 : diag::err_unknown_nested_typename_suggest)
704 << II << DC << DroppedSpecifier << SS->getRange(),
705 CanRecover);
706 } else {
707 llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 707)
;
708 }
709
710 if (!CanRecover)
711 return;
712
713 CXXScopeSpec tmpSS;
714 if (Corrected.getCorrectionSpecifier())
715 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
716 SourceRange(IILoc));
717 // FIXME: Support class template argument deduction here.
718 SuggestedType =
719 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
720 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
721 /*IsCtorOrDtorName=*/false,
722 /*WantNontrivialTypeSourceInfo=*/true);
723 }
724 return;
725 }
726
727 if (getLangOpts().CPlusPlus && !IsTemplateName) {
728 // See if II is a class template that the user forgot to pass arguments to.
729 UnqualifiedId Name;
730 Name.setIdentifier(II, IILoc);
731 CXXScopeSpec EmptySS;
732 TemplateTy TemplateResult;
733 bool MemberOfUnknownSpecialization;
734 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
735 Name, nullptr, true, TemplateResult,
736 MemberOfUnknownSpecialization) == TNK_Type_template) {
737 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
738 return;
739 }
740 }
741
742 // FIXME: Should we move the logic that tries to recover from a missing tag
743 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
744
745 if (!SS || (!SS->isSet() && !SS->isInvalid()))
746 Diag(IILoc, IsTemplateName ? diag::err_no_template
747 : diag::err_unknown_typename)
748 << II;
749 else if (DeclContext *DC = computeDeclContext(*SS, false))
750 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
751 : diag::err_typename_nested_not_found)
752 << II << DC << SS->getRange();
753 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
754 SuggestedType =
755 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
756 } else if (isDependentScopeSpecifier(*SS)) {
757 unsigned DiagID = diag::err_typename_missing;
758 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
759 DiagID = diag::ext_typename_missing;
760
761 Diag(SS->getRange().getBegin(), DiagID)
762 << SS->getScopeRep() << II->getName()
763 << SourceRange(SS->getRange().getBegin(), IILoc)
764 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
765 SuggestedType = ActOnTypenameType(S, SourceLocation(),
766 *SS, *II, IILoc).get();
767 } else {
768 assert(SS && SS->isInvalid() &&((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed"
) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 769, __PRETTY_FUNCTION__))
769 "Invalid scope specifier has already been diagnosed")((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed"
) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 769, __PRETTY_FUNCTION__))
;
770 }
771}
772
773/// Determine whether the given result set contains either a type name
774/// or
775static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
776 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
777 NextToken.is(tok::less);
778
779 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
780 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
781 return true;
782
783 if (CheckTemplate && isa<TemplateDecl>(*I))
784 return true;
785 }
786
787 return false;
788}
789
790static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
791 Scope *S, CXXScopeSpec &SS,
792 IdentifierInfo *&Name,
793 SourceLocation NameLoc) {
794 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
795 SemaRef.LookupParsedName(R, S, &SS);
796 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
797 StringRef FixItTagName;
798 switch (Tag->getTagKind()) {
799 case TTK_Class:
800 FixItTagName = "class ";
801 break;
802
803 case TTK_Enum:
804 FixItTagName = "enum ";
805 break;
806
807 case TTK_Struct:
808 FixItTagName = "struct ";
809 break;
810
811 case TTK_Interface:
812 FixItTagName = "__interface ";
813 break;
814
815 case TTK_Union:
816 FixItTagName = "union ";
817 break;
818 }
819
820 StringRef TagName = FixItTagName.drop_back();
821 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
822 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
823 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
824
825 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
826 I != IEnd; ++I)
827 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
828 << Name << TagName;
829
830 // Replace lookup results with just the tag decl.
831 Result.clear(Sema::LookupTagName);
832 SemaRef.LookupParsedName(Result, S, &SS);
833 return true;
834 }
835
836 return false;
837}
838
839/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
840static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
841 QualType T, SourceLocation NameLoc) {
842 ASTContext &Context = S.Context;
843
844 TypeLocBuilder Builder;
845 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
846
847 T = S.getElaboratedType(ETK_None, SS, T);
848 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
849 ElabTL.setElaboratedKeywordLoc(SourceLocation());
850 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
851 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
852}
853
854Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
855 IdentifierInfo *&Name,
856 SourceLocation NameLoc,
857 const Token &NextToken,
858 CorrectionCandidateCallback *CCC) {
859 DeclarationNameInfo NameInfo(Name, NameLoc);
860 ObjCMethodDecl *CurMethod = getCurMethodDecl();
861
862 assert(NextToken.isNot(tok::coloncolon) &&((NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName"
) ? static_cast<void> (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 863, __PRETTY_FUNCTION__))
863 "parse nested name specifiers before calling ClassifyName")((NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName"
) ? static_cast<void> (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 863, __PRETTY_FUNCTION__))
;
864 if (getLangOpts().CPlusPlus && SS.isSet() &&
865 isCurrentClassName(*Name, S, &SS)) {
866 // Per [class.qual]p2, this names the constructors of SS, not the
867 // injected-class-name. We don't have a classification for that.
868 // There's not much point caching this result, since the parser
869 // will reject it later.
870 return NameClassification::Unknown();
871 }
872
873 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
874 LookupParsedName(Result, S, &SS, !CurMethod);
875
876 if (SS.isInvalid())
877 return NameClassification::Error();
878
879 // For unqualified lookup in a class template in MSVC mode, look into
880 // dependent base classes where the primary class template is known.
881 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
882 if (ParsedType TypeInBase =
883 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
884 return TypeInBase;
885 }
886
887 // Perform lookup for Objective-C instance variables (including automatically
888 // synthesized instance variables), if we're in an Objective-C method.
889 // FIXME: This lookup really, really needs to be folded in to the normal
890 // unqualified lookup mechanism.
891 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
892 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
893 if (Ivar.isInvalid())
894 return NameClassification::Error();
895 if (Ivar.isUsable())
896 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
897
898 // We defer builtin creation until after ivar lookup inside ObjC methods.
899 if (Result.empty())
900 LookupBuiltin(Result);
901 }
902
903 bool SecondTry = false;
904 bool IsFilteredTemplateName = false;
905
906Corrected:
907 switch (Result.getResultKind()) {
908 case LookupResult::NotFound:
909 // If an unqualified-id is followed by a '(', then we have a function
910 // call.
911 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
912 // In C++, this is an ADL-only call.
913 // FIXME: Reference?
914 if (getLangOpts().CPlusPlus)
915 return NameClassification::UndeclaredNonType();
916
917 // C90 6.3.2.2:
918 // If the expression that precedes the parenthesized argument list in a
919 // function call consists solely of an identifier, and if no
920 // declaration is visible for this identifier, the identifier is
921 // implicitly declared exactly as if, in the innermost block containing
922 // the function call, the declaration
923 //
924 // extern int identifier ();
925 //
926 // appeared.
927 //
928 // We also allow this in C99 as an extension.
929 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
930 return NameClassification::NonType(D);
931 }
932
933 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
934 // In C++20 onwards, this could be an ADL-only call to a function
935 // template, and we're required to assume that this is a template name.
936 //
937 // FIXME: Find a way to still do typo correction in this case.
938 TemplateName Template =
939 Context.getAssumedTemplateName(NameInfo.getName());
940 return NameClassification::UndeclaredTemplate(Template);
941 }
942
943 // In C, we first see whether there is a tag type by the same name, in
944 // which case it's likely that the user just forgot to write "enum",
945 // "struct", or "union".
946 if (!getLangOpts().CPlusPlus && !SecondTry &&
947 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
948 break;
949 }
950
951 // Perform typo correction to determine if there is another name that is
952 // close to this name.
953 if (!SecondTry && CCC) {
954 SecondTry = true;
955 if (TypoCorrection Corrected =
956 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
957 &SS, *CCC, CTK_ErrorRecovery)) {
958 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
959 unsigned QualifiedDiag = diag::err_no_member_suggest;
960
961 NamedDecl *FirstDecl = Corrected.getFoundDecl();
962 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
963 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
964 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
965 UnqualifiedDiag = diag::err_no_template_suggest;
966 QualifiedDiag = diag::err_no_member_template_suggest;
967 } else if (UnderlyingFirstDecl &&
968 (isa<TypeDecl>(UnderlyingFirstDecl) ||
969 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
970 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
971 UnqualifiedDiag = diag::err_unknown_typename_suggest;
972 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
973 }
974
975 if (SS.isEmpty()) {
976 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
977 } else {// FIXME: is this even reachable? Test it.
978 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
979 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
980 Name->getName().equals(CorrectedStr);
981 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
982 << Name << computeDeclContext(SS, false)
983 << DroppedSpecifier << SS.getRange());
984 }
985
986 // Update the name, so that the caller has the new name.
987 Name = Corrected.getCorrectionAsIdentifierInfo();
988
989 // Typo correction corrected to a keyword.
990 if (Corrected.isKeyword())
991 return Name;
992
993 // Also update the LookupResult...
994 // FIXME: This should probably go away at some point
995 Result.clear();
996 Result.setLookupName(Corrected.getCorrection());
997 if (FirstDecl)
998 Result.addDecl(FirstDecl);
999
1000 // If we found an Objective-C instance variable, let
1001 // LookupInObjCMethod build the appropriate expression to
1002 // reference the ivar.
1003 // FIXME: This is a gross hack.
1004 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1005 DeclResult R =
1006 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1007 if (R.isInvalid())
1008 return NameClassification::Error();
1009 if (R.isUsable())
1010 return NameClassification::NonType(Ivar);
1011 }
1012
1013 goto Corrected;
1014 }
1015 }
1016
1017 // We failed to correct; just fall through and let the parser deal with it.
1018 Result.suppressDiagnostics();
1019 return NameClassification::Unknown();
1020
1021 case LookupResult::NotFoundInCurrentInstantiation: {
1022 // We performed name lookup into the current instantiation, and there were
1023 // dependent bases, so we treat this result the same way as any other
1024 // dependent nested-name-specifier.
1025
1026 // C++ [temp.res]p2:
1027 // A name used in a template declaration or definition and that is
1028 // dependent on a template-parameter is assumed not to name a type
1029 // unless the applicable name lookup finds a type name or the name is
1030 // qualified by the keyword typename.
1031 //
1032 // FIXME: If the next token is '<', we might want to ask the parser to
1033 // perform some heroics to see if we actually have a
1034 // template-argument-list, which would indicate a missing 'template'
1035 // keyword here.
1036 return NameClassification::DependentNonType();
1037 }
1038
1039 case LookupResult::Found:
1040 case LookupResult::FoundOverloaded:
1041 case LookupResult::FoundUnresolvedValue:
1042 break;
1043
1044 case LookupResult::Ambiguous:
1045 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1046 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1047 /*AllowDependent=*/false)) {
1048 // C++ [temp.local]p3:
1049 // A lookup that finds an injected-class-name (10.2) can result in an
1050 // ambiguity in certain cases (for example, if it is found in more than
1051 // one base class). If all of the injected-class-names that are found
1052 // refer to specializations of the same class template, and if the name
1053 // is followed by a template-argument-list, the reference refers to the
1054 // class template itself and not a specialization thereof, and is not
1055 // ambiguous.
1056 //
1057 // This filtering can make an ambiguous result into an unambiguous one,
1058 // so try again after filtering out template names.
1059 FilterAcceptableTemplateNames(Result);
1060 if (!Result.isAmbiguous()) {
1061 IsFilteredTemplateName = true;
1062 break;
1063 }
1064 }
1065
1066 // Diagnose the ambiguity and return an error.
1067 return NameClassification::Error();
1068 }
1069
1070 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1071 (IsFilteredTemplateName ||
1072 hasAnyAcceptableTemplateNames(
1073 Result, /*AllowFunctionTemplates=*/true,
1074 /*AllowDependent=*/false,
1075 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1076 getLangOpts().CPlusPlus20))) {
1077 // C++ [temp.names]p3:
1078 // After name lookup (3.4) finds that a name is a template-name or that
1079 // an operator-function-id or a literal- operator-id refers to a set of
1080 // overloaded functions any member of which is a function template if
1081 // this is followed by a <, the < is always taken as the delimiter of a
1082 // template-argument-list and never as the less-than operator.
1083 // C++2a [temp.names]p2:
1084 // A name is also considered to refer to a template if it is an
1085 // unqualified-id followed by a < and name lookup finds either one
1086 // or more functions or finds nothing.
1087 if (!IsFilteredTemplateName)
1088 FilterAcceptableTemplateNames(Result);
1089
1090 bool IsFunctionTemplate;
1091 bool IsVarTemplate;
1092 TemplateName Template;
1093 if (Result.end() - Result.begin() > 1) {
1094 IsFunctionTemplate = true;
1095 Template = Context.getOverloadedTemplateName(Result.begin(),
1096 Result.end());
1097 } else if (!Result.empty()) {
1098 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1099 *Result.begin(), /*AllowFunctionTemplates=*/true,
1100 /*AllowDependent=*/false));
1101 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1102 IsVarTemplate = isa<VarTemplateDecl>(TD);
1103
1104 if (SS.isNotEmpty())
1105 Template =
1106 Context.getQualifiedTemplateName(SS.getScopeRep(),
1107 /*TemplateKeyword=*/false, TD);
1108 else
1109 Template = TemplateName(TD);
1110 } else {
1111 // All results were non-template functions. This is a function template
1112 // name.
1113 IsFunctionTemplate = true;
1114 Template = Context.getAssumedTemplateName(NameInfo.getName());
1115 }
1116
1117 if (IsFunctionTemplate) {
1118 // Function templates always go through overload resolution, at which
1119 // point we'll perform the various checks (e.g., accessibility) we need
1120 // to based on which function we selected.
1121 Result.suppressDiagnostics();
1122
1123 return NameClassification::FunctionTemplate(Template);
1124 }
1125
1126 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1127 : NameClassification::TypeTemplate(Template);
1128 }
1129
1130 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1131 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1132 DiagnoseUseOfDecl(Type, NameLoc);
1133 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1134 QualType T = Context.getTypeDeclType(Type);
1135 if (SS.isNotEmpty())
1136 return buildNestedType(*this, SS, T, NameLoc);
1137 return ParsedType::make(T);
1138 }
1139
1140 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1141 if (!Class) {
1142 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1143 if (ObjCCompatibleAliasDecl *Alias =
1144 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1145 Class = Alias->getClassInterface();
1146 }
1147
1148 if (Class) {
1149 DiagnoseUseOfDecl(Class, NameLoc);
1150
1151 if (NextToken.is(tok::period)) {
1152 // Interface. <something> is parsed as a property reference expression.
1153 // Just return "unknown" as a fall-through for now.
1154 Result.suppressDiagnostics();
1155 return NameClassification::Unknown();
1156 }
1157
1158 QualType T = Context.getObjCInterfaceType(Class);
1159 return ParsedType::make(T);
1160 }
1161
1162 if (isa<ConceptDecl>(FirstDecl))
1163 return NameClassification::Concept(
1164 TemplateName(cast<TemplateDecl>(FirstDecl)));
1165
1166 // We can have a type template here if we're classifying a template argument.
1167 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1168 !isa<VarTemplateDecl>(FirstDecl))
1169 return NameClassification::TypeTemplate(
1170 TemplateName(cast<TemplateDecl>(FirstDecl)));
1171
1172 // Check for a tag type hidden by a non-type decl in a few cases where it
1173 // seems likely a type is wanted instead of the non-type that was found.
1174 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1175 if ((NextToken.is(tok::identifier) ||
1176 (NextIsOp &&
1177 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1178 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1179 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1180 DiagnoseUseOfDecl(Type, NameLoc);
1181 QualType T = Context.getTypeDeclType(Type);
1182 if (SS.isNotEmpty())
1183 return buildNestedType(*this, SS, T, NameLoc);
1184 return ParsedType::make(T);
1185 }
1186
1187 // If we already know which single declaration is referenced, just annotate
1188 // that declaration directly. Defer resolving even non-overloaded class
1189 // member accesses, as we need to defer certain access checks until we know
1190 // the context.
1191 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1192 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1193 return NameClassification::NonType(Result.getRepresentativeDecl());
1194
1195 // Otherwise, this is an overload set that we will need to resolve later.
1196 Result.suppressDiagnostics();
1197 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1198 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1199 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1200 Result.begin(), Result.end()));
1201}
1202
1203ExprResult
1204Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1205 SourceLocation NameLoc) {
1206 assert(getLangOpts().CPlusPlus && "ADL-only call in C?")((getLangOpts().CPlusPlus && "ADL-only call in C?") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL-only call in C?\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1206, __PRETTY_FUNCTION__))
;
1207 CXXScopeSpec SS;
1208 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1209 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1210}
1211
1212ExprResult
1213Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1214 IdentifierInfo *Name,
1215 SourceLocation NameLoc,
1216 bool IsAddressOfOperand) {
1217 DeclarationNameInfo NameInfo(Name, NameLoc);
1218 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1219 NameInfo, IsAddressOfOperand,
1220 /*TemplateArgs=*/nullptr);
1221}
1222
1223ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1224 NamedDecl *Found,
1225 SourceLocation NameLoc,
1226 const Token &NextToken) {
1227 if (getCurMethodDecl() && SS.isEmpty())
1228 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1229 return BuildIvarRefExpr(S, NameLoc, Ivar);
1230
1231 // Reconstruct the lookup result.
1232 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1233 Result.addDecl(Found);
1234 Result.resolveKind();
1235
1236 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1237 return BuildDeclarationNameExpr(SS, Result, ADL);
1238}
1239
1240ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1241 // For an implicit class member access, transform the result into a member
1242 // access expression if necessary.
1243 auto *ULE = cast<UnresolvedLookupExpr>(E);
1244 if ((*ULE->decls_begin())->isCXXClassMember()) {
1245 CXXScopeSpec SS;
1246 SS.Adopt(ULE->getQualifierLoc());
1247
1248 // Reconstruct the lookup result.
1249 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1250 LookupOrdinaryName);
1251 Result.setNamingClass(ULE->getNamingClass());
1252 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1253 Result.addDecl(*I, I.getAccess());
1254 Result.resolveKind();
1255 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1256 nullptr, S);
1257 }
1258
1259 // Otherwise, this is already in the form we needed, and no further checks
1260 // are necessary.
1261 return ULE;
1262}
1263
1264Sema::TemplateNameKindForDiagnostics
1265Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1266 auto *TD = Name.getAsTemplateDecl();
1267 if (!TD)
1268 return TemplateNameKindForDiagnostics::DependentTemplate;
1269 if (isa<ClassTemplateDecl>(TD))
1270 return TemplateNameKindForDiagnostics::ClassTemplate;
1271 if (isa<FunctionTemplateDecl>(TD))
1272 return TemplateNameKindForDiagnostics::FunctionTemplate;
1273 if (isa<VarTemplateDecl>(TD))
1274 return TemplateNameKindForDiagnostics::VarTemplate;
1275 if (isa<TypeAliasTemplateDecl>(TD))
1276 return TemplateNameKindForDiagnostics::AliasTemplate;
1277 if (isa<TemplateTemplateParmDecl>(TD))
1278 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1279 if (isa<ConceptDecl>(TD))
1280 return TemplateNameKindForDiagnostics::Concept;
1281 return TemplateNameKindForDiagnostics::DependentTemplate;
1282}
1283
1284void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1285 assert(DC->getLexicalParent() == CurContext &&((DC->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1286, __PRETTY_FUNCTION__))
1286 "The next DeclContext should be lexically contained in the current one.")((DC->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1286, __PRETTY_FUNCTION__))
;
1287 CurContext = DC;
1288 S->setEntity(DC);
1289}
1290
1291void Sema::PopDeclContext() {
1292 assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1292, __PRETTY_FUNCTION__))
;
1293
1294 CurContext = CurContext->getLexicalParent();
1295 assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1295, __PRETTY_FUNCTION__))
;
1296}
1297
1298Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1299 Decl *D) {
1300 // Unlike PushDeclContext, the context to which we return is not necessarily
1301 // the containing DC of TD, because the new context will be some pre-existing
1302 // TagDecl definition instead of a fresh one.
1303 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1304 CurContext = cast<TagDecl>(D)->getDefinition();
1305 assert(CurContext && "skipping definition of undefined tag")((CurContext && "skipping definition of undefined tag"
) ? static_cast<void> (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1305, __PRETTY_FUNCTION__))
;
1306 // Start lookups from the parent of the current context; we don't want to look
1307 // into the pre-existing complete definition.
1308 S->setEntity(CurContext->getLookupParent());
1309 return Result;
1310}
1311
1312void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1313 CurContext = static_cast<decltype(CurContext)>(Context);
1314}
1315
1316/// EnterDeclaratorContext - Used when we must lookup names in the context
1317/// of a declarator's nested name specifier.
1318///
1319void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1320 // C++0x [basic.lookup.unqual]p13:
1321 // A name used in the definition of a static data member of class
1322 // X (after the qualified-id of the static member) is looked up as
1323 // if the name was used in a member function of X.
1324 // C++0x [basic.lookup.unqual]p14:
1325 // If a variable member of a namespace is defined outside of the
1326 // scope of its namespace then any name used in the definition of
1327 // the variable member (after the declarator-id) is looked up as
1328 // if the definition of the variable member occurred in its
1329 // namespace.
1330 // Both of these imply that we should push a scope whose context
1331 // is the semantic context of the declaration. We can't use
1332 // PushDeclContext here because that context is not necessarily
1333 // lexically contained in the current context. Fortunately,
1334 // the containing scope should have the appropriate information.
1335
1336 assert(!S->getEntity() && "scope already has entity")((!S->getEntity() && "scope already has entity") ?
static_cast<void> (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1336, __PRETTY_FUNCTION__))
;
1337
1338#ifndef NDEBUG
1339 Scope *Ancestor = S->getParent();
1340 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1341 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")((Ancestor->getEntity() == CurContext && "ancestor context mismatch"
) ? static_cast<void> (0) : __assert_fail ("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1341, __PRETTY_FUNCTION__))
;
1342#endif
1343
1344 CurContext = DC;
1345 S->setEntity(DC);
1346
1347 if (S->getParent()->isTemplateParamScope()) {
1348 // Also set the corresponding entities for all immediately-enclosing
1349 // template parameter scopes.
1350 EnterTemplatedContext(S->getParent(), DC);
1351 }
1352}
1353
1354void Sema::ExitDeclaratorContext(Scope *S) {
1355 assert(S->getEntity() == CurContext && "Context imbalance!")((S->getEntity() == CurContext && "Context imbalance!"
) ? static_cast<void> (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1355, __PRETTY_FUNCTION__))
;
1356
1357 // Switch back to the lexical context. The safety of this is
1358 // enforced by an assert in EnterDeclaratorContext.
1359 Scope *Ancestor = S->getParent();
1360 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1361 CurContext = Ancestor->getEntity();
1362
1363 // We don't need to do anything with the scope, which is going to
1364 // disappear.
1365}
1366
1367void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1368 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "expected to be initializing a template parameter scope"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1369, __PRETTY_FUNCTION__))
1369 "expected to be initializing a template parameter scope")((S->isTemplateParamScope() && "expected to be initializing a template parameter scope"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1369, __PRETTY_FUNCTION__))
;
1370
1371 // C++20 [temp.local]p7:
1372 // In the definition of a member of a class template that appears outside
1373 // of the class template definition, the name of a member of the class
1374 // template hides the name of a template-parameter of any enclosing class
1375 // templates (but not a template-parameter of the member if the member is a
1376 // class or function template).
1377 // C++20 [temp.local]p9:
1378 // In the definition of a class template or in the definition of a member
1379 // of such a template that appears outside of the template definition, for
1380 // each non-dependent base class (13.8.2.1), if the name of the base class
1381 // or the name of a member of the base class is the same as the name of a
1382 // template-parameter, the base class name or member name hides the
1383 // template-parameter name (6.4.10).
1384 //
1385 // This means that a template parameter scope should be searched immediately
1386 // after searching the DeclContext for which it is a template parameter
1387 // scope. For example, for
1388 // template<typename T> template<typename U> template<typename V>
1389 // void N::A<T>::B<U>::f(...)
1390 // we search V then B<U> (and base classes) then U then A<T> (and base
1391 // classes) then T then N then ::.
1392 unsigned ScopeDepth = getTemplateDepth(S);
1393 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1394 DeclContext *SearchDCAfterScope = DC;
1395 for (; DC; DC = DC->getLookupParent()) {
1396 if (const TemplateParameterList *TPL =
1397 cast<Decl>(DC)->getDescribedTemplateParams()) {
1398 unsigned DCDepth = TPL->getDepth() + 1;
1399 if (DCDepth > ScopeDepth)
1400 continue;
1401 if (ScopeDepth == DCDepth)
1402 SearchDCAfterScope = DC = DC->getLookupParent();
1403 break;
1404 }
1405 }
1406 S->setLookupEntity(SearchDCAfterScope);
1407 }
1408}
1409
1410void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1411 // We assume that the caller has already called
1412 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1413 FunctionDecl *FD = D->getAsFunction();
1414 if (!FD)
1415 return;
1416
1417 // Same implementation as PushDeclContext, but enters the context
1418 // from the lexical parent, rather than the top-level class.
1419 assert(CurContext == FD->getLexicalParent() &&((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1420, __PRETTY_FUNCTION__))
1420 "The next DeclContext should be lexically contained in the current one.")((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1420, __PRETTY_FUNCTION__))
;
1421 CurContext = FD;
1422 S->setEntity(CurContext);
1423
1424 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1425 ParmVarDecl *Param = FD->getParamDecl(P);
1426 // If the parameter has an identifier, then add it to the scope
1427 if (Param->getIdentifier()) {
1428 S->AddDecl(Param);
1429 IdResolver.AddDecl(Param);
1430 }
1431 }
1432}
1433
1434void Sema::ActOnExitFunctionContext() {
1435 // Same implementation as PopDeclContext, but returns to the lexical parent,
1436 // rather than the top-level class.
1437 assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1437, __PRETTY_FUNCTION__))
;
1438 CurContext = CurContext->getLexicalParent();
1439 assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1439, __PRETTY_FUNCTION__))
;
1440}
1441
1442/// Determine whether we allow overloading of the function
1443/// PrevDecl with another declaration.
1444///
1445/// This routine determines whether overloading is possible, not
1446/// whether some new function is actually an overload. It will return
1447/// true in C++ (where we can always provide overloads) or, as an
1448/// extension, in C when the previous function is already an
1449/// overloaded function declaration or has the "overloadable"
1450/// attribute.
1451static bool AllowOverloadingOfFunction(LookupResult &Previous,
1452 ASTContext &Context,
1453 const FunctionDecl *New) {
1454 if (Context.getLangOpts().CPlusPlus)
1455 return true;
1456
1457 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1458 return true;
1459
1460 return Previous.getResultKind() == LookupResult::Found &&
1461 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1462 New->hasAttr<OverloadableAttr>());
1463}
1464
1465/// Add this decl to the scope shadowed decl chains.
1466void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1467 // Move up the scope chain until we find the nearest enclosing
1468 // non-transparent context. The declaration will be introduced into this
1469 // scope.
1470 while (S->getEntity() && S->getEntity()->isTransparentContext())
1471 S = S->getParent();
1472
1473 // Add scoped declarations into their context, so that they can be
1474 // found later. Declarations without a context won't be inserted
1475 // into any context.
1476 if (AddToContext)
1477 CurContext->addDecl(D);
1478
1479 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1480 // are function-local declarations.
1481 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1482 return;
1483
1484 // Template instantiations should also not be pushed into scope.
1485 if (isa<FunctionDecl>(D) &&
1486 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1487 return;
1488
1489 // If this replaces anything in the current scope,
1490 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1491 IEnd = IdResolver.end();
1492 for (; I != IEnd; ++I) {
1493 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1494 S->RemoveDecl(*I);
1495 IdResolver.RemoveDecl(*I);
1496
1497 // Should only need to replace one decl.
1498 break;
1499 }
1500 }
1501
1502 S->AddDecl(D);
1503
1504 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1505 // Implicitly-generated labels may end up getting generated in an order that
1506 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1507 // the label at the appropriate place in the identifier chain.
1508 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1509 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1510 if (IDC == CurContext) {
1511 if (!S->isDeclScope(*I))
1512 continue;
1513 } else if (IDC->Encloses(CurContext))
1514 break;
1515 }
1516
1517 IdResolver.InsertDeclAfter(I, D);
1518 } else {
1519 IdResolver.AddDecl(D);
1520 }
1521}
1522
1523bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1524 bool AllowInlineNamespace) {
1525 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1526}
1527
1528Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1529 DeclContext *TargetDC = DC->getPrimaryContext();
1530 do {
1531 if (DeclContext *ScopeDC = S->getEntity())
1532 if (ScopeDC->getPrimaryContext() == TargetDC)
1533 return S;
1534 } while ((S = S->getParent()));
1535
1536 return nullptr;
1537}
1538
1539static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1540 DeclContext*,
1541 ASTContext&);
1542
1543/// Filters out lookup results that don't fall within the given scope
1544/// as determined by isDeclInScope.
1545void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1546 bool ConsiderLinkage,
1547 bool AllowInlineNamespace) {
1548 LookupResult::Filter F = R.makeFilter();
1549 while (F.hasNext()) {
1550 NamedDecl *D = F.next();
1551
1552 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1553 continue;
1554
1555 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1556 continue;
1557
1558 F.erase();
1559 }
1560
1561 F.done();
1562}
1563
1564/// We've determined that \p New is a redeclaration of \p Old. Check that they
1565/// have compatible owning modules.
1566bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1567 // FIXME: The Modules TS is not clear about how friend declarations are
1568 // to be treated. It's not meaningful to have different owning modules for
1569 // linkage in redeclarations of the same entity, so for now allow the
1570 // redeclaration and change the owning modules to match.
1571 if (New->getFriendObjectKind() &&
1572 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1573 New->setLocalOwningModule(Old->getOwningModule());
1574 makeMergedDefinitionVisible(New);
1575 return false;
1576 }
1577
1578 Module *NewM = New->getOwningModule();
1579 Module *OldM = Old->getOwningModule();
1580
1581 if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1582 NewM = NewM->Parent;
1583 if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1584 OldM = OldM->Parent;
1585
1586 if (NewM == OldM)
1587 return false;
1588
1589 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1590 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1591 if (NewIsModuleInterface || OldIsModuleInterface) {
1592 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1593 // if a declaration of D [...] appears in the purview of a module, all
1594 // other such declarations shall appear in the purview of the same module
1595 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1596 << New
1597 << NewIsModuleInterface
1598 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1599 << OldIsModuleInterface
1600 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1601 Diag(Old->getLocation(), diag::note_previous_declaration);
1602 New->setInvalidDecl();
1603 return true;
1604 }
1605
1606 return false;
1607}
1608
1609static bool isUsingDecl(NamedDecl *D) {
1610 return isa<UsingShadowDecl>(D) ||
1611 isa<UnresolvedUsingTypenameDecl>(D) ||
1612 isa<UnresolvedUsingValueDecl>(D);
1613}
1614
1615/// Removes using shadow declarations from the lookup results.
1616static void RemoveUsingDecls(LookupResult &R) {
1617 LookupResult::Filter F = R.makeFilter();
1618 while (F.hasNext())
1619 if (isUsingDecl(F.next()))
1620 F.erase();
1621
1622 F.done();
1623}
1624
1625/// Check for this common pattern:
1626/// @code
1627/// class S {
1628/// S(const S&); // DO NOT IMPLEMENT
1629/// void operator=(const S&); // DO NOT IMPLEMENT
1630/// };
1631/// @endcode
1632static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1633 // FIXME: Should check for private access too but access is set after we get
1634 // the decl here.
1635 if (D->doesThisDeclarationHaveABody())
1636 return false;
1637
1638 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1639 return CD->isCopyConstructor();
1640 return D->isCopyAssignmentOperator();
1641}
1642
1643// We need this to handle
1644//
1645// typedef struct {
1646// void *foo() { return 0; }
1647// } A;
1648//
1649// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1650// for example. If 'A', foo will have external linkage. If we have '*A',
1651// foo will have no linkage. Since we can't know until we get to the end
1652// of the typedef, this function finds out if D might have non-external linkage.
1653// Callers should verify at the end of the TU if it D has external linkage or
1654// not.
1655bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1656 const DeclContext *DC = D->getDeclContext();
1657 while (!DC->isTranslationUnit()) {
1658 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1659 if (!RD->hasNameForLinkage())
1660 return true;
1661 }
1662 DC = DC->getParent();
1663 }
1664
1665 return !D->isExternallyVisible();
1666}
1667
1668// FIXME: This needs to be refactored; some other isInMainFile users want
1669// these semantics.
1670static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1671 if (S.TUKind != TU_Complete)
1672 return false;
1673 return S.SourceMgr.isInMainFile(Loc);
1674}
1675
1676bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1677 assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1677, __PRETTY_FUNCTION__))
;
1678
1679 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1680 return false;
1681
1682 // Ignore all entities declared within templates, and out-of-line definitions
1683 // of members of class templates.
1684 if (D->getDeclContext()->isDependentContext() ||
1685 D->getLexicalDeclContext()->isDependentContext())
1686 return false;
1687
1688 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1689 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1690 return false;
1691 // A non-out-of-line declaration of a member specialization was implicitly
1692 // instantiated; it's the out-of-line declaration that we're interested in.
1693 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1694 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1695 return false;
1696
1697 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1698 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1699 return false;
1700 } else {
1701 // 'static inline' functions are defined in headers; don't warn.
1702 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1703 return false;
1704 }
1705
1706 if (FD->doesThisDeclarationHaveABody() &&
1707 Context.DeclMustBeEmitted(FD))
1708 return false;
1709 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1710 // Constants and utility variables are defined in headers with internal
1711 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1712 // like "inline".)
1713 if (!isMainFileLoc(*this, VD->getLocation()))
1714 return false;
1715
1716 if (Context.DeclMustBeEmitted(VD))
1717 return false;
1718
1719 if (VD->isStaticDataMember() &&
1720 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1721 return false;
1722 if (VD->isStaticDataMember() &&
1723 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1724 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1725 return false;
1726
1727 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1728 return false;
1729 } else {
1730 return false;
1731 }
1732
1733 // Only warn for unused decls internal to the translation unit.
1734 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1735 // for inline functions defined in the main source file, for instance.
1736 return mightHaveNonExternalLinkage(D);
1737}
1738
1739void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1740 if (!D)
1741 return;
1742
1743 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1744 const FunctionDecl *First = FD->getFirstDecl();
1745 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1746 return; // First should already be in the vector.
1747 }
1748
1749 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1750 const VarDecl *First = VD->getFirstDecl();
1751 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1752 return; // First should already be in the vector.
1753 }
1754
1755 if (ShouldWarnIfUnusedFileScopedDecl(D))
1756 UnusedFileScopedDecls.push_back(D);
1757}
1758
1759static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1760 if (D->isInvalidDecl())
1761 return false;
1762
1763 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1764 // For a decomposition declaration, warn if none of the bindings are
1765 // referenced, instead of if the variable itself is referenced (which
1766 // it is, by the bindings' expressions).
1767 for (auto *BD : DD->bindings())
1768 if (BD->isReferenced())
1769 return false;
1770 } else if (!D->getDeclName()) {
1771 return false;
1772 } else if (D->isReferenced() || D->isUsed()) {
1773 return false;
1774 }
1775
1776 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1777 return false;
1778
1779 if (isa<LabelDecl>(D))
1780 return true;
1781
1782 // Except for labels, we only care about unused decls that are local to
1783 // functions.
1784 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1785 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1786 // For dependent types, the diagnostic is deferred.
1787 WithinFunction =
1788 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1789 if (!WithinFunction)
1790 return false;
1791
1792 if (isa<TypedefNameDecl>(D))
1793 return true;
1794
1795 // White-list anything that isn't a local variable.
1796 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1797 return false;
1798
1799 // Types of valid local variables should be complete, so this should succeed.
1800 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1801
1802 // White-list anything with an __attribute__((unused)) type.
1803 const auto *Ty = VD->getType().getTypePtr();
1804
1805 // Only look at the outermost level of typedef.
1806 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1807 if (TT->getDecl()->hasAttr<UnusedAttr>())
1808 return false;
1809 }
1810
1811 // If we failed to complete the type for some reason, or if the type is
1812 // dependent, don't diagnose the variable.
1813 if (Ty->isIncompleteType() || Ty->isDependentType())
1814 return false;
1815
1816 // Look at the element type to ensure that the warning behaviour is
1817 // consistent for both scalars and arrays.
1818 Ty = Ty->getBaseElementTypeUnsafe();
1819
1820 if (const TagType *TT = Ty->getAs<TagType>()) {
1821 const TagDecl *Tag = TT->getDecl();
1822 if (Tag->hasAttr<UnusedAttr>())
1823 return false;
1824
1825 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1826 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1827 return false;
1828
1829 if (const Expr *Init = VD->getInit()) {
1830 if (const ExprWithCleanups *Cleanups =
1831 dyn_cast<ExprWithCleanups>(Init))
1832 Init = Cleanups->getSubExpr();
1833 const CXXConstructExpr *Construct =
1834 dyn_cast<CXXConstructExpr>(Init);
1835 if (Construct && !Construct->isElidable()) {
1836 CXXConstructorDecl *CD = Construct->getConstructor();
1837 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1838 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1839 return false;
1840 }
1841
1842 // Suppress the warning if we don't know how this is constructed, and
1843 // it could possibly be non-trivial constructor.
1844 if (Init->isTypeDependent())
1845 for (const CXXConstructorDecl *Ctor : RD->ctors())
1846 if (!Ctor->isTrivial())
1847 return false;
1848 }
1849 }
1850 }
1851
1852 // TODO: __attribute__((unused)) templates?
1853 }
1854
1855 return true;
1856}
1857
1858static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1859 FixItHint &Hint) {
1860 if (isa<LabelDecl>(D)) {
1861 SourceLocation AfterColon = Lexer::findLocationAfterToken(
1862 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1863 true);
1864 if (AfterColon.isInvalid())
1865 return;
1866 Hint = FixItHint::CreateRemoval(
1867 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1868 }
1869}
1870
1871void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1872 if (D->getTypeForDecl()->isDependentType())
1873 return;
1874
1875 for (auto *TmpD : D->decls()) {
1876 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1877 DiagnoseUnusedDecl(T);
1878 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1879 DiagnoseUnusedNestedTypedefs(R);
1880 }
1881}
1882
1883/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1884/// unless they are marked attr(unused).
1885void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1886 if (!ShouldDiagnoseUnusedDecl(D))
1887 return;
1888
1889 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1890 // typedefs can be referenced later on, so the diagnostics are emitted
1891 // at end-of-translation-unit.
1892 UnusedLocalTypedefNameCandidates.insert(TD);
1893 return;
1894 }
1895
1896 FixItHint Hint;
1897 GenerateFixForUnusedDecl(D, Context, Hint);
1898
1899 unsigned DiagID;
1900 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1901 DiagID = diag::warn_unused_exception_param;
1902 else if (isa<LabelDecl>(D))
1903 DiagID = diag::warn_unused_label;
1904 else
1905 DiagID = diag::warn_unused_variable;
1906
1907 Diag(D->getLocation(), DiagID) << D << Hint;
1908}
1909
1910static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1911 // Verify that we have no forward references left. If so, there was a goto
1912 // or address of a label taken, but no definition of it. Label fwd
1913 // definitions are indicated with a null substmt which is also not a resolved
1914 // MS inline assembly label name.
1915 bool Diagnose = false;
1916 if (L->isMSAsmLabel())
1917 Diagnose = !L->isResolvedMSAsmLabel();
1918 else
1919 Diagnose = L->getStmt() == nullptr;
1920 if (Diagnose)
1921 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1922}
1923
1924void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1925 S->mergeNRVOIntoParent();
1926
1927 if (S->decl_empty()) return;
1928 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope
)) && "Scope shouldn't contain decls!") ? static_cast
<void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1929, __PRETTY_FUNCTION__))
1929 "Scope shouldn't contain decls!")(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope
)) && "Scope shouldn't contain decls!") ? static_cast
<void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1929, __PRETTY_FUNCTION__))
;
1930
1931 for (auto *TmpD : S->decls()) {
1932 assert(TmpD && "This decl didn't get pushed??")((TmpD && "This decl didn't get pushed??") ? static_cast
<void> (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1932, __PRETTY_FUNCTION__))
;
1933
1934 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")((isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"
) ? static_cast<void> (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 1934, __PRETTY_FUNCTION__))
;
1935 NamedDecl *D = cast<NamedDecl>(TmpD);
1936
1937 // Diagnose unused variables in this scope.
1938 if (!S->hasUnrecoverableErrorOccurred()) {
1939 DiagnoseUnusedDecl(D);
1940 if (const auto *RD = dyn_cast<RecordDecl>(D))
1941 DiagnoseUnusedNestedTypedefs(RD);
1942 }
1943
1944 if (!D->getDeclName()) continue;
1945
1946 // If this was a forward reference to a label, verify it was defined.
1947 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1948 CheckPoppedLabel(LD, *this);
1949
1950 // Remove this name from our lexical scope, and warn on it if we haven't
1951 // already.
1952 IdResolver.RemoveDecl(D);
1953 auto ShadowI = ShadowingDecls.find(D);
1954 if (ShadowI != ShadowingDecls.end()) {
1955 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1956 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1957 << D << FD << FD->getParent();
1958 Diag(FD->getLocation(), diag::note_previous_declaration);
1959 }
1960 ShadowingDecls.erase(ShadowI);
1961 }
1962 }
1963}
1964
1965/// Look for an Objective-C class in the translation unit.
1966///
1967/// \param Id The name of the Objective-C class we're looking for. If
1968/// typo-correction fixes this name, the Id will be updated
1969/// to the fixed name.
1970///
1971/// \param IdLoc The location of the name in the translation unit.
1972///
1973/// \param DoTypoCorrection If true, this routine will attempt typo correction
1974/// if there is no class with the given name.
1975///
1976/// \returns The declaration of the named Objective-C class, or NULL if the
1977/// class could not be found.
1978ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1979 SourceLocation IdLoc,
1980 bool DoTypoCorrection) {
1981 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1982 // creation from this context.
1983 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1984
1985 if (!IDecl && DoTypoCorrection) {
1986 // Perform typo correction at the given location, but only if we
1987 // find an Objective-C class name.
1988 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1989 if (TypoCorrection C =
1990 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1991 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1992 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1993 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1994 Id = IDecl->getIdentifier();
1995 }
1996 }
1997 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1998 // This routine must always return a class definition, if any.
1999 if (Def && Def->getDefinition())
2000 Def = Def->getDefinition();
2001 return Def;
2002}
2003
2004/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2005/// from S, where a non-field would be declared. This routine copes
2006/// with the difference between C and C++ scoping rules in structs and
2007/// unions. For example, the following code is well-formed in C but
2008/// ill-formed in C++:
2009/// @code
2010/// struct S6 {
2011/// enum { BAR } e;
2012/// };
2013///
2014/// void test_S6() {
2015/// struct S6 a;
2016/// a.e = BAR;
2017/// }
2018/// @endcode
2019/// For the declaration of BAR, this routine will return a different
2020/// scope. The scope S will be the scope of the unnamed enumeration
2021/// within S6. In C++, this routine will return the scope associated
2022/// with S6, because the enumeration's scope is a transparent
2023/// context but structures can contain non-field names. In C, this
2024/// routine will return the translation unit scope, since the
2025/// enumeration's scope is a transparent context and structures cannot
2026/// contain non-field names.
2027Scope *Sema::getNonFieldDeclScope(Scope *S) {
2028 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2029 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2030 (S->isClassScope() && !getLangOpts().CPlusPlus))
2031 S = S->getParent();
2032 return S;
2033}
2034
2035static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2036 ASTContext::GetBuiltinTypeError Error) {
2037 switch (Error) {
2038 case ASTContext::GE_None:
2039 return "";
2040 case ASTContext::GE_Missing_type:
2041 return BuiltinInfo.getHeaderName(ID);
2042 case ASTContext::GE_Missing_stdio:
2043 return "stdio.h";
2044 case ASTContext::GE_Missing_setjmp:
2045 return "setjmp.h";
2046 case ASTContext::GE_Missing_ucontext:
2047 return "ucontext.h";
2048 }
2049 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 2049)
;
2050}
2051
2052FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2053 unsigned ID, SourceLocation Loc) {
2054 DeclContext *Parent = Context.getTranslationUnitDecl();
2055
2056 if (getLangOpts().CPlusPlus) {
2057 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2058 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2059 CLinkageDecl->setImplicit();
2060 Parent->addDecl(CLinkageDecl);
2061 Parent = CLinkageDecl;
2062 }
2063
2064 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2065 /*TInfo=*/nullptr, SC_Extern, false,
2066 Type->isFunctionProtoType());
2067 New->setImplicit();
2068 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2069
2070 // Create Decl objects for each parameter, adding them to the
2071 // FunctionDecl.
2072 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2073 SmallVector<ParmVarDecl *, 16> Params;
2074 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2075 ParmVarDecl *parm = ParmVarDecl::Create(
2076 Context, New, SourceLocation(), SourceLocation(), nullptr,
2077 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2078 parm->setScopeInfo(0, i);
2079 Params.push_back(parm);
2080 }
2081 New->setParams(Params);
2082 }
2083
2084 AddKnownFunctionAttributes(New);
2085 return New;
2086}
2087
2088/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2089/// file scope. lazily create a decl for it. ForRedeclaration is true
2090/// if we're creating this built-in in anticipation of redeclaring the
2091/// built-in.
2092NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2093 Scope *S, bool ForRedeclaration,
2094 SourceLocation Loc) {
2095 LookupNecessaryTypesForBuiltin(S, ID);
2096
2097 ASTContext::GetBuiltinTypeError Error;
2098 QualType R = Context.GetBuiltinType(ID, Error);
2099 if (Error) {
2100 if (!ForRedeclaration)
2101 return nullptr;
2102
2103 // If we have a builtin without an associated type we should not emit a
2104 // warning when we were not able to find a type for it.
2105 if (Error == ASTContext::GE_Missing_type ||
2106 Context.BuiltinInfo.allowTypeMismatch(ID))
2107 return nullptr;
2108
2109 // If we could not find a type for setjmp it is because the jmp_buf type was
2110 // not defined prior to the setjmp declaration.
2111 if (Error == ASTContext::GE_Missing_setjmp) {
2112 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2113 << Context.BuiltinInfo.getName(ID);
2114 return nullptr;
2115 }
2116
2117 // Generally, we emit a warning that the declaration requires the
2118 // appropriate header.
2119 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2120 << getHeaderName(Context.BuiltinInfo, ID, Error)
2121 << Context.BuiltinInfo.getName(ID);
2122 return nullptr;
2123 }
2124
2125 if (!ForRedeclaration &&
2126 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2127 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2128 Diag(Loc, diag::ext_implicit_lib_function_decl)
2129 << Context.BuiltinInfo.getName(ID) << R;
2130 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2131 Diag(Loc, diag::note_include_header_or_declare)
2132 << Header << Context.BuiltinInfo.getName(ID);
2133 }
2134
2135 if (R.isNull())
2136 return nullptr;
2137
2138 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2139 RegisterLocallyScopedExternCDecl(New, S);
2140
2141 // TUScope is the translation-unit scope to insert this function into.
2142 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2143 // relate Scopes to DeclContexts, and probably eliminate CurContext
2144 // entirely, but we're not there yet.
2145 DeclContext *SavedContext = CurContext;
2146 CurContext = New->getDeclContext();
2147 PushOnScopeChains(New, TUScope);
2148 CurContext = SavedContext;
2149 return New;
2150}
2151
2152/// Typedef declarations don't have linkage, but they still denote the same
2153/// entity if their types are the same.
2154/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2155/// isSameEntity.
2156static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2157 TypedefNameDecl *Decl,
2158 LookupResult &Previous) {
2159 // This is only interesting when modules are enabled.
2160 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2161 return;
2162
2163 // Empty sets are uninteresting.
2164 if (Previous.empty())
2165 return;
2166
2167 LookupResult::Filter Filter = Previous.makeFilter();
2168 while (Filter.hasNext()) {
2169 NamedDecl *Old = Filter.next();
2170
2171 // Non-hidden declarations are never ignored.
2172 if (S.isVisible(Old))
2173 continue;
2174
2175 // Declarations of the same entity are not ignored, even if they have
2176 // different linkages.
2177 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2178 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2179 Decl->getUnderlyingType()))
2180 continue;
2181
2182 // If both declarations give a tag declaration a typedef name for linkage
2183 // purposes, then they declare the same entity.
2184 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2185 Decl->getAnonDeclWithTypedefName())
2186 continue;
2187 }
2188
2189 Filter.erase();
2190 }
2191
2192 Filter.done();
2193}
2194
2195bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2196 QualType OldType;
2197 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2198 OldType = OldTypedef->getUnderlyingType();
2199 else
2200 OldType = Context.getTypeDeclType(Old);
2201 QualType NewType = New->getUnderlyingType();
2202
2203 if (NewType->isVariablyModifiedType()) {
2204 // Must not redefine a typedef with a variably-modified type.
2205 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2206 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2207 << Kind << NewType;
2208 if (Old->getLocation().isValid())
2209 notePreviousDefinition(Old, New->getLocation());
2210 New->setInvalidDecl();
2211 return true;
2212 }
2213
2214 if (OldType != NewType &&
2215 !OldType->isDependentType() &&
2216 !NewType->isDependentType() &&
2217 !Context.hasSameType(OldType, NewType)) {
2218 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2219 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2220 << Kind << NewType << OldType;
2221 if (Old->getLocation().isValid())
2222 notePreviousDefinition(Old, New->getLocation());
2223 New->setInvalidDecl();
2224 return true;
2225 }
2226 return false;
2227}
2228
2229/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2230/// same name and scope as a previous declaration 'Old'. Figure out
2231/// how to resolve this situation, merging decls or emitting
2232/// diagnostics as appropriate. If there was an error, set New to be invalid.
2233///
2234void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2235 LookupResult &OldDecls) {
2236 // If the new decl is known invalid already, don't bother doing any
2237 // merging checks.
2238 if (New->isInvalidDecl()) return;
2239
2240 // Allow multiple definitions for ObjC built-in typedefs.
2241 // FIXME: Verify the underlying types are equivalent!
2242 if (getLangOpts().ObjC) {
2243 const IdentifierInfo *TypeID = New->getIdentifier();
2244 switch (TypeID->getLength()) {
2245 default: break;
2246 case 2:
2247 {
2248 if (!TypeID->isStr("id"))
2249 break;
2250 QualType T = New->getUnderlyingType();
2251 if (!T->isPointerType())
2252 break;
2253 if (!T->isVoidPointerType()) {
2254 QualType PT = T->castAs<PointerType>()->getPointeeType();
2255 if (!PT->isStructureType())
2256 break;
2257 }
2258 Context.setObjCIdRedefinitionType(T);
2259 // Install the built-in type for 'id', ignoring the current definition.
2260 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2261 return;
2262 }
2263 case 5:
2264 if (!TypeID->isStr("Class"))
2265 break;
2266 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2267 // Install the built-in type for 'Class', ignoring the current definition.
2268 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2269 return;
2270 case 3:
2271 if (!TypeID->isStr("SEL"))
2272 break;
2273 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2274 // Install the built-in type for 'SEL', ignoring the current definition.
2275 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2276 return;
2277 }
2278 // Fall through - the typedef name was not a builtin type.
2279 }
2280
2281 // Verify the old decl was also a type.
2282 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2283 if (!Old) {
2284 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2285 << New->getDeclName();
2286
2287 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2288 if (OldD->getLocation().isValid())
2289 notePreviousDefinition(OldD, New->getLocation());
2290
2291 return New->setInvalidDecl();
2292 }
2293
2294 // If the old declaration is invalid, just give up here.
2295 if (Old->isInvalidDecl())
2296 return New->setInvalidDecl();
2297
2298 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2299 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2300 auto *NewTag = New->getAnonDeclWithTypedefName();
2301 NamedDecl *Hidden = nullptr;
2302 if (OldTag && NewTag &&
2303 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2304 !hasVisibleDefinition(OldTag, &Hidden)) {
2305 // There is a definition of this tag, but it is not visible. Use it
2306 // instead of our tag.
2307 New->setTypeForDecl(OldTD->getTypeForDecl());
2308 if (OldTD->isModed())
2309 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2310 OldTD->getUnderlyingType());
2311 else
2312 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2313
2314 // Make the old tag definition visible.
2315 makeMergedDefinitionVisible(Hidden);
2316
2317 // If this was an unscoped enumeration, yank all of its enumerators
2318 // out of the scope.
2319 if (isa<EnumDecl>(NewTag)) {
2320 Scope *EnumScope = getNonFieldDeclScope(S);
2321 for (auto *D : NewTag->decls()) {
2322 auto *ED = cast<EnumConstantDecl>(D);
2323 assert(EnumScope->isDeclScope(ED))((EnumScope->isDeclScope(ED)) ? static_cast<void> (0
) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 2323, __PRETTY_FUNCTION__))
;
2324 EnumScope->RemoveDecl(ED);
2325 IdResolver.RemoveDecl(ED);
2326 ED->getLexicalDeclContext()->removeDecl(ED);
2327 }
2328 }
2329 }
2330 }
2331
2332 // If the typedef types are not identical, reject them in all languages and
2333 // with any extensions enabled.
2334 if (isIncompatibleTypedef(Old, New))
2335 return;
2336
2337 // The types match. Link up the redeclaration chain and merge attributes if
2338 // the old declaration was a typedef.
2339 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2340 New->setPreviousDecl(Typedef);
2341 mergeDeclAttributes(New, Old);
2342 }
2343
2344 if (getLangOpts().MicrosoftExt)
2345 return;
2346
2347 if (getLangOpts().CPlusPlus) {
2348 // C++ [dcl.typedef]p2:
2349 // In a given non-class scope, a typedef specifier can be used to
2350 // redefine the name of any type declared in that scope to refer
2351 // to the type to which it already refers.
2352 if (!isa<CXXRecordDecl>(CurContext))
2353 return;
2354
2355 // C++0x [dcl.typedef]p4:
2356 // In a given class scope, a typedef specifier can be used to redefine
2357 // any class-name declared in that scope that is not also a typedef-name
2358 // to refer to the type to which it already refers.
2359 //
2360 // This wording came in via DR424, which was a correction to the
2361 // wording in DR56, which accidentally banned code like:
2362 //
2363 // struct S {
2364 // typedef struct A { } A;
2365 // };
2366 //
2367 // in the C++03 standard. We implement the C++0x semantics, which
2368 // allow the above but disallow
2369 //
2370 // struct S {
2371 // typedef int I;
2372 // typedef int I;
2373 // };
2374 //
2375 // since that was the intent of DR56.
2376 if (!isa<TypedefNameDecl>(Old))
2377 return;
2378
2379 Diag(New->getLocation(), diag::err_redefinition)
2380 << New->getDeclName();
2381 notePreviousDefinition(Old, New->getLocation());
2382 return New->setInvalidDecl();
2383 }
2384
2385 // Modules always permit redefinition of typedefs, as does C11.
2386 if (getLangOpts().Modules || getLangOpts().C11)
2387 return;
2388
2389 // If we have a redefinition of a typedef in C, emit a warning. This warning
2390 // is normally mapped to an error, but can be controlled with
2391 // -Wtypedef-redefinition. If either the original or the redefinition is
2392 // in a system header, don't emit this for compatibility with GCC.
2393 if (getDiagnostics().getSuppressSystemWarnings() &&
2394 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2395 (Old->isImplicit() ||
2396 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2397 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2398 return;
2399
2400 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2401 << New->getDeclName();
2402 notePreviousDefinition(Old, New->getLocation());
2403}
2404
2405/// DeclhasAttr - returns true if decl Declaration already has the target
2406/// attribute.
2407static bool DeclHasAttr(const Decl *D, const Attr *A) {
2408 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2409 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2410 for (const auto *i : D->attrs())
2411 if (i->getKind() == A->getKind()) {
2412 if (Ann) {
2413 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2414 return true;
2415 continue;
2416 }
2417 // FIXME: Don't hardcode this check
2418 if (OA && isa<OwnershipAttr>(i))
2419 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2420 return true;
2421 }
2422
2423 return false;
2424}
2425
2426static bool isAttributeTargetADefinition(Decl *D) {
2427 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2428 return VD->isThisDeclarationADefinition();
2429 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2430 return TD->isCompleteDefinition() || TD->isBeingDefined();
2431 return true;
2432}
2433
2434/// Merge alignment attributes from \p Old to \p New, taking into account the
2435/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2436///
2437/// \return \c true if any attributes were added to \p New.
2438static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2439 // Look for alignas attributes on Old, and pick out whichever attribute
2440 // specifies the strictest alignment requirement.
2441 AlignedAttr *OldAlignasAttr = nullptr;
2442 AlignedAttr *OldStrictestAlignAttr = nullptr;
2443 unsigned OldAlign = 0;
2444 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2445 // FIXME: We have no way of representing inherited dependent alignments
2446 // in a case like:
2447 // template<int A, int B> struct alignas(A) X;
2448 // template<int A, int B> struct alignas(B) X {};
2449 // For now, we just ignore any alignas attributes which are not on the
2450 // definition in such a case.
2451 if (I->isAlignmentDependent())
2452 return false;
2453
2454 if (I->isAlignas())
2455 OldAlignasAttr = I;
2456
2457 unsigned Align = I->getAlignment(S.Context);
2458 if (Align > OldAlign) {
2459 OldAlign = Align;
2460 OldStrictestAlignAttr = I;
2461 }
2462 }
2463
2464 // Look for alignas attributes on New.
2465 AlignedAttr *NewAlignasAttr = nullptr;
2466 unsigned NewAlign = 0;
2467 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2468 if (I->isAlignmentDependent())
2469 return false;
2470
2471 if (I->isAlignas())
2472 NewAlignasAttr = I;
2473
2474 unsigned Align = I->getAlignment(S.Context);
2475 if (Align > NewAlign)
2476 NewAlign = Align;
2477 }
2478
2479 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2480 // Both declarations have 'alignas' attributes. We require them to match.
2481 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2482 // fall short. (If two declarations both have alignas, they must both match
2483 // every definition, and so must match each other if there is a definition.)
2484
2485 // If either declaration only contains 'alignas(0)' specifiers, then it
2486 // specifies the natural alignment for the type.
2487 if (OldAlign == 0 || NewAlign == 0) {
2488 QualType Ty;
2489 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2490 Ty = VD->getType();
2491 else
2492 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2493
2494 if (OldAlign == 0)
2495 OldAlign = S.Context.getTypeAlign(Ty);
2496 if (NewAlign == 0)
2497 NewAlign = S.Context.getTypeAlign(Ty);
2498 }
2499
2500 if (OldAlign != NewAlign) {
2501 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2502 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2503 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2504 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2505 }
2506 }
2507
2508 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2509 // C++11 [dcl.align]p6:
2510 // if any declaration of an entity has an alignment-specifier,
2511 // every defining declaration of that entity shall specify an
2512 // equivalent alignment.
2513 // C11 6.7.5/7:
2514 // If the definition of an object does not have an alignment
2515 // specifier, any other declaration of that object shall also
2516 // have no alignment specifier.
2517 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2518 << OldAlignasAttr;
2519 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2520 << OldAlignasAttr;
2521 }
2522
2523 bool AnyAdded = false;
2524
2525 // Ensure we have an attribute representing the strictest alignment.
2526 if (OldAlign > NewAlign) {
2527 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2528 Clone->setInherited(true);
2529 New->addAttr(Clone);
2530 AnyAdded = true;
2531 }
2532
2533 // Ensure we have an alignas attribute if the old declaration had one.
2534 if (OldAlignasAttr && !NewAlignasAttr &&
2535 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2536 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2537 Clone->setInherited(true);
2538 New->addAttr(Clone);
2539 AnyAdded = true;
2540 }
2541
2542 return AnyAdded;
2543}
2544
2545static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2546 const InheritableAttr *Attr,
2547 Sema::AvailabilityMergeKind AMK) {
2548 // This function copies an attribute Attr from a previous declaration to the
2549 // new declaration D if the new declaration doesn't itself have that attribute
2550 // yet or if that attribute allows duplicates.
2551 // If you're adding a new attribute that requires logic different from
2552 // "use explicit attribute on decl if present, else use attribute from
2553 // previous decl", for example if the attribute needs to be consistent
2554 // between redeclarations, you need to call a custom merge function here.
2555 InheritableAttr *NewAttr = nullptr;
2556 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2557 NewAttr = S.mergeAvailabilityAttr(
2558 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2559 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2560 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2561 AA->getPriority());
2562 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2563 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2564 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2565 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2566 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2567 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2568 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2569 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2570 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2571 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2572 FA->getFirstArg());
2573 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2574 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2575 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2576 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2577 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2578 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2579 IA->getInheritanceModel());
2580 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2581 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2582 &S.Context.Idents.get(AA->getSpelling()));
2583 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2584 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2585 isa<CUDAGlobalAttr>(Attr))) {
2586 // CUDA target attributes are part of function signature for
2587 // overloading purposes and must not be merged.
2588 return false;
2589 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2590 NewAttr = S.mergeMinSizeAttr(D, *MA);
2591 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2592 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2593 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2594 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2595 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2596 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2597 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2598 NewAttr = S.mergeCommonAttr(D, *CommonA);
2599 else if (isa<AlignedAttr>(Attr))
2600 // AlignedAttrs are handled separately, because we need to handle all
2601 // such attributes on a declaration at the same time.
2602 NewAttr = nullptr;
2603 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2604 (AMK == Sema::AMK_Override ||
2605 AMK == Sema::AMK_ProtocolImplementation))
2606 NewAttr = nullptr;
2607 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2608 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2609 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2610 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2611 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2612 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2613 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2614 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2615 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2616 NewAttr = S.mergeImportNameAttr(D, *INA);
2617 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2618 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2619
2620 if (NewAttr) {
2621 NewAttr->setInherited(true);
2622 D->addAttr(NewAttr);
2623 if (isa<MSInheritanceAttr>(NewAttr))
2624 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2625 return true;
2626 }
2627
2628 return false;
2629}
2630
2631static const NamedDecl *getDefinition(const Decl *D) {
2632 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2633 return TD->getDefinition();
2634 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2635 const VarDecl *Def = VD->getDefinition();
2636 if (Def)
2637 return Def;
2638 return VD->getActingDefinition();
2639 }
2640 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2641 const FunctionDecl *Def = nullptr;
2642 if (FD->isDefined(Def, true))
2643 return Def;
2644 }
2645 return nullptr;
2646}
2647
2648static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2649 for (const auto *Attribute : D->attrs())
2650 if (Attribute->getKind() == Kind)
2651 return true;
2652 return false;
2653}
2654
2655/// checkNewAttributesAfterDef - If we already have a definition, check that
2656/// there are no new attributes in this declaration.
2657static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2658 if (!New->hasAttrs())
2659 return;
2660
2661 const NamedDecl *Def = getDefinition(Old);
2662 if (!Def || Def == New)
2663 return;
2664
2665 AttrVec &NewAttributes = New->getAttrs();
2666 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2667 const Attr *NewAttribute = NewAttributes[I];
2668
2669 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2670 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2671 Sema::SkipBodyInfo SkipBody;
2672 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2673
2674 // If we're skipping this definition, drop the "alias" attribute.
2675 if (SkipBody.ShouldSkip) {
2676 NewAttributes.erase(NewAttributes.begin() + I);
2677 --E;
2678 continue;
2679 }
2680 } else {
2681 VarDecl *VD = cast<VarDecl>(New);
2682 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2683 VarDecl::TentativeDefinition
2684 ? diag::err_alias_after_tentative
2685 : diag::err_redefinition;
2686 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2687 if (Diag == diag::err_redefinition)
2688 S.notePreviousDefinition(Def, VD->getLocation());
2689 else
2690 S.Diag(Def->getLocation(), diag::note_previous_definition);
2691 VD->setInvalidDecl();
2692 }
2693 ++I;
2694 continue;
2695 }
2696
2697 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2698 // Tentative definitions are only interesting for the alias check above.
2699 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2700 ++I;
2701 continue;
2702 }
2703 }
2704
2705 if (hasAttribute(Def, NewAttribute->getKind())) {
2706 ++I;
2707 continue; // regular attr merging will take care of validating this.
2708 }
2709
2710 if (isa<C11NoReturnAttr>(NewAttribute)) {
2711 // C's _Noreturn is allowed to be added to a function after it is defined.
2712 ++I;
2713 continue;
2714 } else if (isa<UuidAttr>(NewAttribute)) {
2715 // msvc will allow a subsequent definition to add an uuid to a class
2716 ++I;
2717 continue;
2718 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2719 if (AA->isAlignas()) {
2720 // C++11 [dcl.align]p6:
2721 // if any declaration of an entity has an alignment-specifier,
2722 // every defining declaration of that entity shall specify an
2723 // equivalent alignment.
2724 // C11 6.7.5/7:
2725 // If the definition of an object does not have an alignment
2726 // specifier, any other declaration of that object shall also
2727 // have no alignment specifier.
2728 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2729 << AA;
2730 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2731 << AA;
2732 NewAttributes.erase(NewAttributes.begin() + I);
2733 --E;
2734 continue;
2735 }
2736 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2737 // If there is a C definition followed by a redeclaration with this
2738 // attribute then there are two different definitions. In C++, prefer the
2739 // standard diagnostics.
2740 if (!S.getLangOpts().CPlusPlus) {
2741 S.Diag(NewAttribute->getLocation(),
2742 diag::err_loader_uninitialized_redeclaration);
2743 S.Diag(Def->getLocation(), diag::note_previous_definition);
2744 NewAttributes.erase(NewAttributes.begin() + I);
2745 --E;
2746 continue;
2747 }
2748 } else if (isa<SelectAnyAttr>(NewAttribute) &&
2749 cast<VarDecl>(New)->isInline() &&
2750 !cast<VarDecl>(New)->isInlineSpecified()) {
2751 // Don't warn about applying selectany to implicitly inline variables.
2752 // Older compilers and language modes would require the use of selectany
2753 // to make such variables inline, and it would have no effect if we
2754 // honored it.
2755 ++I;
2756 continue;
2757 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2758 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2759 // declarations after defintions.
2760 ++I;
2761 continue;
2762 }
2763
2764 S.Diag(NewAttribute->getLocation(),
2765 diag::warn_attribute_precede_definition);
2766 S.Diag(Def->getLocation(), diag::note_previous_definition);
2767 NewAttributes.erase(NewAttributes.begin() + I);
2768 --E;
2769 }
2770}
2771
2772static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2773 const ConstInitAttr *CIAttr,
2774 bool AttrBeforeInit) {
2775 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2776
2777 // Figure out a good way to write this specifier on the old declaration.
2778 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2779 // enough of the attribute list spelling information to extract that without
2780 // heroics.
2781 std::string SuitableSpelling;
2782 if (S.getLangOpts().CPlusPlus20)
2783 SuitableSpelling = std::string(
2784 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2785 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2786 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2787 InsertLoc, {tok::l_square, tok::l_square,
2788 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2789 S.PP.getIdentifierInfo("require_constant_initialization"),
2790 tok::r_square, tok::r_square}));
2791 if (SuitableSpelling.empty())
2792 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2793 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2794 S.PP.getIdentifierInfo("require_constant_initialization"),
2795 tok::r_paren, tok::r_paren}));
2796 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2797 SuitableSpelling = "constinit";
2798 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2799 SuitableSpelling = "[[clang::require_constant_initialization]]";
2800 if (SuitableSpelling.empty())
2801 SuitableSpelling = "__attribute__((require_constant_initialization))";
2802 SuitableSpelling += " ";
2803
2804 if (AttrBeforeInit) {
2805 // extern constinit int a;
2806 // int a = 0; // error (missing 'constinit'), accepted as extension
2807 assert(CIAttr->isConstinit() && "should not diagnose this for attribute")((CIAttr->isConstinit() && "should not diagnose this for attribute"
) ? static_cast<void> (0) : __assert_fail ("CIAttr->isConstinit() && \"should not diagnose this for attribute\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 2807, __PRETTY_FUNCTION__))
;
2808 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2809 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2810 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2811 } else {
2812 // int a = 0;
2813 // constinit extern int a; // error (missing 'constinit')
2814 S.Diag(CIAttr->getLocation(),
2815 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2816 : diag::warn_require_const_init_added_too_late)
2817 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2818 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2819 << CIAttr->isConstinit()
2820 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2821 }
2822}
2823
2824/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2825void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2826 AvailabilityMergeKind AMK) {
2827 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2828 UsedAttr *NewAttr = OldAttr->clone(Context);
2829 NewAttr->setInherited(true);
2830 New->addAttr(NewAttr);
2831 }
2832
2833 if (!Old->hasAttrs() && !New->hasAttrs())
2834 return;
2835
2836 // [dcl.constinit]p1:
2837 // If the [constinit] specifier is applied to any declaration of a
2838 // variable, it shall be applied to the initializing declaration.
2839 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2840 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2841 if (bool(OldConstInit) != bool(NewConstInit)) {
2842 const auto *OldVD = cast<VarDecl>(Old);
2843 auto *NewVD = cast<VarDecl>(New);
2844
2845 // Find the initializing declaration. Note that we might not have linked
2846 // the new declaration into the redeclaration chain yet.
2847 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2848 if (!InitDecl &&
2849 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2850 InitDecl = NewVD;
2851
2852 if (InitDecl == NewVD) {
2853 // This is the initializing declaration. If it would inherit 'constinit',
2854 // that's ill-formed. (Note that we do not apply this to the attribute
2855 // form).
2856 if (OldConstInit && OldConstInit->isConstinit())
2857 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2858 /*AttrBeforeInit=*/true);
2859 } else if (NewConstInit) {
2860 // This is the first time we've been told that this declaration should
2861 // have a constant initializer. If we already saw the initializing
2862 // declaration, this is too late.
2863 if (InitDecl && InitDecl != NewVD) {
2864 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2865 /*AttrBeforeInit=*/false);
2866 NewVD->dropAttr<ConstInitAttr>();
2867 }
2868 }
2869 }
2870
2871 // Attributes declared post-definition are currently ignored.
2872 checkNewAttributesAfterDef(*this, New, Old);
2873
2874 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2875 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2876 if (!OldA->isEquivalent(NewA)) {
2877 // This redeclaration changes __asm__ label.
2878 Diag(New->getLocation(), diag::err_different_asm_label);
2879 Diag(OldA->getLocation(), diag::note_previous_declaration);
2880 }
2881 } else if (Old->isUsed()) {
2882 // This redeclaration adds an __asm__ label to a declaration that has
2883 // already been ODR-used.
2884 Diag(New->getLocation(), diag::err_late_asm_label_name)
2885 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2886 }
2887 }
2888
2889 // Re-declaration cannot add abi_tag's.
2890 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2891 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2892 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2893 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2894 NewTag) == OldAbiTagAttr->tags_end()) {
2895 Diag(NewAbiTagAttr->getLocation(),
2896 diag::err_new_abi_tag_on_redeclaration)
2897 << NewTag;
2898 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2899 }
2900 }
2901 } else {
2902 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2903 Diag(Old->getLocation(), diag::note_previous_declaration);
2904 }
2905 }
2906
2907 // This redeclaration adds a section attribute.
2908 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2909 if (auto *VD = dyn_cast<VarDecl>(New)) {
2910 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2911 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2912 Diag(Old->getLocation(), diag::note_previous_declaration);
2913 }
2914 }
2915 }
2916
2917 // Redeclaration adds code-seg attribute.
2918 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2919 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2920 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2921 Diag(New->getLocation(), diag::warn_mismatched_section)
2922 << 0 /*codeseg*/;
2923 Diag(Old->getLocation(), diag::note_previous_declaration);
2924 }
2925
2926 if (!Old->hasAttrs())
2927 return;
2928
2929 bool foundAny = New->hasAttrs();
2930
2931 // Ensure that any moving of objects within the allocated map is done before
2932 // we process them.
2933 if (!foundAny) New->setAttrs(AttrVec());
2934
2935 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2936 // Ignore deprecated/unavailable/availability attributes if requested.
2937 AvailabilityMergeKind LocalAMK = AMK_None;
2938 if (isa<DeprecatedAttr>(I) ||
2939 isa<UnavailableAttr>(I) ||
2940 isa<AvailabilityAttr>(I)) {
2941 switch (AMK) {
2942 case AMK_None:
2943 continue;
2944
2945 case AMK_Redeclaration:
2946 case AMK_Override:
2947 case AMK_ProtocolImplementation:
2948 LocalAMK = AMK;
2949 break;
2950 }
2951 }
2952
2953 // Already handled.
2954 if (isa<UsedAttr>(I))
2955 continue;
2956
2957 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2958 foundAny = true;
2959 }
2960
2961 if (mergeAlignedAttrs(*this, New, Old))
2962 foundAny = true;
2963
2964 if (!foundAny) New->dropAttrs();
2965}
2966
2967/// mergeParamDeclAttributes - Copy attributes from the old parameter
2968/// to the new one.
2969static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2970 const ParmVarDecl *oldDecl,
2971 Sema &S) {
2972 // C++11 [dcl.attr.depend]p2:
2973 // The first declaration of a function shall specify the
2974 // carries_dependency attribute for its declarator-id if any declaration
2975 // of the function specifies the carries_dependency attribute.
2976 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2977 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2978 S.Diag(CDA->getLocation(),
2979 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2980 // Find the first declaration of the parameter.
2981 // FIXME: Should we build redeclaration chains for function parameters?
2982 const FunctionDecl *FirstFD =
2983 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2984 const ParmVarDecl *FirstVD =
2985 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2986 S.Diag(FirstVD->getLocation(),
2987 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2988 }
2989
2990 if (!oldDecl->hasAttrs())
2991 return;
2992
2993 bool foundAny = newDecl->hasAttrs();
2994
2995 // Ensure that any moving of objects within the allocated map is
2996 // done before we process them.
2997 if (!foundAny) newDecl->setAttrs(AttrVec());
2998
2999 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3000 if (!DeclHasAttr(newDecl, I)) {
3001 InheritableAttr *newAttr =
3002 cast<InheritableParamAttr>(I->clone(S.Context));
3003 newAttr->setInherited(true);
3004 newDecl->addAttr(newAttr);
3005 foundAny = true;
3006 }
3007 }
3008
3009 if (!foundAny) newDecl->dropAttrs();
3010}
3011
3012static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3013 const ParmVarDecl *OldParam,
3014 Sema &S) {
3015 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3016 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3017 if (*Oldnullability != *Newnullability) {
3018 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3019 << DiagNullabilityKind(
3020 *Newnullability,
3021 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3022 != 0))
3023 << DiagNullabilityKind(
3024 *Oldnullability,
3025 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3026 != 0));
3027 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3028 }
3029 } else {
3030 QualType NewT = NewParam->getType();
3031 NewT = S.Context.getAttributedType(
3032 AttributedType::getNullabilityAttrKind(*Oldnullability),
3033 NewT, NewT);
3034 NewParam->setType(NewT);
3035 }
3036 }
3037}
3038
3039namespace {
3040
3041/// Used in MergeFunctionDecl to keep track of function parameters in
3042/// C.
3043struct GNUCompatibleParamWarning {
3044 ParmVarDecl *OldParm;
3045 ParmVarDecl *NewParm;
3046 QualType PromotedType;
3047};
3048
3049} // end anonymous namespace
3050
3051// Determine whether the previous declaration was a definition, implicit
3052// declaration, or a declaration.
3053template <typename T>
3054static std::pair<diag::kind, SourceLocation>
3055getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3056 diag::kind PrevDiag;
3057 SourceLocation OldLocation = Old->getLocation();
3058 if (Old->isThisDeclarationADefinition())
3059 PrevDiag = diag::note_previous_definition;
3060 else if (Old->isImplicit()) {
3061 PrevDiag = diag::note_previous_implicit_declaration;
3062 if (OldLocation.isInvalid())
3063 OldLocation = New->getLocation();
3064 } else
3065 PrevDiag = diag::note_previous_declaration;
3066 return std::make_pair(PrevDiag, OldLocation);
3067}
3068
3069/// canRedefineFunction - checks if a function can be redefined. Currently,
3070/// only extern inline functions can be redefined, and even then only in
3071/// GNU89 mode.
3072static bool canRedefineFunction(const FunctionDecl *FD,
3073 const LangOptions& LangOpts) {
3074 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3075 !LangOpts.CPlusPlus &&
3076 FD->isInlineSpecified() &&
3077 FD->getStorageClass() == SC_Extern);
3078}
3079
3080const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3081 const AttributedType *AT = T->getAs<AttributedType>();
3082 while (AT && !AT->isCallingConv())
3083 AT = AT->getModifiedType()->getAs<AttributedType>();
3084 return AT;
3085}
3086
3087template <typename T>
3088static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3089 const DeclContext *DC = Old->getDeclContext();
3090 if (DC->isRecord())
3091 return false;
3092
3093 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3094 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3095 return true;
3096 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3097 return true;
3098 return false;
3099}
3100
3101template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3102static bool isExternC(VarTemplateDecl *) { return false; }
3103
3104/// Check whether a redeclaration of an entity introduced by a
3105/// using-declaration is valid, given that we know it's not an overload
3106/// (nor a hidden tag declaration).
3107template<typename ExpectedDecl>
3108static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3109 ExpectedDecl *New) {
3110 // C++11 [basic.scope.declarative]p4:
3111 // Given a set of declarations in a single declarative region, each of
3112 // which specifies the same unqualified name,
3113 // -- they shall all refer to the same entity, or all refer to functions
3114 // and function templates; or
3115 // -- exactly one declaration shall declare a class name or enumeration
3116 // name that is not a typedef name and the other declarations shall all
3117 // refer to the same variable or enumerator, or all refer to functions
3118 // and function templates; in this case the class name or enumeration
3119 // name is hidden (3.3.10).
3120
3121 // C++11 [namespace.udecl]p14:
3122 // If a function declaration in namespace scope or block scope has the
3123 // same name and the same parameter-type-list as a function introduced
3124 // by a using-declaration, and the declarations do not declare the same
3125 // function, the program is ill-formed.
3126
3127 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3128 if (Old &&
3129 !Old->getDeclContext()->getRedeclContext()->Equals(
3130 New->getDeclContext()->getRedeclContext()) &&
3131 !(isExternC(Old) && isExternC(New)))
3132 Old = nullptr;
3133
3134 if (!Old) {
3135 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3136 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3137 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3138 return true;
3139 }
3140 return false;
3141}
3142
3143static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3144 const FunctionDecl *B) {
3145 assert(A->getNumParams() == B->getNumParams())((A->getNumParams() == B->getNumParams()) ? static_cast
<void> (0) : __assert_fail ("A->getNumParams() == B->getNumParams()"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 3145, __PRETTY_FUNCTION__))
;
3146
3147 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3148 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3149 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3150 if (AttrA == AttrB)
3151 return true;
3152 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3153 AttrA->isDynamic() == AttrB->isDynamic();
3154 };
3155
3156 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3157}
3158
3159/// If necessary, adjust the semantic declaration context for a qualified
3160/// declaration to name the correct inline namespace within the qualifier.
3161static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3162 DeclaratorDecl *OldD) {
3163 // The only case where we need to update the DeclContext is when
3164 // redeclaration lookup for a qualified name finds a declaration
3165 // in an inline namespace within the context named by the qualifier:
3166 //
3167 // inline namespace N { int f(); }
3168 // int ::f(); // Sema DC needs adjusting from :: to N::.
3169 //
3170 // For unqualified declarations, the semantic context *can* change
3171 // along the redeclaration chain (for local extern declarations,
3172 // extern "C" declarations, and friend declarations in particular).
3173 if (!NewD->getQualifier())
3174 return;
3175
3176 // NewD is probably already in the right context.
3177 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3178 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3179 if (NamedDC->Equals(SemaDC))
3180 return;
3181
3182 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->
isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration"
) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 3184, __PRETTY_FUNCTION__))
3183 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->
isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration"
) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 3184, __PRETTY_FUNCTION__))
3184 "unexpected context for redeclaration")(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->
isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration"
) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 3184, __PRETTY_FUNCTION__))
;
3185
3186 auto *LexDC = NewD->getLexicalDeclContext();
3187 auto FixSemaDC = [=](NamedDecl *D) {
3188 if (!D)
3189 return;
3190 D->setDeclContext(SemaDC);
3191 D->setLexicalDeclContext(LexDC);
3192 };
3193
3194 FixSemaDC(NewD);
3195 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3196 FixSemaDC(FD->getDescribedFunctionTemplate());
3197 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3198 FixSemaDC(VD->getDescribedVarTemplate());
3199}
3200
3201/// MergeFunctionDecl - We just parsed a function 'New' from
3202/// declarator D which has the same name and scope as a previous
3203/// declaration 'Old'. Figure out how to resolve this situation,
3204/// merging decls or emitting diagnostics as appropriate.
3205///
3206/// In C++, New and Old must be declarations that are not
3207/// overloaded. Use IsOverload to determine whether New and Old are
3208/// overloaded, and to select the Old declaration that New should be
3209/// merged with.
3210///
3211/// Returns true if there was an error, false otherwise.
3212bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3213 Scope *S, bool MergeTypeWithOld) {
3214 // Verify the old decl was also a function.
3215 FunctionDecl *Old = OldD->getAsFunction();
3216 if (!Old) {
3217 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3218 if (New->getFriendObjectKind()) {
3219 Diag(New->getLocation(), diag::err_using_decl_friend);
3220 Diag(Shadow->getTargetDecl()->getLocation(),
3221 diag::note_using_decl_target);
3222 Diag(Shadow->getUsingDecl()->getLocation(),
3223 diag::note_using_decl) << 0;
3224 return true;
3225 }
3226
3227 // Check whether the two declarations might declare the same function.
3228 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3229 return true;
3230 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3231 } else {
3232 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3233 << New->getDeclName();
3234 notePreviousDefinition(OldD, New->getLocation());
3235 return true;
3236 }
3237 }
3238
3239 // If the old declaration is invalid, just give up here.
3240 if (Old->isInvalidDecl())
3241 return true;
3242
3243 // Disallow redeclaration of some builtins.
3244 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3245 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3246 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3247 << Old << Old->getType();
3248 return true;
3249 }
3250
3251 diag::kind PrevDiag;
3252 SourceLocation OldLocation;
3253 std::tie(PrevDiag, OldLocation) =
3254 getNoteDiagForInvalidRedeclaration(Old, New);
3255
3256 // Don't complain about this if we're in GNU89 mode and the old function
3257 // is an extern inline function.
3258 // Don't complain about specializations. They are not supposed to have
3259 // storage classes.
3260 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3261 New->getStorageClass() == SC_Static &&
3262 Old->hasExternalFormalLinkage() &&
3263 !New->getTemplateSpecializationInfo() &&
3264 !canRedefineFunction(Old, getLangOpts())) {
3265 if (getLangOpts().MicrosoftExt) {
3266 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3267 Diag(OldLocation, PrevDiag);
3268 } else {
3269 Diag(New->getLocation(), diag::err_static_non_static) << New;
3270 Diag(OldLocation, PrevDiag);
3271 return true;
3272 }
3273 }
3274
3275 if (New->hasAttr<InternalLinkageAttr>() &&
3276 !Old->hasAttr<InternalLinkageAttr>()) {
3277 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3278 << New->getDeclName();
3279 notePreviousDefinition(Old, New->getLocation());
3280 New->dropAttr<InternalLinkageAttr>();
3281 }
3282
3283 if (CheckRedeclarationModuleOwnership(New, Old))
3284 return true;
3285
3286 if (!getLangOpts().CPlusPlus) {
3287 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3288 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3289 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3290 << New << OldOvl;
3291
3292 // Try our best to find a decl that actually has the overloadable
3293 // attribute for the note. In most cases (e.g. programs with only one
3294 // broken declaration/definition), this won't matter.
3295 //
3296 // FIXME: We could do this if we juggled some extra state in
3297 // OverloadableAttr, rather than just removing it.
3298 const Decl *DiagOld = Old;
3299 if (OldOvl) {
3300 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3301 const auto *A = D->getAttr<OverloadableAttr>();
3302 return A && !A->isImplicit();
3303 });
3304 // If we've implicitly added *all* of the overloadable attrs to this
3305 // chain, emitting a "previous redecl" note is pointless.
3306 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3307 }
3308
3309 if (DiagOld)
3310 Diag(DiagOld->getLocation(),
3311 diag::note_attribute_overloadable_prev_overload)
3312 << OldOvl;
3313
3314 if (OldOvl)
3315 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3316 else
3317 New->dropAttr<OverloadableAttr>();
3318 }
3319 }
3320
3321 // If a function is first declared with a calling convention, but is later
3322 // declared or defined without one, all following decls assume the calling
3323 // convention of the first.
3324 //
3325 // It's OK if a function is first declared without a calling convention,
3326 // but is later declared or defined with the default calling convention.
3327 //
3328 // To test if either decl has an explicit calling convention, we look for
3329 // AttributedType sugar nodes on the type as written. If they are missing or
3330 // were canonicalized away, we assume the calling convention was implicit.
3331 //
3332 // Note also that we DO NOT return at this point, because we still have
3333 // other tests to run.
3334 QualType OldQType = Context.getCanonicalType(Old->getType());
3335 QualType NewQType = Context.getCanonicalType(New->getType());
3336 const FunctionType *OldType = cast<FunctionType>(OldQType);
3337 const FunctionType *NewType = cast<FunctionType>(NewQType);
3338 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3339 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3340 bool RequiresAdjustment = false;
3341
3342 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3343 FunctionDecl *First = Old->getFirstDecl();
3344 const FunctionType *FT =
3345 First->getType().getCanonicalType()->castAs<FunctionType>();
3346 FunctionType::ExtInfo FI = FT->getExtInfo();
3347 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3348 if (!NewCCExplicit) {
3349 // Inherit the CC from the previous declaration if it was specified
3350 // there but not here.
3351 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3352 RequiresAdjustment = true;
3353 } else if (Old->getBuiltinID()) {
3354 // Builtin attribute isn't propagated to the new one yet at this point,
3355 // so we check if the old one is a builtin.
3356
3357 // Calling Conventions on a Builtin aren't really useful and setting a
3358 // default calling convention and cdecl'ing some builtin redeclarations is
3359 // common, so warn and ignore the calling convention on the redeclaration.
3360 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3361 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3362 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3363 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3364 RequiresAdjustment = true;
3365 } else {
3366 // Calling conventions aren't compatible, so complain.
3367 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3368 Diag(New->getLocation(), diag::err_cconv_change)
3369 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3370 << !FirstCCExplicit
3371 << (!FirstCCExplicit ? "" :
3372 FunctionType::getNameForCallConv(FI.getCC()));
3373
3374 // Put the note on the first decl, since it is the one that matters.
3375 Diag(First->getLocation(), diag::note_previous_declaration);
3376 return true;
3377 }
3378 }
3379
3380 // FIXME: diagnose the other way around?
3381 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3382 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3383 RequiresAdjustment = true;
3384 }
3385
3386 // Merge regparm attribute.
3387 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3388 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3389 if (NewTypeInfo.getHasRegParm()) {
3390 Diag(New->getLocation(), diag::err_regparm_mismatch)
3391 << NewType->getRegParmType()
3392 << OldType->getRegParmType();
3393 Diag(OldLocation, diag::note_previous_declaration);
3394 return true;
3395 }
3396
3397 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3398 RequiresAdjustment = true;
3399 }
3400
3401 // Merge ns_returns_retained attribute.
3402 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3403 if (NewTypeInfo.getProducesResult()) {
3404 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3405 << "'ns_returns_retained'";
3406 Diag(OldLocation, diag::note_previous_declaration);
3407 return true;
3408 }
3409
3410 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3411 RequiresAdjustment = true;
3412 }
3413
3414 if (OldTypeInfo.getNoCallerSavedRegs() !=
3415 NewTypeInfo.getNoCallerSavedRegs()) {
3416 if (NewTypeInfo.getNoCallerSavedRegs()) {
3417 AnyX86NoCallerSavedRegistersAttr *Attr =
3418 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3419 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3420 Diag(OldLocation, diag::note_previous_declaration);
3421 return true;
3422 }
3423
3424 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3425 RequiresAdjustment = true;
3426 }
3427
3428 if (RequiresAdjustment) {
3429 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3430 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3431 New->setType(QualType(AdjustedType, 0));
3432 NewQType = Context.getCanonicalType(New->getType());
3433 }
3434
3435 // If this redeclaration makes the function inline, we may need to add it to
3436 // UndefinedButUsed.
3437 if (!Old->isInlined() && New->isInlined() &&
3438 !New->hasAttr<GNUInlineAttr>() &&
3439 !getLangOpts().GNUInline &&
3440 Old->isUsed(false) &&
3441 !Old->isDefined() && !New->isThisDeclarationADefinition())
3442 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3443 SourceLocation()));
3444
3445 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3446 // about it.
3447 if (New->hasAttr<GNUInlineAttr>() &&
3448 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3449 UndefinedButUsed.erase(Old->getCanonicalDecl());
3450 }
3451
3452 // If pass_object_size params don't match up perfectly, this isn't a valid
3453 // redeclaration.
3454 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3455 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3456 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3457 << New->getDeclName();
3458 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3459 return true;
3460 }
3461
3462 if (getLangOpts().CPlusPlus) {
3463 // C++1z [over.load]p2
3464 // Certain function declarations cannot be overloaded:
3465 // -- Function declarations that differ only in the return type,
3466 // the exception specification, or both cannot be overloaded.
3467
3468 // Check the exception specifications match. This may recompute the type of
3469 // both Old and New if it resolved exception specifications, so grab the
3470 // types again after this. Because this updates the type, we do this before
3471 // any of the other checks below, which may update the "de facto" NewQType
3472 // but do not necessarily update the type of New.
3473 if (CheckEquivalentExceptionSpec(Old, New))
3474 return true;
3475 OldQType = Context.getCanonicalType(Old->getType());
3476 NewQType = Context.getCanonicalType(New->getType());
3477
3478 // Go back to the type source info to compare the declared return types,
3479 // per C++1y [dcl.type.auto]p13:
3480 // Redeclarations or specializations of a function or function template
3481 // with a declared return type that uses a placeholder type shall also
3482 // use that placeholder, not a deduced type.
3483 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3484 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3485 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3486 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3487 OldDeclaredReturnType)) {
3488 QualType ResQT;
3489 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3490 OldDeclaredReturnType->isObjCObjectPointerType())
3491 // FIXME: This does the wrong thing for a deduced return type.
3492 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3493 if (ResQT.isNull()) {
3494 if (New->isCXXClassMember() && New->isOutOfLine())
3495 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3496 << New << New->getReturnTypeSourceRange();
3497 else
3498 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3499 << New->getReturnTypeSourceRange();
3500 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3501 << Old->getReturnTypeSourceRange();
3502 return true;
3503 }
3504 else
3505 NewQType = ResQT;
3506 }
3507
3508 QualType OldReturnType = OldType->getReturnType();
3509 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3510 if (OldReturnType != NewReturnType) {
3511 // If this function has a deduced return type and has already been
3512 // defined, copy the deduced value from the old declaration.
3513 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3514 if (OldAT && OldAT->isDeduced()) {
3515 New->setType(
3516 SubstAutoType(New->getType(),
3517 OldAT->isDependentType() ? Context.DependentTy
3518 : OldAT->getDeducedType()));
3519 NewQType = Context.getCanonicalType(
3520 SubstAutoType(NewQType,
3521 OldAT->isDependentType() ? Context.DependentTy
3522 : OldAT->getDeducedType()));
3523 }
3524 }
3525
3526 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3527 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3528 if (OldMethod && NewMethod) {
3529 // Preserve triviality.
3530 NewMethod->setTrivial(OldMethod->isTrivial());
3531
3532 // MSVC allows explicit template specialization at class scope:
3533 // 2 CXXMethodDecls referring to the same function will be injected.
3534 // We don't want a redeclaration error.
3535 bool IsClassScopeExplicitSpecialization =
3536 OldMethod->isFunctionTemplateSpecialization() &&
3537 NewMethod->isFunctionTemplateSpecialization();
3538 bool isFriend = NewMethod->getFriendObjectKind();
3539
3540 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3541 !IsClassScopeExplicitSpecialization) {
3542 // -- Member function declarations with the same name and the
3543 // same parameter types cannot be overloaded if any of them
3544 // is a static member function declaration.
3545 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3546 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3547 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3548 return true;
3549 }
3550
3551 // C++ [class.mem]p1:
3552 // [...] A member shall not be declared twice in the
3553 // member-specification, except that a nested class or member
3554 // class template can be declared and then later defined.
3555 if (!inTemplateInstantiation()) {
3556 unsigned NewDiag;
3557 if (isa<CXXConstructorDecl>(OldMethod))
3558 NewDiag = diag::err_constructor_redeclared;
3559 else if (isa<CXXDestructorDecl>(NewMethod))
3560 NewDiag = diag::err_destructor_redeclared;
3561 else if (isa<CXXConversionDecl>(NewMethod))
3562 NewDiag = diag::err_conv_function_redeclared;
3563 else
3564 NewDiag = diag::err_member_redeclared;
3565
3566 Diag(New->getLocation(), NewDiag);
3567 } else {
3568 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3569 << New << New->getType();
3570 }
3571 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3572 return true;
3573
3574 // Complain if this is an explicit declaration of a special
3575 // member that was initially declared implicitly.
3576 //
3577 // As an exception, it's okay to befriend such methods in order
3578 // to permit the implicit constructor/destructor/operator calls.
3579 } else if (OldMethod->isImplicit()) {
3580 if (isFriend) {
3581 NewMethod->setImplicit();
3582 } else {
3583 Diag(NewMethod->getLocation(),
3584 diag::err_definition_of_implicitly_declared_member)
3585 << New << getSpecialMember(OldMethod);
3586 return true;
3587 }
3588 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3589 Diag(NewMethod->getLocation(),
3590 diag::err_definition_of_explicitly_defaulted_member)
3591 << getSpecialMember(OldMethod);
3592 return true;
3593 }
3594 }
3595
3596 // C++11 [dcl.attr.noreturn]p1:
3597 // The first declaration of a function shall specify the noreturn
3598 // attribute if any declaration of that function specifies the noreturn
3599 // attribute.
3600 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3601 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3602 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3603 Diag(Old->getFirstDecl()->getLocation(),
3604 diag::note_noreturn_missing_first_decl);
3605 }
3606
3607 // C++11 [dcl.attr.depend]p2:
3608 // The first declaration of a function shall specify the
3609 // carries_dependency attribute for its declarator-id if any declaration
3610 // of the function specifies the carries_dependency attribute.
3611 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3612 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3613 Diag(CDA->getLocation(),
3614 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3615 Diag(Old->getFirstDecl()->getLocation(),
3616 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3617 }
3618
3619 // (C++98 8.3.5p3):
3620 // All declarations for a function shall agree exactly in both the
3621 // return type and the parameter-type-list.
3622 // We also want to respect all the extended bits except noreturn.
3623
3624 // noreturn should now match unless the old type info didn't have it.
3625 QualType OldQTypeForComparison = OldQType;
3626 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3627 auto *OldType = OldQType->castAs<FunctionProtoType>();
3628 const FunctionType *OldTypeForComparison
3629 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3630 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3631 assert(OldQTypeForComparison.isCanonical())((OldQTypeForComparison.isCanonical()) ? static_cast<void>
(0) : __assert_fail ("OldQTypeForComparison.isCanonical()", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 3631, __PRETTY_FUNCTION__))
;
3632 }
3633
3634 if (haveIncompatibleLanguageLinkages(Old, New)) {
3635 // As a special case, retain the language linkage from previous
3636 // declarations of a friend function as an extension.
3637 //
3638 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3639 // and is useful because there's otherwise no way to specify language
3640 // linkage within class scope.
3641 //
3642 // Check cautiously as the friend object kind isn't yet complete.
3643 if (New->getFriendObjectKind() != Decl::FOK_None) {
3644 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3645 Diag(OldLocation, PrevDiag);
3646 } else {
3647 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3648 Diag(OldLocation, PrevDiag);
3649 return true;
3650 }
3651 }
3652
3653 // If the function types are compatible, merge the declarations. Ignore the
3654 // exception specifier because it was already checked above in
3655 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3656 // about incompatible types under -fms-compatibility.
3657 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3658 NewQType))
3659 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3660
3661 // If the types are imprecise (due to dependent constructs in friends or
3662 // local extern declarations), it's OK if they differ. We'll check again
3663 // during instantiation.
3664 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3665 return false;
3666
3667 // Fall through for conflicting redeclarations and redefinitions.
3668 }
3669
3670 // C: Function types need to be compatible, not identical. This handles
3671 // duplicate function decls like "void f(int); void f(enum X);" properly.
3672 if (!getLangOpts().CPlusPlus &&
3673 Context.typesAreCompatible(OldQType, NewQType)) {
3674 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3675 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3676 const FunctionProtoType *OldProto = nullptr;
3677 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3678 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3679 // The old declaration provided a function prototype, but the
3680 // new declaration does not. Merge in the prototype.
3681 assert(!OldProto->hasExceptionSpec() && "Exception spec in C")((!OldProto->hasExceptionSpec() && "Exception spec in C"
) ? static_cast<void> (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 3681, __PRETTY_FUNCTION__))
;
3682 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3683 NewQType =
3684 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3685 OldProto->getExtProtoInfo());
3686 New->setType(NewQType);
3687 New->setHasInheritedPrototype();
3688
3689 // Synthesize parameters with the same types.
3690 SmallVector<ParmVarDecl*, 16> Params;
3691 for (const auto &ParamType : OldProto->param_types()) {
3692 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3693 SourceLocation(), nullptr,
3694 ParamType, /*TInfo=*/nullptr,
3695 SC_None, nullptr);
3696 Param->setScopeInfo(0, Params.size());
3697 Param->setImplicit();
3698 Params.push_back(Param);
3699 }
3700
3701 New->setParams(Params);
3702 }
3703
3704 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3705 }
3706
3707 // Check if the function types are compatible when pointer size address
3708 // spaces are ignored.
3709 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3710 return false;
3711
3712 // GNU C permits a K&R definition to follow a prototype declaration
3713 // if the declared types of the parameters in the K&R definition
3714 // match the types in the prototype declaration, even when the
3715 // promoted types of the parameters from the K&R definition differ
3716 // from the types in the prototype. GCC then keeps the types from
3717 // the prototype.
3718 //
3719 // If a variadic prototype is followed by a non-variadic K&R definition,
3720 // the K&R definition becomes variadic. This is sort of an edge case, but
3721 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3722 // C99 6.9.1p8.
3723 if (!getLangOpts().CPlusPlus &&
3724 Old->hasPrototype() && !New->hasPrototype() &&
3725 New->getType()->getAs<FunctionProtoType>() &&
3726 Old->getNumParams() == New->getNumParams()) {
3727 SmallVector<QualType, 16> ArgTypes;
3728 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3729 const FunctionProtoType *OldProto
3730 = Old->getType()->getAs<FunctionProtoType>();
3731 const FunctionProtoType *NewProto
3732 = New->getType()->getAs<FunctionProtoType>();
3733
3734 // Determine whether this is the GNU C extension.
3735 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3736 NewProto->getReturnType());
3737 bool LooseCompatible = !MergedReturn.isNull();
3738 for (unsigned Idx = 0, End = Old->getNumParams();
3739 LooseCompatible && Idx != End; ++Idx) {
3740 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3741 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3742 if (Context.typesAreCompatible(OldParm->getType(),
3743 NewProto->getParamType(Idx))) {
3744 ArgTypes.push_back(NewParm->getType());
3745 } else if (Context.typesAreCompatible(OldParm->getType(),
3746 NewParm->getType(),
3747 /*CompareUnqualified=*/true)) {
3748 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3749 NewProto->getParamType(Idx) };
3750 Warnings.push_back(Warn);
3751 ArgTypes.push_back(NewParm->getType());
3752 } else
3753 LooseCompatible = false;
3754 }
3755
3756 if (LooseCompatible) {
3757 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3758 Diag(Warnings[Warn].NewParm->getLocation(),
3759 diag::ext_param_promoted_not_compatible_with_prototype)
3760 << Warnings[Warn].PromotedType
3761 << Warnings[Warn].OldParm->getType();
3762 if (Warnings[Warn].OldParm->getLocation().isValid())
3763 Diag(Warnings[Warn].OldParm->getLocation(),
3764 diag::note_previous_declaration);
3765 }
3766
3767 if (MergeTypeWithOld)
3768 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3769 OldProto->getExtProtoInfo()));
3770 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3771 }
3772
3773 // Fall through to diagnose conflicting types.
3774 }
3775
3776 // A function that has already been declared has been redeclared or
3777 // defined with a different type; show an appropriate diagnostic.
3778
3779 // If the previous declaration was an implicitly-generated builtin
3780 // declaration, then at the very least we should use a specialized note.
3781 unsigned BuiltinID;
3782 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3783 // If it's actually a library-defined builtin function like 'malloc'
3784 // or 'printf', just warn about the incompatible redeclaration.
3785 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3786 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3787 Diag(OldLocation, diag::note_previous_builtin_declaration)
3788 << Old << Old->getType();
3789 return false;
3790 }
3791
3792 PrevDiag = diag::note_previous_builtin_declaration;
3793 }
3794
3795 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3796 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3797 return true;
3798}
3799
3800/// Completes the merge of two function declarations that are
3801/// known to be compatible.
3802///
3803/// This routine handles the merging of attributes and other
3804/// properties of function declarations from the old declaration to
3805/// the new declaration, once we know that New is in fact a
3806/// redeclaration of Old.
3807///
3808/// \returns false
3809bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3810 Scope *S, bool MergeTypeWithOld) {
3811 // Merge the attributes
3812 mergeDeclAttributes(New, Old);
3813
3814 // Merge "pure" flag.
3815 if (Old->isPure())
3816 New->setPure();
3817
3818 // Merge "used" flag.
3819 if (Old->getMostRecentDecl()->isUsed(false))
3820 New->setIsUsed();
3821
3822 // Merge attributes from the parameters. These can mismatch with K&R
3823 // declarations.
3824 if (New->getNumParams() == Old->getNumParams())
3825 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3826 ParmVarDecl *NewParam = New->getParamDecl(i);
3827 ParmVarDecl *OldParam = Old->getParamDecl(i);
3828 mergeParamDeclAttributes(NewParam, OldParam, *this);
3829 mergeParamDeclTypes(NewParam, OldParam, *this);
3830 }
3831
3832 if (getLangOpts().CPlusPlus)
3833 return MergeCXXFunctionDecl(New, Old, S);
3834
3835 // Merge the function types so the we get the composite types for the return
3836 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3837 // was visible.
3838 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3839 if (!Merged.isNull() && MergeTypeWithOld)
3840 New->setType(Merged);
3841
3842 return false;
3843}
3844
3845void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3846 ObjCMethodDecl *oldMethod) {
3847 // Merge the attributes, including deprecated/unavailable
3848 AvailabilityMergeKind MergeKind =
3849 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3850 ? AMK_ProtocolImplementation
3851 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3852 : AMK_Override;
3853
3854 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3855
3856 // Merge attributes from the parameters.
3857 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3858 oe = oldMethod->param_end();
3859 for (ObjCMethodDecl::param_iterator
3860 ni = newMethod->param_begin(), ne = newMethod->param_end();
3861 ni != ne && oi != oe; ++ni, ++oi)
3862 mergeParamDeclAttributes(*ni, *oi, *this);
3863
3864 CheckObjCMethodOverride(newMethod, oldMethod);
3865}
3866
3867static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3868 assert(!S.Context.hasSameType(New->getType(), Old->getType()))((!S.Context.hasSameType(New->getType(), Old->getType()
)) ? static_cast<void> (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 3868, __PRETTY_FUNCTION__))
;
3869
3870 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3871 ? diag::err_redefinition_different_type
3872 : diag::err_redeclaration_different_type)
3873 << New->getDeclName() << New->getType() << Old->getType();
3874
3875 diag::kind PrevDiag;
3876 SourceLocation OldLocation;
3877 std::tie(PrevDiag, OldLocation)
3878 = getNoteDiagForInvalidRedeclaration(Old, New);
3879 S.Diag(OldLocation, PrevDiag);
3880 New->setInvalidDecl();
3881}
3882
3883/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3884/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3885/// emitting diagnostics as appropriate.
3886///
3887/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3888/// to here in AddInitializerToDecl. We can't check them before the initializer
3889/// is attached.
3890void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3891 bool MergeTypeWithOld) {
3892 if (New->isInvalidDecl() || Old->isInvalidDecl())
3893 return;
3894
3895 QualType MergedT;
3896 if (getLangOpts().CPlusPlus) {
3897 if (New->getType()->isUndeducedType()) {
3898 // We don't know what the new type is until the initializer is attached.
3899 return;
3900 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3901 // These could still be something that needs exception specs checked.
3902 return MergeVarDeclExceptionSpecs(New, Old);
3903 }
3904 // C++ [basic.link]p10:
3905 // [...] the types specified by all declarations referring to a given
3906 // object or function shall be identical, except that declarations for an
3907 // array object can specify array types that differ by the presence or
3908 // absence of a major array bound (8.3.4).
3909 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3910 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3911 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3912
3913 // We are merging a variable declaration New into Old. If it has an array
3914 // bound, and that bound differs from Old's bound, we should diagnose the
3915 // mismatch.
3916 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3917 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3918 PrevVD = PrevVD->getPreviousDecl()) {
3919 QualType PrevVDTy = PrevVD->getType();
3920 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3921 continue;
3922
3923 if (!Context.hasSameType(New->getType(), PrevVDTy))
3924 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3925 }
3926 }
3927
3928 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3929 if (Context.hasSameType(OldArray->getElementType(),
3930 NewArray->getElementType()))
3931 MergedT = New->getType();
3932 }
3933 // FIXME: Check visibility. New is hidden but has a complete type. If New
3934 // has no array bound, it should not inherit one from Old, if Old is not
3935 // visible.
3936 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3937 if (Context.hasSameType(OldArray->getElementType(),
3938 NewArray->getElementType()))
3939 MergedT = Old->getType();
3940 }
3941 }
3942 else if (New->getType()->isObjCObjectPointerType() &&
3943 Old->getType()->isObjCObjectPointerType()) {
3944 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3945 Old->getType());
3946 }
3947 } else {
3948 // C 6.2.7p2:
3949 // All declarations that refer to the same object or function shall have
3950 // compatible type.
3951 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3952 }
3953 if (MergedT.isNull()) {
3954 // It's OK if we couldn't merge types if either type is dependent, for a
3955 // block-scope variable. In other cases (static data members of class
3956 // templates, variable templates, ...), we require the types to be
3957 // equivalent.
3958 // FIXME: The C++ standard doesn't say anything about this.
3959 if ((New->getType()->isDependentType() ||
3960 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3961 // If the old type was dependent, we can't merge with it, so the new type
3962 // becomes dependent for now. We'll reproduce the original type when we
3963 // instantiate the TypeSourceInfo for the variable.
3964 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3965 New->setType(Context.DependentTy);
3966 return;
3967 }
3968 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3969 }
3970
3971 // Don't actually update the type on the new declaration if the old
3972 // declaration was an extern declaration in a different scope.
3973 if (MergeTypeWithOld)
3974 New->setType(MergedT);
3975}
3976
3977static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3978 LookupResult &Previous) {
3979 // C11 6.2.7p4:
3980 // For an identifier with internal or external linkage declared
3981 // in a scope in which a prior declaration of that identifier is
3982 // visible, if the prior declaration specifies internal or
3983 // external linkage, the type of the identifier at the later
3984 // declaration becomes the composite type.
3985 //
3986 // If the variable isn't visible, we do not merge with its type.
3987 if (Previous.isShadowed())
3988 return false;
3989
3990 if (S.getLangOpts().CPlusPlus) {
3991 // C++11 [dcl.array]p3:
3992 // If there is a preceding declaration of the entity in the same
3993 // scope in which the bound was specified, an omitted array bound
3994 // is taken to be the same as in that earlier declaration.
3995 return NewVD->isPreviousDeclInSameBlockScope() ||
3996 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3997 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3998 } else {
3999 // If the old declaration was function-local, don't merge with its
4000 // type unless we're in the same function.
4001 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4002 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4003 }
4004}
4005
4006/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4007/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4008/// situation, merging decls or emitting diagnostics as appropriate.
4009///
4010/// Tentative definition rules (C99 6.9.2p2) are checked by
4011/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4012/// definitions here, since the initializer hasn't been attached.
4013///
4014void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4015 // If the new decl is already invalid, don't do any other checking.
4016 if (New->isInvalidDecl())
4017 return;
4018
4019 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4020 return;
4021
4022 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4023
4024 // Verify the old decl was also a variable or variable template.
4025 VarDecl *Old = nullptr;
4026 VarTemplateDecl *OldTemplate = nullptr;
4027 if (Previous.isSingleResult()) {
4028 if (NewTemplate) {
4029 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4030 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4031
4032 if (auto *Shadow =
4033 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4034 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4035 return New->setInvalidDecl();
4036 } else {
4037 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4038
4039 if (auto *Shadow =
4040 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4041 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4042 return New->setInvalidDecl();
4043 }
4044 }
4045 if (!Old) {
4046 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4047 << New->getDeclName();
4048 notePreviousDefinition(Previous.getRepresentativeDecl(),
4049 New->getLocation());
4050 return New->setInvalidDecl();
4051 }
4052
4053 // Ensure the template parameters are compatible.
4054 if (NewTemplate &&
4055 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4056 OldTemplate->getTemplateParameters(),
4057 /*Complain=*/true, TPL_TemplateMatch))
4058 return New->setInvalidDecl();
4059
4060 // C++ [class.mem]p1:
4061 // A member shall not be declared twice in the member-specification [...]
4062 //
4063 // Here, we need only consider static data members.
4064 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4065 Diag(New->getLocation(), diag::err_duplicate_member)
4066 << New->getIdentifier();
4067 Diag(Old->getLocation(), diag::note_previous_declaration);
4068 New->setInvalidDecl();
4069 }
4070
4071 mergeDeclAttributes(New, Old);
4072 // Warn if an already-declared variable is made a weak_import in a subsequent
4073 // declaration
4074 if (New->hasAttr<WeakImportAttr>() &&
4075 Old->getStorageClass() == SC_None &&
4076 !Old->hasAttr<WeakImportAttr>()) {
4077 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4078 notePreviousDefinition(Old, New->getLocation());
4079 // Remove weak_import attribute on new declaration.
4080 New->dropAttr<WeakImportAttr>();
4081 }
4082
4083 if (New->hasAttr<InternalLinkageAttr>() &&
4084 !Old->hasAttr<InternalLinkageAttr>()) {
4085 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4086 << New->getDeclName();
4087 notePreviousDefinition(Old, New->getLocation());
4088 New->dropAttr<InternalLinkageAttr>();
4089 }
4090
4091 // Merge the types.
4092 VarDecl *MostRecent = Old->getMostRecentDecl();
4093 if (MostRecent != Old) {
4094 MergeVarDeclTypes(New, MostRecent,
4095 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4096 if (New->isInvalidDecl())
4097 return;
4098 }
4099
4100 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4101 if (New->isInvalidDecl())
4102 return;
4103
4104 diag::kind PrevDiag;
4105 SourceLocation OldLocation;
4106 std::tie(PrevDiag, OldLocation) =
4107 getNoteDiagForInvalidRedeclaration(Old, New);
4108
4109 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4110 if (New->getStorageClass() == SC_Static &&
4111 !New->isStaticDataMember() &&
4112 Old->hasExternalFormalLinkage()) {
4113 if (getLangOpts().MicrosoftExt) {
4114 Diag(New->getLocation(), diag::ext_static_non_static)
4115 << New->getDeclName();
4116 Diag(OldLocation, PrevDiag);
4117 } else {
4118 Diag(New->getLocation(), diag::err_static_non_static)
4119 << New->getDeclName();
4120 Diag(OldLocation, PrevDiag);
4121 return New->setInvalidDecl();
4122 }
4123 }
4124 // C99 6.2.2p4:
4125 // For an identifier declared with the storage-class specifier
4126 // extern in a scope in which a prior declaration of that
4127 // identifier is visible,23) if the prior declaration specifies
4128 // internal or external linkage, the linkage of the identifier at
4129 // the later declaration is the same as the linkage specified at
4130 // the prior declaration. If no prior declaration is visible, or
4131 // if the prior declaration specifies no linkage, then the
4132 // identifier has external linkage.
4133 if (New->hasExternalStorage() && Old->hasLinkage())
4134 /* Okay */;
4135 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4136 !New->isStaticDataMember() &&
4137 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4138 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4139 Diag(OldLocation, PrevDiag);
4140 return New->setInvalidDecl();
4141 }
4142
4143 // Check if extern is followed by non-extern and vice-versa.
4144 if (New->hasExternalStorage() &&
4145 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4146 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4147 Diag(OldLocation, PrevDiag);
4148 return New->setInvalidDecl();
4149 }
4150 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4151 !New->hasExternalStorage()) {
4152 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4153 Diag(OldLocation, PrevDiag);
4154 return New->setInvalidDecl();
4155 }
4156
4157 if (CheckRedeclarationModuleOwnership(New, Old))
4158 return;
4159
4160 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4161
4162 // FIXME: The test for external storage here seems wrong? We still
4163 // need to check for mismatches.
4164 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4165 // Don't complain about out-of-line definitions of static members.
4166 !(Old->getLexicalDeclContext()->isRecord() &&
4167 !New->getLexicalDeclContext()->isRecord())) {
4168 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4169 Diag(OldLocation, PrevDiag);
4170 return New->setInvalidDecl();
4171 }
4172
4173 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4174 if (VarDecl *Def = Old->getDefinition()) {
4175 // C++1z [dcl.fcn.spec]p4:
4176 // If the definition of a variable appears in a translation unit before
4177 // its first declaration as inline, the program is ill-formed.
4178 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4179 Diag(Def->getLocation(), diag::note_previous_definition);
4180 }
4181 }
4182
4183 // If this redeclaration makes the variable inline, we may need to add it to
4184 // UndefinedButUsed.
4185 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4186 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4187 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4188 SourceLocation()));
4189
4190 if (New->getTLSKind() != Old->getTLSKind()) {
4191 if (!Old->getTLSKind()) {
4192 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4193 Diag(OldLocation, PrevDiag);
4194 } else if (!New->getTLSKind()) {
4195 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4196 Diag(OldLocation, PrevDiag);
4197 } else {
4198 // Do not allow redeclaration to change the variable between requiring
4199 // static and dynamic initialization.
4200 // FIXME: GCC allows this, but uses the TLS keyword on the first
4201 // declaration to determine the kind. Do we need to be compatible here?
4202 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4203 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4204 Diag(OldLocation, PrevDiag);
4205 }
4206 }
4207
4208 // C++ doesn't have tentative definitions, so go right ahead and check here.
4209 if (getLangOpts().CPlusPlus &&
4210 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4211 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4212 Old->getCanonicalDecl()->isConstexpr()) {
4213 // This definition won't be a definition any more once it's been merged.
4214 Diag(New->getLocation(),
4215 diag::warn_deprecated_redundant_constexpr_static_def);
4216 } else if (VarDecl *Def = Old->getDefinition()) {
4217 if (checkVarDeclRedefinition(Def, New))
4218 return;
4219 }
4220 }
4221
4222 if (haveIncompatibleLanguageLinkages(Old, New)) {
4223 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4224 Diag(OldLocation, PrevDiag);
4225 New->setInvalidDecl();
4226 return;
4227 }
4228
4229 // Merge "used" flag.
4230 if (Old->getMostRecentDecl()->isUsed(false))
4231 New->setIsUsed();
4232
4233 // Keep a chain of previous declarations.
4234 New->setPreviousDecl(Old);
4235 if (NewTemplate)
4236 NewTemplate->setPreviousDecl(OldTemplate);
4237 adjustDeclContextForDeclaratorDecl(New, Old);
4238
4239 // Inherit access appropriately.
4240 New->setAccess(Old->getAccess());
4241 if (NewTemplate)
4242 NewTemplate->setAccess(New->getAccess());
4243
4244 if (Old->isInline())
4245 New->setImplicitlyInline();
4246}
4247
4248void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4249 SourceManager &SrcMgr = getSourceManager();
4250 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4251 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4252 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4253 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4254 auto &HSI = PP.getHeaderSearchInfo();
4255 StringRef HdrFilename =
4256 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4257
4258 auto noteFromModuleOrInclude = [&](Module *Mod,
4259 SourceLocation IncLoc) -> bool {
4260 // Redefinition errors with modules are common with non modular mapped
4261 // headers, example: a non-modular header H in module A that also gets
4262 // included directly in a TU. Pointing twice to the same header/definition
4263 // is confusing, try to get better diagnostics when modules is on.
4264 if (IncLoc.isValid()) {
4265 if (Mod) {
4266 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4267 << HdrFilename.str() << Mod->getFullModuleName();
4268 if (!Mod->DefinitionLoc.isInvalid())
4269 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4270 << Mod->getFullModuleName();
4271 } else {
4272 Diag(IncLoc, diag::note_redefinition_include_same_file)
4273 << HdrFilename.str();
4274 }
4275 return true;
4276 }
4277
4278 return false;
4279 };
4280
4281 // Is it the same file and same offset? Provide more information on why
4282 // this leads to a redefinition error.
4283 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4284 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4285 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4286 bool EmittedDiag =
4287 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4288 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4289
4290 // If the header has no guards, emit a note suggesting one.
4291 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4292 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4293
4294 if (EmittedDiag)
4295 return;
4296 }
4297
4298 // Redefinition coming from different files or couldn't do better above.
4299 if (Old->getLocation().isValid())
4300 Diag(Old->getLocation(), diag::note_previous_definition);
4301}
4302
4303/// We've just determined that \p Old and \p New both appear to be definitions
4304/// of the same variable. Either diagnose or fix the problem.
4305bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4306 if (!hasVisibleDefinition(Old) &&
4307 (New->getFormalLinkage() == InternalLinkage ||
4308 New->isInline() ||
4309 New->getDescribedVarTemplate() ||
4310 New->getNumTemplateParameterLists() ||
4311 New->getDeclContext()->isDependentContext())) {
4312 // The previous definition is hidden, and multiple definitions are
4313 // permitted (in separate TUs). Demote this to a declaration.
4314 New->demoteThisDefinitionToDeclaration();
4315
4316 // Make the canonical definition visible.
4317 if (auto *OldTD = Old->getDescribedVarTemplate())
4318 makeMergedDefinitionVisible(OldTD);
4319 makeMergedDefinitionVisible(Old);
4320 return false;
4321 } else {
4322 Diag(New->getLocation(), diag::err_redefinition) << New;
4323 notePreviousDefinition(Old, New->getLocation());
4324 New->setInvalidDecl();
4325 return true;
4326 }
4327}
4328
4329/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4330/// no declarator (e.g. "struct foo;") is parsed.
4331Decl *
4332Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4333 RecordDecl *&AnonRecord) {
4334 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4335 AnonRecord);
4336}
4337
4338// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4339// disambiguate entities defined in different scopes.
4340// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4341// compatibility.
4342// We will pick our mangling number depending on which version of MSVC is being
4343// targeted.
4344static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4345 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4346 ? S->getMSCurManglingNumber()
4347 : S->getMSLastManglingNumber();
4348}
4349
4350void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4351 if (!Context.getLangOpts().CPlusPlus)
4352 return;
4353
4354 if (isa<CXXRecordDecl>(Tag->getParent())) {
4355 // If this tag is the direct child of a class, number it if
4356 // it is anonymous.
4357 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4358 return;
4359 MangleNumberingContext &MCtx =
4360 Context.getManglingNumberContext(Tag->getParent());
4361 Context.setManglingNumber(
4362 Tag, MCtx.getManglingNumber(
4363 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4364 return;
4365 }
4366
4367 // If this tag isn't a direct child of a class, number it if it is local.
4368 MangleNumberingContext *MCtx;
4369 Decl *ManglingContextDecl;
4370 std::tie(MCtx, ManglingContextDecl) =
4371 getCurrentMangleNumberContext(Tag->getDeclContext());
4372 if (MCtx) {
4373 Context.setManglingNumber(
4374 Tag, MCtx->getManglingNumber(
4375 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4376 }
4377}
4378
4379namespace {
4380struct NonCLikeKind {
4381 enum {
4382 None,
4383 BaseClass,
4384 DefaultMemberInit,
4385 Lambda,
4386 Friend,
4387 OtherMember,
4388 Invalid,
4389 } Kind = None;
4390 SourceRange Range;
4391
4392 explicit operator bool() { return Kind != None; }
4393};
4394}
4395
4396/// Determine whether a class is C-like, according to the rules of C++
4397/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4398static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4399 if (RD->isInvalidDecl())
4400 return {NonCLikeKind::Invalid, {}};
4401
4402 // C++ [dcl.typedef]p9: [P1766R1]
4403 // An unnamed class with a typedef name for linkage purposes shall not
4404 //
4405 // -- have any base classes
4406 if (RD->getNumBases())
4407 return {NonCLikeKind::BaseClass,
4408 SourceRange(RD->bases_begin()->getBeginLoc(),
4409 RD->bases_end()[-1].getEndLoc())};
4410 bool Invalid = false;
4411 for (Decl *D : RD->decls()) {
4412 // Don't complain about things we already diagnosed.
4413 if (D->isInvalidDecl()) {
4414 Invalid = true;
4415 continue;
4416 }
4417
4418 // -- have any [...] default member initializers
4419 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4420 if (FD->hasInClassInitializer()) {
4421 auto *Init = FD->getInClassInitializer();
4422 return {NonCLikeKind::DefaultMemberInit,
4423 Init ? Init->getSourceRange() : D->getSourceRange()};
4424 }
4425 continue;
4426 }
4427
4428 // FIXME: We don't allow friend declarations. This violates the wording of
4429 // P1766, but not the intent.
4430 if (isa<FriendDecl>(D))
4431 return {NonCLikeKind::Friend, D->getSourceRange()};
4432
4433 // -- declare any members other than non-static data members, member
4434 // enumerations, or member classes,
4435 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4436 isa<EnumDecl>(D))
4437 continue;
4438 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4439 if (!MemberRD) {
4440 if (D->isImplicit())
4441 continue;
4442 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4443 }
4444
4445 // -- contain a lambda-expression,
4446 if (MemberRD->isLambda())
4447 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4448
4449 // and all member classes shall also satisfy these requirements
4450 // (recursively).
4451 if (MemberRD->isThisDeclarationADefinition()) {
4452 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4453 return Kind;
4454 }
4455 }
4456
4457 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4458}
4459
4460void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4461 TypedefNameDecl *NewTD) {
4462 if (TagFromDeclSpec->isInvalidDecl())
4463 return;
4464
4465 // Do nothing if the tag already has a name for linkage purposes.
4466 if (TagFromDeclSpec->hasNameForLinkage())
4467 return;
4468
4469 // A well-formed anonymous tag must always be a TUK_Definition.
4470 assert(TagFromDeclSpec->isThisDeclarationADefinition())((TagFromDeclSpec->isThisDeclarationADefinition()) ? static_cast
<void> (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 4470, __PRETTY_FUNCTION__))
;
4471
4472 // The type must match the tag exactly; no qualifiers allowed.
4473 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4474 Context.getTagDeclType(TagFromDeclSpec))) {
4475 if (getLangOpts().CPlusPlus)
4476 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4477 return;
4478 }
4479
4480 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4481 // An unnamed class with a typedef name for linkage purposes shall [be
4482 // C-like].
4483 //
4484 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4485 // shouldn't happen, but there are constructs that the language rule doesn't
4486 // disallow for which we can't reasonably avoid computing linkage early.
4487 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4488 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4489 : NonCLikeKind();
4490 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4491 if (NonCLike || ChangesLinkage) {
4492 if (NonCLike.Kind == NonCLikeKind::Invalid)
4493 return;
4494
4495 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4496 if (ChangesLinkage) {
4497 // If the linkage changes, we can't accept this as an extension.
4498 if (NonCLike.Kind == NonCLikeKind::None)
4499 DiagID = diag::err_typedef_changes_linkage;
4500 else
4501 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4502 }
4503
4504 SourceLocation FixitLoc =
4505 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4506 llvm::SmallString<40> TextToInsert;
4507 TextToInsert += ' ';
4508 TextToInsert += NewTD->getIdentifier()->getName();
4509
4510 Diag(FixitLoc, DiagID)
4511 << isa<TypeAliasDecl>(NewTD)
4512 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4513 if (NonCLike.Kind != NonCLikeKind::None) {
4514 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4515 << NonCLike.Kind - 1 << NonCLike.Range;
4516 }
4517 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4518 << NewTD << isa<TypeAliasDecl>(NewTD);
4519
4520 if (ChangesLinkage)
4521 return;
4522 }
4523
4524 // Otherwise, set this as the anon-decl typedef for the tag.
4525 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4526}
4527
4528static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4529 switch (T) {
4530 case DeclSpec::TST_class:
4531 return 0;
4532 case DeclSpec::TST_struct:
4533 return 1;
4534 case DeclSpec::TST_interface:
4535 return 2;
4536 case DeclSpec::TST_union:
4537 return 3;
4538 case DeclSpec::TST_enum:
4539 return 4;
4540 default:
4541 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 4541)
;
4542 }
4543}
4544
4545/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4546/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4547/// parameters to cope with template friend declarations.
4548Decl *
4549Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4550 MultiTemplateParamsArg TemplateParams,
4551 bool IsExplicitInstantiation,
4552 RecordDecl *&AnonRecord) {
4553 Decl *TagD = nullptr;
4554 TagDecl *Tag = nullptr;
4555 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4556 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4557 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4558 DS.getTypeSpecType() == DeclSpec::TST_union ||
4559 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4560 TagD = DS.getRepAsDecl();
4561
4562 if (!TagD) // We probably had an error
4563 return nullptr;
4564
4565 // Note that the above type specs guarantee that the
4566 // type rep is a Decl, whereas in many of the others
4567 // it's a Type.
4568 if (isa<TagDecl>(TagD))
4569 Tag = cast<TagDecl>(TagD);
4570 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4571 Tag = CTD->getTemplatedDecl();
4572 }
4573
4574 if (Tag) {
4575 handleTagNumbering(Tag, S);
4576 Tag->setFreeStanding();
4577 if (Tag->isInvalidDecl())
4578 return Tag;
4579 }
4580
4581 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4582 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4583 // or incomplete types shall not be restrict-qualified."
4584 if (TypeQuals & DeclSpec::TQ_restrict)
4585 Diag(DS.getRestrictSpecLoc(),
4586 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4587 << DS.getSourceRange();
4588 }
4589
4590 if (DS.isInlineSpecified())
4591 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4592 << getLangOpts().CPlusPlus17;
4593
4594 if (DS.hasConstexprSpecifier()) {
4595 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4596 // and definitions of functions and variables.
4597 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4598 // the declaration of a function or function template
4599 if (Tag)
4600 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4601 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4602 << static_cast<int>(DS.getConstexprSpecifier());
4603 else
4604 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4605 << static_cast<int>(DS.getConstexprSpecifier());
4606 // Don't emit warnings after this error.
4607 return TagD;
4608 }
4609
4610 DiagnoseFunctionSpecifiers(DS);
4611
4612 if (DS.isFriendSpecified()) {
4613 // If we're dealing with a decl but not a TagDecl, assume that
4614 // whatever routines created it handled the friendship aspect.
4615 if (TagD && !Tag)
4616 return nullptr;
4617 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4618 }
4619
4620 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4621 bool IsExplicitSpecialization =
4622 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4623 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4624 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4625 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4626 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4627 // nested-name-specifier unless it is an explicit instantiation
4628 // or an explicit specialization.
4629 //
4630 // FIXME: We allow class template partial specializations here too, per the
4631 // obvious intent of DR1819.
4632 //
4633 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4634 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4635 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4636 return nullptr;
4637 }
4638
4639 // Track whether this decl-specifier declares anything.
4640 bool DeclaresAnything = true;
4641
4642 // Handle anonymous struct definitions.
4643 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4644 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4645 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4646 if (getLangOpts().CPlusPlus ||
4647 Record->getDeclContext()->isRecord()) {
4648 // If CurContext is a DeclContext that can contain statements,
4649 // RecursiveASTVisitor won't visit the decls that
4650 // BuildAnonymousStructOrUnion() will put into CurContext.
4651 // Also store them here so that they can be part of the
4652 // DeclStmt that gets created in this case.
4653 // FIXME: Also return the IndirectFieldDecls created by
4654 // BuildAnonymousStructOr union, for the same reason?
4655 if (CurContext->isFunctionOrMethod())
4656 AnonRecord = Record;
4657 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4658 Context.getPrintingPolicy());
4659 }
4660
4661 DeclaresAnything = false;
4662 }
4663 }
4664
4665 // C11 6.7.2.1p2:
4666 // A struct-declaration that does not declare an anonymous structure or
4667 // anonymous union shall contain a struct-declarator-list.
4668 //
4669 // This rule also existed in C89 and C99; the grammar for struct-declaration
4670 // did not permit a struct-declaration without a struct-declarator-list.
4671 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4672 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4673 // Check for Microsoft C extension: anonymous struct/union member.
4674 // Handle 2 kinds of anonymous struct/union:
4675 // struct STRUCT;
4676 // union UNION;
4677 // and
4678 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4679 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4680 if ((Tag && Tag->getDeclName()) ||
4681 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4682 RecordDecl *Record = nullptr;
4683 if (Tag)
4684 Record = dyn_cast<RecordDecl>(Tag);
4685 else if (const RecordType *RT =
4686 DS.getRepAsType().get()->getAsStructureType())
4687 Record = RT->getDecl();
4688 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4689 Record = UT->getDecl();
4690
4691 if (Record && getLangOpts().MicrosoftExt) {
4692 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4693 << Record->isUnion() << DS.getSourceRange();
4694 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4695 }
4696
4697 DeclaresAnything = false;
4698 }
4699 }
4700
4701 // Skip all the checks below if we have a type error.
4702 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4703 (TagD && TagD->isInvalidDecl()))
4704 return TagD;
4705
4706 if (getLangOpts().CPlusPlus &&
4707 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4708 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4709 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4710 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4711 DeclaresAnything = false;
4712
4713 if (!DS.isMissingDeclaratorOk()) {
4714 // Customize diagnostic for a typedef missing a name.
4715 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4716 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4717 << DS.getSourceRange();
4718 else
4719 DeclaresAnything = false;
4720 }
4721
4722 if (DS.isModulePrivateSpecified() &&
4723 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4724 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4725 << Tag->getTagKind()
4726 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4727
4728 ActOnDocumentableDecl(TagD);
4729
4730 // C 6.7/2:
4731 // A declaration [...] shall declare at least a declarator [...], a tag,
4732 // or the members of an enumeration.
4733 // C++ [dcl.dcl]p3:
4734 // [If there are no declarators], and except for the declaration of an
4735 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4736 // names into the program, or shall redeclare a name introduced by a
4737 // previous declaration.
4738 if (!DeclaresAnything) {
4739 // In C, we allow this as a (popular) extension / bug. Don't bother
4740 // producing further diagnostics for redundant qualifiers after this.
4741 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4742 ? diag::err_no_declarators
4743 : diag::ext_no_declarators)
4744 << DS.getSourceRange();
4745 return TagD;
4746 }
4747
4748 // C++ [dcl.stc]p1:
4749 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4750 // init-declarator-list of the declaration shall not be empty.
4751 // C++ [dcl.fct.spec]p1:
4752 // If a cv-qualifier appears in a decl-specifier-seq, the
4753 // init-declarator-list of the declaration shall not be empty.
4754 //
4755 // Spurious qualifiers here appear to be valid in C.
4756 unsigned DiagID = diag::warn_standalone_specifier;
4757 if (getLangOpts().CPlusPlus)
4758 DiagID = diag::ext_standalone_specifier;
4759
4760 // Note that a linkage-specification sets a storage class, but
4761 // 'extern "C" struct foo;' is actually valid and not theoretically
4762 // useless.
4763 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4764 if (SCS == DeclSpec::SCS_mutable)
4765 // Since mutable is not a viable storage class specifier in C, there is
4766 // no reason to treat it as an extension. Instead, diagnose as an error.
4767 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4768 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4769 Diag(DS.getStorageClassSpecLoc(), DiagID)
4770 << DeclSpec::getSpecifierName(SCS);
4771 }
4772
4773 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4774 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4775 << DeclSpec::getSpecifierName(TSCS);
4776 if (DS.getTypeQualifiers()) {
4777 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4778 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4779 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4780 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4781 // Restrict is covered above.
4782 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4783 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4784 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4785 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4786 }
4787
4788 // Warn about ignored type attributes, for example:
4789 // __attribute__((aligned)) struct A;
4790 // Attributes should be placed after tag to apply to type declaration.
4791 if (!DS.getAttributes().empty()) {
4792 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4793 if (TypeSpecType == DeclSpec::TST_class ||
4794 TypeSpecType == DeclSpec::TST_struct ||
4795 TypeSpecType == DeclSpec::TST_interface ||
4796 TypeSpecType == DeclSpec::TST_union ||
4797 TypeSpecType == DeclSpec::TST_enum) {
4798 for (const ParsedAttr &AL : DS.getAttributes())
4799 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4800 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4801 }
4802 }
4803
4804 return TagD;
4805}
4806
4807/// We are trying to inject an anonymous member into the given scope;
4808/// check if there's an existing declaration that can't be overloaded.
4809///
4810/// \return true if this is a forbidden redeclaration
4811static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4812 Scope *S,
4813 DeclContext *Owner,
4814 DeclarationName Name,
4815 SourceLocation NameLoc,
4816 bool IsUnion) {
4817 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4818 Sema::ForVisibleRedeclaration);
4819 if (!SemaRef.LookupName(R, S)) return false;
4820
4821 // Pick a representative declaration.
4822 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4823 assert(PrevDecl && "Expected a non-null Decl")((PrevDecl && "Expected a non-null Decl") ? static_cast
<void> (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 4823, __PRETTY_FUNCTION__))
;
4824
4825 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4826 return false;
4827
4828 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4829 << IsUnion << Name;
4830 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4831
4832 return true;
4833}
4834
4835/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4836/// anonymous struct or union AnonRecord into the owning context Owner
4837/// and scope S. This routine will be invoked just after we realize
4838/// that an unnamed union or struct is actually an anonymous union or
4839/// struct, e.g.,
4840///
4841/// @code
4842/// union {
4843/// int i;
4844/// float f;
4845/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4846/// // f into the surrounding scope.x
4847/// @endcode
4848///
4849/// This routine is recursive, injecting the names of nested anonymous
4850/// structs/unions into the owning context and scope as well.
4851static bool
4852InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4853 RecordDecl *AnonRecord, AccessSpecifier AS,
4854 SmallVectorImpl<NamedDecl *> &Chaining) {
4855 bool Invalid = false;
4856
4857 // Look every FieldDecl and IndirectFieldDecl with a name.
4858 for (auto *D : AnonRecord->decls()) {
4859 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4860 cast<NamedDecl>(D)->getDeclName()) {
4861 ValueDecl *VD = cast<ValueDecl>(D);
4862 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4863 VD->getLocation(),
4864 AnonRecord->isUnion())) {
4865 // C++ [class.union]p2:
4866 // The names of the members of an anonymous union shall be
4867 // distinct from the names of any other entity in the
4868 // scope in which the anonymous union is declared.
4869 Invalid = true;
4870 } else {
4871 // C++ [class.union]p2:
4872 // For the purpose of name lookup, after the anonymous union
4873 // definition, the members of the anonymous union are
4874 // considered to have been defined in the scope in which the
4875 // anonymous union is declared.
4876 unsigned OldChainingSize = Chaining.size();
4877 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4878 Chaining.append(IF->chain_begin(), IF->chain_end());
4879 else
4880 Chaining.push_back(VD);
4881
4882 assert(Chaining.size() >= 2)((Chaining.size() >= 2) ? static_cast<void> (0) : __assert_fail
("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 4882, __PRETTY_FUNCTION__))
;
4883 NamedDecl **NamedChain =
4884 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4885 for (unsigned i = 0; i < Chaining.size(); i++)
4886 NamedChain[i] = Chaining[i];
4887
4888 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4889 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4890 VD->getType(), {NamedChain, Chaining.size()});
4891
4892 for (const auto *Attr : VD->attrs())
4893 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4894
4895 IndirectField->setAccess(AS);
4896 IndirectField->setImplicit();
4897 SemaRef.PushOnScopeChains(IndirectField, S);
4898
4899 // That includes picking up the appropriate access specifier.
4900 if (AS != AS_none) IndirectField->setAccess(AS);
4901
4902 Chaining.resize(OldChainingSize);
4903 }
4904 }
4905 }
4906
4907 return Invalid;
4908}
4909
4910/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4911/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4912/// illegal input values are mapped to SC_None.
4913static StorageClass
4914StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4915 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4916 assert(StorageClassSpec != DeclSpec::SCS_typedef &&((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl."
) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 4917, __PRETTY_FUNCTION__))
4917 "Parser allowed 'typedef' as storage class VarDecl.")((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl."
) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 4917, __PRETTY_FUNCTION__))
;
4918 switch (StorageClassSpec) {
4919 case DeclSpec::SCS_unspecified: return SC_None;
4920 case DeclSpec::SCS_extern:
4921 if (DS.isExternInLinkageSpec())
4922 return SC_None;
4923 return SC_Extern;
4924 case DeclSpec::SCS_static: return SC_Static;
4925 case DeclSpec::SCS_auto: return SC_Auto;
4926 case DeclSpec::SCS_register: return SC_Register;
4927 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4928 // Illegal SCSs map to None: error reporting is up to the caller.
4929 case DeclSpec::SCS_mutable: // Fall through.
4930 case DeclSpec::SCS_typedef: return SC_None;
4931 }
4932 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 4932)
;
4933}
4934
4935static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4936 assert(Record->hasInClassInitializer())((Record->hasInClassInitializer()) ? static_cast<void>
(0) : __assert_fail ("Record->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 4936, __PRETTY_FUNCTION__))
;
4937
4938 for (const auto *I : Record->decls()) {
4939 const auto *FD = dyn_cast<FieldDecl>(I);
4940 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4941 FD = IFD->getAnonField();
4942 if (FD && FD->hasInClassInitializer())
4943 return FD->getLocation();
4944 }
4945
4946 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 4946)
;
4947}
4948
4949static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4950 SourceLocation DefaultInitLoc) {
4951 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4952 return;
4953
4954 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4955 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4956}
4957
4958static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4959 CXXRecordDecl *AnonUnion) {
4960 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4961 return;
4962
4963 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4964}
4965
4966/// BuildAnonymousStructOrUnion - Handle the declaration of an
4967/// anonymous structure or union. Anonymous unions are a C++ feature
4968/// (C++ [class.union]) and a C11 feature; anonymous structures
4969/// are a C11 feature and GNU C++ extension.
4970Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4971 AccessSpecifier AS,
4972 RecordDecl *Record,
4973 const PrintingPolicy &Policy) {
4974 DeclContext *Owner = Record->getDeclContext();
4975
4976 // Diagnose whether this anonymous struct/union is an extension.
4977 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4978 Diag(Record->getLocation(), diag::ext_anonymous_union);
4979 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4980 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4981 else if (!Record->isUnion() && !getLangOpts().C11)
4982 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4983
4984 // C and C++ require different kinds of checks for anonymous
4985 // structs/unions.
4986 bool Invalid = false;
4987 if (getLangOpts().CPlusPlus) {
4988 const char *PrevSpec = nullptr;
4989 if (Record->isUnion()) {
4990 // C++ [class.union]p6:
4991 // C++17 [class.union.anon]p2:
4992 // Anonymous unions declared in a named namespace or in the
4993 // global namespace shall be declared static.
4994 unsigned DiagID;
4995 DeclContext *OwnerScope = Owner->getRedeclContext();
4996 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4997 (OwnerScope->isTranslationUnit() ||
4998 (OwnerScope->isNamespace() &&
4999 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5000 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5001 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5002
5003 // Recover by adding 'static'.
5004 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5005 PrevSpec, DiagID, Policy);
5006 }
5007 // C++ [class.union]p6:
5008 // A storage class is not allowed in a declaration of an
5009 // anonymous union in a class scope.
5010 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5011 isa<RecordDecl>(Owner)) {
5012 Diag(DS.getStorageClassSpecLoc(),
5013 diag::err_anonymous_union_with_storage_spec)
5014 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5015
5016 // Recover by removing the storage specifier.
5017 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5018 SourceLocation(),
5019 PrevSpec, DiagID, Context.getPrintingPolicy());
5020 }
5021 }
5022
5023 // Ignore const/volatile/restrict qualifiers.
5024 if (DS.getTypeQualifiers()) {
5025 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5026 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5027 << Record->isUnion() << "const"
5028 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5029 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5030 Diag(DS.getVolatileSpecLoc(),
5031 diag::ext_anonymous_struct_union_qualified)
5032 << Record->isUnion() << "volatile"
5033 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5034 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5035 Diag(DS.getRestrictSpecLoc(),
5036 diag::ext_anonymous_struct_union_qualified)
5037 << Record->isUnion() << "restrict"
5038 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5039 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5040 Diag(DS.getAtomicSpecLoc(),
5041 diag::ext_anonymous_struct_union_qualified)
5042 << Record->isUnion() << "_Atomic"
5043 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5044 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5045 Diag(DS.getUnalignedSpecLoc(),
5046 diag::ext_anonymous_struct_union_qualified)
5047 << Record->isUnion() << "__unaligned"
5048 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5049
5050 DS.ClearTypeQualifiers();
5051 }
5052
5053 // C++ [class.union]p2:
5054 // The member-specification of an anonymous union shall only
5055 // define non-static data members. [Note: nested types and
5056 // functions cannot be declared within an anonymous union. ]
5057 for (auto *Mem : Record->decls()) {
5058 // Ignore invalid declarations; we already diagnosed them.
5059 if (Mem->isInvalidDecl())
5060 continue;
5061
5062 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5063 // C++ [class.union]p3:
5064 // An anonymous union shall not have private or protected
5065 // members (clause 11).
5066 assert(FD->getAccess() != AS_none)((FD->getAccess() != AS_none) ? static_cast<void> (0
) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 5066, __PRETTY_FUNCTION__))
;
5067 if (FD->getAccess() != AS_public) {
5068 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5069 << Record->isUnion() << (FD->getAccess() == AS_protected);
5070 Invalid = true;
5071 }
5072
5073 // C++ [class.union]p1
5074 // An object of a class with a non-trivial constructor, a non-trivial
5075 // copy constructor, a non-trivial destructor, or a non-trivial copy
5076 // assignment operator cannot be a member of a union, nor can an
5077 // array of such objects.
5078 if (CheckNontrivialField(FD))
5079 Invalid = true;
5080 } else if (Mem->isImplicit()) {
5081 // Any implicit members are fine.
5082 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5083 // This is a type that showed up in an
5084 // elaborated-type-specifier inside the anonymous struct or
5085 // union, but which actually declares a type outside of the
5086 // anonymous struct or union. It's okay.
5087 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5088 if (!MemRecord->isAnonymousStructOrUnion() &&
5089 MemRecord->getDeclName()) {
5090 // Visual C++ allows type definition in anonymous struct or union.
5091 if (getLangOpts().MicrosoftExt)
5092 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5093 << Record->isUnion();
5094 else {
5095 // This is a nested type declaration.
5096 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5097 << Record->isUnion();
5098 Invalid = true;
5099 }
5100 } else {
5101 // This is an anonymous type definition within another anonymous type.
5102 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5103 // not part of standard C++.
5104 Diag(MemRecord->getLocation(),
5105 diag::ext_anonymous_record_with_anonymous_type)
5106 << Record->isUnion();
5107 }
5108 } else if (isa<AccessSpecDecl>(Mem)) {
5109 // Any access specifier is fine.
5110 } else if (isa<StaticAssertDecl>(Mem)) {
5111 // In C++1z, static_assert declarations are also fine.
5112 } else {
5113 // We have something that isn't a non-static data
5114 // member. Complain about it.
5115 unsigned DK = diag::err_anonymous_record_bad_member;
5116 if (isa<TypeDecl>(Mem))
5117 DK = diag::err_anonymous_record_with_type;
5118 else if (isa<FunctionDecl>(Mem))
5119 DK = diag::err_anonymous_record_with_function;
5120 else if (isa<VarDecl>(Mem))
5121 DK = diag::err_anonymous_record_with_static;
5122
5123 // Visual C++ allows type definition in anonymous struct or union.
5124 if (getLangOpts().MicrosoftExt &&
5125 DK == diag::err_anonymous_record_with_type)
5126 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5127 << Record->isUnion();
5128 else {
5129 Diag(Mem->getLocation(), DK) << Record->isUnion();
5130 Invalid = true;
5131 }
5132 }
5133 }
5134
5135 // C++11 [class.union]p8 (DR1460):
5136 // At most one variant member of a union may have a
5137 // brace-or-equal-initializer.
5138 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5139 Owner->isRecord())
5140 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5141 cast<CXXRecordDecl>(Record));
5142 }
5143
5144 if (!Record->isUnion() && !Owner->isRecord()) {
5145 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5146 << getLangOpts().CPlusPlus;
5147 Invalid = true;
5148 }
5149
5150 // C++ [dcl.dcl]p3:
5151 // [If there are no declarators], and except for the declaration of an
5152 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5153 // names into the program
5154 // C++ [class.mem]p2:
5155 // each such member-declaration shall either declare at least one member
5156 // name of the class or declare at least one unnamed bit-field
5157 //
5158 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5159 if (getLangOpts().CPlusPlus && Record->field_empty())
5160 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5161
5162 // Mock up a declarator.
5163 Declarator Dc(DS, DeclaratorContext::Member);
5164 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5165 assert(TInfo && "couldn't build declarator info for anonymous struct/union")((TInfo && "couldn't build declarator info for anonymous struct/union"
) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 5165, __PRETTY_FUNCTION__))
;
5166
5167 // Create a declaration for this anonymous struct/union.
5168 NamedDecl *Anon = nullptr;
5169 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5170 Anon = FieldDecl::Create(
5171 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5172 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5173 /*BitWidth=*/nullptr, /*Mutable=*/false,
5174 /*InitStyle=*/ICIS_NoInit);
5175 Anon->setAccess(AS);
5176 ProcessDeclAttributes(S, Anon, Dc);
5177
5178 if (getLangOpts().CPlusPlus)
5179 FieldCollector->Add(cast<FieldDecl>(Anon));
5180 } else {
5181 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5182 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5183 if (SCSpec == DeclSpec::SCS_mutable) {
5184 // mutable can only appear on non-static class members, so it's always
5185 // an error here
5186 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5187 Invalid = true;
5188 SC = SC_None;
5189 }
5190
5191 assert(DS.getAttributes().empty() && "No attribute expected")((DS.getAttributes().empty() && "No attribute expected"
) ? static_cast<void> (0) : __assert_fail ("DS.getAttributes().empty() && \"No attribute expected\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 5191, __PRETTY_FUNCTION__))
;
5192 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5193 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5194 Context.getTypeDeclType(Record), TInfo, SC);
5195
5196 // Default-initialize the implicit variable. This initialization will be
5197 // trivial in almost all cases, except if a union member has an in-class
5198 // initializer:
5199 // union { int n = 0; };
5200 ActOnUninitializedDecl(Anon);
5201 }
5202 Anon->setImplicit();
5203
5204 // Mark this as an anonymous struct/union type.
5205 Record->setAnonymousStructOrUnion(true);
5206
5207 // Add the anonymous struct/union object to the current
5208 // context. We'll be referencing this object when we refer to one of
5209 // its members.
5210 Owner->addDecl(Anon);
5211
5212 // Inject the members of the anonymous struct/union into the owning
5213 // context and into the identifier resolver chain for name lookup
5214 // purposes.
5215 SmallVector<NamedDecl*, 2> Chain;
5216 Chain.push_back(Anon);
5217
5218 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5219 Invalid = true;
5220
5221 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5222 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5223 MangleNumberingContext *MCtx;
5224 Decl *ManglingContextDecl;
5225 std::tie(MCtx, ManglingContextDecl) =
5226 getCurrentMangleNumberContext(NewVD->getDeclContext());
5227 if (MCtx) {
5228 Context.setManglingNumber(
5229 NewVD, MCtx->getManglingNumber(
5230 NewVD, getMSManglingNumber(getLangOpts(), S)));
5231 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5232 }
5233 }
5234 }
5235
5236 if (Invalid)
5237 Anon->setInvalidDecl();
5238
5239 return Anon;
5240}
5241
5242/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5243/// Microsoft C anonymous structure.
5244/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5245/// Example:
5246///
5247/// struct A { int a; };
5248/// struct B { struct A; int b; };
5249///
5250/// void foo() {
5251/// B var;
5252/// var.a = 3;
5253/// }
5254///
5255Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5256 RecordDecl *Record) {
5257 assert(Record && "expected a record!")((Record && "expected a record!") ? static_cast<void
> (0) : __assert_fail ("Record && \"expected a record!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 5257, __PRETTY_FUNCTION__))
;
5258
5259 // Mock up a declarator.
5260 Declarator Dc(DS, DeclaratorContext::TypeName);
5261 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5262 assert(TInfo && "couldn't build declarator info for anonymous struct")((TInfo && "couldn't build declarator info for anonymous struct"
) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 5262, __PRETTY_FUNCTION__))
;
5263
5264 auto *ParentDecl = cast<RecordDecl>(CurContext);
5265 QualType RecTy = Context.getTypeDeclType(Record);
5266
5267 // Create a declaration for this anonymous struct.
5268 NamedDecl *Anon =
5269 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5270 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5271 /*BitWidth=*/nullptr, /*Mutable=*/false,
5272 /*InitStyle=*/ICIS_NoInit);
5273 Anon->setImplicit();
5274
5275 // Add the anonymous struct object to the current context.
5276 CurContext->addDecl(Anon);
5277
5278 // Inject the members of the anonymous struct into the current
5279 // context and into the identifier resolver chain for name lookup
5280 // purposes.
5281 SmallVector<NamedDecl*, 2> Chain;
5282 Chain.push_back(Anon);
5283
5284 RecordDecl *RecordDef = Record->getDefinition();
5285 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5286 diag::err_field_incomplete_or_sizeless) ||
5287 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5288 AS_none, Chain)) {
5289 Anon->setInvalidDecl();
5290 ParentDecl->setInvalidDecl();
5291 }
5292
5293 return Anon;
5294}
5295
5296/// GetNameForDeclarator - Determine the full declaration name for the
5297/// given Declarator.
5298DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5299 return GetNameFromUnqualifiedId(D.getName());
5300}
5301
5302/// Retrieves the declaration name from a parsed unqualified-id.
5303DeclarationNameInfo
5304Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5305 DeclarationNameInfo NameInfo;
5306 NameInfo.setLoc(Name.StartLocation);
5307
5308 switch (Name.getKind()) {
5309
5310 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5311 case UnqualifiedIdKind::IK_Identifier:
5312 NameInfo.setName(Name.Identifier);
5313 return NameInfo;
5314
5315 case UnqualifiedIdKind::IK_DeductionGuideName: {
5316 // C++ [temp.deduct.guide]p3:
5317 // The simple-template-id shall name a class template specialization.
5318 // The template-name shall be the same identifier as the template-name
5319 // of the simple-template-id.
5320 // These together intend to imply that the template-name shall name a
5321 // class template.
5322 // FIXME: template<typename T> struct X {};
5323 // template<typename T> using Y = X<T>;
5324 // Y(int) -> Y<int>;
5325 // satisfies these rules but does not name a class template.
5326 TemplateName TN = Name.TemplateName.get().get();
5327 auto *Template = TN.getAsTemplateDecl();
5328 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5329 Diag(Name.StartLocation,
5330 diag::err_deduction_guide_name_not_class_template)
5331 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5332 if (Template)
5333 Diag(Template->getLocation(), diag::note_template_decl_here);
5334 return DeclarationNameInfo();
5335 }
5336
5337 NameInfo.setName(
5338 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5339 return NameInfo;
5340 }
5341
5342 case UnqualifiedIdKind::IK_OperatorFunctionId:
5343 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5344 Name.OperatorFunctionId.Operator));
5345 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5346 = Name.OperatorFunctionId.SymbolLocations[0];
5347 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5348 = Name.EndLocation.getRawEncoding();
5349 return NameInfo;
5350
5351 case UnqualifiedIdKind::IK_LiteralOperatorId:
5352 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5353 Name.Identifier));
5354 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5355 return NameInfo;
5356
5357 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5358 TypeSourceInfo *TInfo;
5359 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5360 if (Ty.isNull())
5361 return DeclarationNameInfo();
5362 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5363 Context.getCanonicalType(Ty)));
5364 NameInfo.setNamedTypeInfo(TInfo);
5365 return NameInfo;
5366 }
5367
5368 case UnqualifiedIdKind::IK_ConstructorName: {
5369 TypeSourceInfo *TInfo;
5370 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5371 if (Ty.isNull())
5372 return DeclarationNameInfo();
5373 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5374 Context.getCanonicalType(Ty)));
5375 NameInfo.setNamedTypeInfo(TInfo);
5376 return NameInfo;
5377 }
5378
5379 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5380 // In well-formed code, we can only have a constructor
5381 // template-id that refers to the current context, so go there
5382 // to find the actual type being constructed.
5383 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5384 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5385 return DeclarationNameInfo();
5386
5387 // Determine the type of the class being constructed.
5388 QualType CurClassType = Context.getTypeDeclType(CurClass);
5389
5390 // FIXME: Check two things: that the template-id names the same type as
5391 // CurClassType, and that the template-id does not occur when the name
5392 // was qualified.
5393
5394 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5395 Context.getCanonicalType(CurClassType)));
5396 // FIXME: should we retrieve TypeSourceInfo?
5397 NameInfo.setNamedTypeInfo(nullptr);
5398 return NameInfo;
5399 }
5400
5401 case UnqualifiedIdKind::IK_DestructorName: {
5402 TypeSourceInfo *TInfo;
5403 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5404 if (Ty.isNull())
5405 return DeclarationNameInfo();
5406 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5407 Context.getCanonicalType(Ty)));
5408 NameInfo.setNamedTypeInfo(TInfo);
5409 return NameInfo;
5410 }
5411
5412 case UnqualifiedIdKind::IK_TemplateId: {
5413 TemplateName TName = Name.TemplateId->Template.get();
5414 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5415 return Context.getNameForTemplate(TName, TNameLoc);
5416 }
5417
5418 } // switch (Name.getKind())
5419
5420 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 5420)
;
5421}
5422
5423static QualType getCoreType(QualType Ty) {
5424 do {
5425 if (Ty->isPointerType() || Ty->isReferenceType())
5426 Ty = Ty->getPointeeType();
5427 else if (Ty->isArrayType())
5428 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5429 else
5430 return Ty.withoutLocalFastQualifiers();
5431 } while (true);
5432}
5433
5434/// hasSimilarParameters - Determine whether the C++ functions Declaration
5435/// and Definition have "nearly" matching parameters. This heuristic is
5436/// used to improve diagnostics in the case where an out-of-line function
5437/// definition doesn't match any declaration within the class or namespace.
5438/// Also sets Params to the list of indices to the parameters that differ
5439/// between the declaration and the definition. If hasSimilarParameters
5440/// returns true and Params is empty, then all of the parameters match.
5441static bool hasSimilarParameters(ASTContext &Context,
5442 FunctionDecl *Declaration,
5443 FunctionDecl *Definition,
5444 SmallVectorImpl<unsigned> &Params) {
5445 Params.clear();
5446 if (Declaration->param_size() != Definition->param_size())
5447 return false;
5448 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5449 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5450 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5451
5452 // The parameter types are identical
5453 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5454 continue;
5455
5456 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5457 QualType DefParamBaseTy = getCoreType(DefParamTy);
5458 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5459 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5460
5461 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5462 (DeclTyName && DeclTyName == DefTyName))
5463 Params.push_back(Idx);
5464 else // The two parameters aren't even close
5465 return false;
5466 }
5467
5468 return true;
5469}
5470
5471/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5472/// declarator needs to be rebuilt in the current instantiation.
5473/// Any bits of declarator which appear before the name are valid for
5474/// consideration here. That's specifically the type in the decl spec
5475/// and the base type in any member-pointer chunks.
5476static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5477 DeclarationName Name) {
5478 // The types we specifically need to rebuild are:
5479 // - typenames, typeofs, and decltypes
5480 // - types which will become injected class names
5481 // Of course, we also need to rebuild any type referencing such a
5482 // type. It's safest to just say "dependent", but we call out a
5483 // few cases here.
5484
5485 DeclSpec &DS = D.getMutableDeclSpec();
5486 switch (DS.getTypeSpecType()) {
5487 case DeclSpec::TST_typename:
5488 case DeclSpec::TST_typeofType:
5489 case DeclSpec::TST_underlyingType:
5490 case DeclSpec::TST_atomic: {
5491 // Grab the type from the parser.
5492 TypeSourceInfo *TSI = nullptr;
5493 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5494 if (T.isNull() || !T->isDependentType()) break;
5495
5496 // Make sure there's a type source info. This isn't really much
5497 // of a waste; most dependent types should have type source info
5498 // attached already.
5499 if (!TSI)
5500 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5501
5502 // Rebuild the type in the current instantiation.
5503 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5504 if (!TSI) return true;
5505
5506 // Store the new type back in the decl spec.
5507 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5508 DS.UpdateTypeRep(LocType);
5509 break;
5510 }
5511
5512 case DeclSpec::TST_decltype:
5513 case DeclSpec::TST_typeofExpr: {
5514 Expr *E = DS.getRepAsExpr();
5515 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5516 if (Result.isInvalid()) return true;
5517 DS.UpdateExprRep(Result.get());
5518 break;
5519 }
5520
5521 default:
5522 // Nothing to do for these decl specs.
5523 break;
5524 }
5525
5526 // It doesn't matter what order we do this in.
5527 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5528 DeclaratorChunk &Chunk = D.getTypeObject(I);
5529
5530 // The only type information in the declarator which can come
5531 // before the declaration name is the base type of a member
5532 // pointer.
5533 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5534 continue;
5535
5536 // Rebuild the scope specifier in-place.
5537 CXXScopeSpec &SS = Chunk.Mem.Scope();
5538 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5539 return true;
5540 }
5541
5542 return false;
5543}
5544
5545Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5546 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5547 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5548
5549 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5550 Dcl && Dcl->getDeclContext()->isFileContext())
5551 Dcl->setTopLevelDeclInObjCContainer();
5552
5553 if (getLangOpts().OpenCL)
5554 setCurrentOpenCLExtensionForDecl(Dcl);
5555
5556 return Dcl;
5557}
5558
5559/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5560/// If T is the name of a class, then each of the following shall have a
5561/// name different from T:
5562/// - every static data member of class T;
5563/// - every member function of class T
5564/// - every member of class T that is itself a type;
5565/// \returns true if the declaration name violates these rules.
5566bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5567 DeclarationNameInfo NameInfo) {
5568 DeclarationName Name = NameInfo.getName();
5569
5570 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5571 while (Record && Record->isAnonymousStructOrUnion())
5572 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5573 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5574 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5575 return true;
5576 }
5577
5578 return false;
5579}
5580
5581/// Diagnose a declaration whose declarator-id has the given
5582/// nested-name-specifier.
5583///
5584/// \param SS The nested-name-specifier of the declarator-id.
5585///
5586/// \param DC The declaration context to which the nested-name-specifier
5587/// resolves.
5588///
5589/// \param Name The name of the entity being declared.
5590///
5591/// \param Loc The location of the name of the entity being declared.
5592///
5593/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5594/// we're declaring an explicit / partial specialization / instantiation.
5595///
5596/// \returns true if we cannot safely recover from this error, false otherwise.
5597bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5598 DeclarationName Name,
5599 SourceLocation Loc, bool IsTemplateId) {
5600 DeclContext *Cur = CurContext;
5601 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5602 Cur = Cur->getParent();
5603
5604 // If the user provided a superfluous scope specifier that refers back to the
5605 // class in which the entity is already declared, diagnose and ignore it.
5606 //
5607 // class X {
5608 // void X::f();
5609 // };
5610 //
5611 // Note, it was once ill-formed to give redundant qualification in all
5612 // contexts, but that rule was removed by DR482.
5613 if (Cur->Equals(DC)) {
5614 if (Cur->isRecord()) {
5615 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5616 : diag::err_member_extra_qualification)
5617 << Name << FixItHint::CreateRemoval(SS.getRange());
5618 SS.clear();
5619 } else {
5620 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5621 }
5622 return false;
5623 }
5624
5625 // Check whether the qualifying scope encloses the scope of the original
5626 // declaration. For a template-id, we perform the checks in
5627 // CheckTemplateSpecializationScope.
5628 if (!Cur->Encloses(DC) && !IsTemplateId) {
5629 if (Cur->isRecord())
5630 Diag(Loc, diag::err_member_qualification)
5631 << Name << SS.getRange();
5632 else if (isa<TranslationUnitDecl>(DC))
5633 Diag(Loc, diag::err_invalid_declarator_global_scope)
5634 << Name << SS.getRange();
5635 else if (isa<FunctionDecl>(Cur))
5636 Diag(Loc, diag::err_invalid_declarator_in_function)
5637 << Name << SS.getRange();
5638 else if (isa<BlockDecl>(Cur))
5639 Diag(Loc, diag::err_invalid_declarator_in_block)
5640 << Name << SS.getRange();
5641 else
5642 Diag(Loc, diag::err_invalid_declarator_scope)
5643 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5644
5645 return true;
5646 }
5647
5648 if (Cur->isRecord()) {
5649 // Cannot qualify members within a class.
5650 Diag(Loc, diag::err_member_qualification)
5651 << Name << SS.getRange();
5652 SS.clear();
5653
5654 // C++ constructors and destructors with incorrect scopes can break
5655 // our AST invariants by having the wrong underlying types. If
5656 // that's the case, then drop this declaration entirely.
5657 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5658 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5659 !Context.hasSameType(Name.getCXXNameType(),
5660 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5661 return true;
5662
5663 return false;
5664 }
5665
5666 // C++11 [dcl.meaning]p1:
5667 // [...] "The nested-name-specifier of the qualified declarator-id shall
5668 // not begin with a decltype-specifer"
5669 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5670 while (SpecLoc.getPrefix())
5671 SpecLoc = SpecLoc.getPrefix();
5672 if (dyn_cast_or_null<DecltypeType>(
5673 SpecLoc.getNestedNameSpecifier()->getAsType()))
5674 Diag(Loc, diag::err_decltype_in_declarator)
5675 << SpecLoc.getTypeLoc().getSourceRange();
5676
5677 return false;
5678}
5679
5680NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5681 MultiTemplateParamsArg TemplateParamLists) {
5682 // TODO: consider using NameInfo for diagnostic.
5683 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5684 DeclarationName Name = NameInfo.getName();
5685
5686 // All of these full declarators require an identifier. If it doesn't have
5687 // one, the ParsedFreeStandingDeclSpec action should be used.
5688 if (D.isDecompositionDeclarator()) {
5689 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5690 } else if (!Name) {
5691 if (!D.isInvalidType()) // Reject this if we think it is valid.
5692 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5693 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5694 return nullptr;
5695 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5696 return nullptr;
5697
5698 // The scope passed in may not be a decl scope. Zip up the scope tree until
5699 // we find one that is.
5700 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5701 (S->getFlags() & Scope::TemplateParamScope) != 0)
5702 S = S->getParent();
5703
5704 DeclContext *DC = CurContext;
5705 if (D.getCXXScopeSpec().isInvalid())
5706 D.setInvalidType();
5707 else if (D.getCXXScopeSpec().isSet()) {
5708 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5709 UPPC_DeclarationQualifier))
5710 return nullptr;
5711
5712 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5713 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5714 if (!DC || isa<EnumDecl>(DC)) {
5715 // If we could not compute the declaration context, it's because the
5716 // declaration context is dependent but does not refer to a class,
5717 // class template, or class template partial specialization. Complain
5718 // and return early, to avoid the coming semantic disaster.
5719 Diag(D.getIdentifierLoc(),
5720 diag::err_template_qualified_declarator_no_match)
5721 << D.getCXXScopeSpec().getScopeRep()
5722 << D.getCXXScopeSpec().getRange();
5723 return nullptr;
5724 }
5725 bool IsDependentContext = DC->isDependentContext();
5726
5727 if (!IsDependentContext &&
5728 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5729 return nullptr;
5730
5731 // If a class is incomplete, do not parse entities inside it.
5732 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5733 Diag(D.getIdentifierLoc(),
5734 diag::err_member_def_undefined_record)
5735 << Name << DC << D.getCXXScopeSpec().getRange();
5736 return nullptr;
5737 }
5738 if (!D.getDeclSpec().isFriendSpecified()) {
5739 if (diagnoseQualifiedDeclaration(
5740 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5741 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5742 if (DC->isRecord())
5743 return nullptr;
5744
5745 D.setInvalidType();
5746 }
5747 }
5748
5749 // Check whether we need to rebuild the type of the given
5750 // declaration in the current instantiation.
5751 if (EnteringContext && IsDependentContext &&
5752 TemplateParamLists.size() != 0) {
5753 ContextRAII SavedContext(*this, DC);
5754 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5755 D.setInvalidType();
5756 }
5757 }
5758
5759 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5760 QualType R = TInfo->getType();
5761
5762 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5763 UPPC_DeclarationType))
5764 D.setInvalidType();
5765
5766 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5767 forRedeclarationInCurContext());
5768
5769 // See if this is a redefinition of a variable in the same scope.
5770 if (!D.getCXXScopeSpec().isSet()) {
5771 bool IsLinkageLookup = false;
5772 bool CreateBuiltins = false;
5773
5774 // If the declaration we're planning to build will be a function
5775 // or object with linkage, then look for another declaration with
5776 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5777 //
5778 // If the declaration we're planning to build will be declared with
5779 // external linkage in the translation unit, create any builtin with
5780 // the same name.
5781 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5782 /* Do nothing*/;
5783 else if (CurContext->isFunctionOrMethod() &&
5784 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5785 R->isFunctionType())) {
5786 IsLinkageLookup = true;
5787 CreateBuiltins =
5788 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5789 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5790 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5791 CreateBuiltins = true;
5792
5793 if (IsLinkageLookup) {
5794 Previous.clear(LookupRedeclarationWithLinkage);
5795 Previous.setRedeclarationKind(ForExternalRedeclaration);
5796 }
5797
5798 LookupName(Previous, S, CreateBuiltins);
5799 } else { // Something like "int foo::x;"
5800 LookupQualifiedName(Previous, DC);
5801
5802 // C++ [dcl.meaning]p1:
5803 // When the declarator-id is qualified, the declaration shall refer to a
5804 // previously declared member of the class or namespace to which the
5805 // qualifier refers (or, in the case of a namespace, of an element of the
5806 // inline namespace set of that namespace (7.3.1)) or to a specialization
5807 // thereof; [...]
5808 //
5809 // Note that we already checked the context above, and that we do not have
5810 // enough information to make sure that Previous contains the declaration
5811 // we want to match. For example, given:
5812 //
5813 // class X {
5814 // void f();
5815 // void f(float);
5816 // };
5817 //
5818 // void X::f(int) { } // ill-formed
5819 //
5820 // In this case, Previous will point to the overload set
5821 // containing the two f's declared in X, but neither of them
5822 // matches.
5823
5824 // C++ [dcl.meaning]p1:
5825 // [...] the member shall not merely have been introduced by a
5826 // using-declaration in the scope of the class or namespace nominated by
5827 // the nested-name-specifier of the declarator-id.
5828 RemoveUsingDecls(Previous);
5829 }
5830
5831 if (Previous.isSingleResult() &&
5832 Previous.getFoundDecl()->isTemplateParameter()) {
5833 // Maybe we will complain about the shadowed template parameter.
5834 if (!D.isInvalidType())
5835 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5836 Previous.getFoundDecl());
5837
5838 // Just pretend that we didn't see the previous declaration.
5839 Previous.clear();
5840 }
5841
5842 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5843 // Forget that the previous declaration is the injected-class-name.
5844 Previous.clear();
5845
5846 // In C++, the previous declaration we find might be a tag type
5847 // (class or enum). In this case, the new declaration will hide the
5848 // tag type. Note that this applies to functions, function templates, and
5849 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5850 if (Previous.isSingleTagDecl() &&
5851 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5852 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5853 Previous.clear();
5854
5855 // Check that there are no default arguments other than in the parameters
5856 // of a function declaration (C++ only).
5857 if (getLangOpts().CPlusPlus)
5858 CheckExtraCXXDefaultArguments(D);
5859
5860 NamedDecl *New;
5861
5862 bool AddToScope = true;
5863 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5864 if (TemplateParamLists.size()) {
5865 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5866 return nullptr;
5867 }
5868
5869 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5870 } else if (R->isFunctionType()) {
5871 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5872 TemplateParamLists,
5873 AddToScope);
5874 } else {
5875 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5876 AddToScope);
5877 }
5878
5879 if (!New)
5880 return nullptr;
5881
5882 // If this has an identifier and is not a function template specialization,
5883 // add it to the scope stack.
5884 if (New->getDeclName() && AddToScope)
5885 PushOnScopeChains(New, S);
5886
5887 if (isInOpenMPDeclareTargetContext())
5888 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5889
5890 return New;
5891}
5892
5893/// Helper method to turn variable array types into constant array
5894/// types in certain situations which would otherwise be errors (for
5895/// GCC compatibility).
5896static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5897 ASTContext &Context,
5898 bool &SizeIsNegative,
5899 llvm::APSInt &Oversized) {
5900 // This method tries to turn a variable array into a constant
5901 // array even when the size isn't an ICE. This is necessary
5902 // for compatibility with code that depends on gcc's buggy
5903 // constant expression folding, like struct {char x[(int)(char*)2];}
5904 SizeIsNegative = false;
5905 Oversized = 0;
5906
5907 if (T->isDependentType())
5908 return QualType();
5909
5910 QualifierCollector Qs;
5911 const Type *Ty = Qs.strip(T);
5912
5913 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5914 QualType Pointee = PTy->getPointeeType();
5915 QualType FixedType =
5916 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5917 Oversized);
5918 if (FixedType.isNull()) return FixedType;
5919 FixedType = Context.getPointerType(FixedType);
5920 return Qs.apply(Context, FixedType);
5921 }
5922 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5923 QualType Inner = PTy->getInnerType();
5924 QualType FixedType =
5925 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5926 Oversized);
5927 if (FixedType.isNull()) return FixedType;
5928 FixedType = Context.getParenType(FixedType);
5929 return Qs.apply(Context, FixedType);
5930 }
5931
5932 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5933 if (!VLATy)
5934 return QualType();
5935
5936 QualType ElemTy = VLATy->getElementType();
5937 if (ElemTy->isVariablyModifiedType()) {
5938 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
5939 SizeIsNegative, Oversized);
5940 if (ElemTy.isNull())
5941 return QualType();
5942 }
5943
5944 Expr::EvalResult Result;
5945 if (!VLATy->getSizeExpr() ||
5946 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5947 return QualType();
5948
5949 llvm::APSInt Res = Result.Val.getInt();
5950
5951 // Check whether the array size is negative.
5952 if (Res.isSigned() && Res.isNegative()) {
5953 SizeIsNegative = true;
5954 return QualType();
5955 }
5956
5957 // Check whether the array is too large to be addressed.
5958 unsigned ActiveSizeBits =
5959 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
5960 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
5961 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
5962 : Res.getActiveBits();
5963 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5964 Oversized = Res;
5965 return QualType();
5966 }
5967
5968 return Context.getConstantArrayType(ElemTy, Res, VLATy->getSizeExpr(),
5969 ArrayType::Normal, 0);
5970}
5971
5972static void
5973FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5974 SrcTL = SrcTL.getUnqualifiedLoc();
5975 DstTL = DstTL.getUnqualifiedLoc();
5976 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5977 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5978 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5979 DstPTL.getPointeeLoc());
5980 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5981 return;
5982 }
5983 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5984 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5985 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5986 DstPTL.getInnerLoc());
5987 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5988 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5989 return;
5990 }
5991 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5992 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5993 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5994 TypeLoc DstElemTL = DstATL.getElementLoc();
5995 if (VariableArrayTypeLoc SrcElemATL =
5996 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
5997 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
5998 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
5999 } else {
6000 DstElemTL.initializeFullCopy(SrcElemTL);
6001 }
6002 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6003 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6004 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6005}
6006
6007/// Helper method to turn variable array types into constant array
6008/// types in certain situations which would otherwise be errors (for
6009/// GCC compatibility).
6010static TypeSourceInfo*
6011TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6012 ASTContext &Context,
6013 bool &SizeIsNegative,
6014 llvm::APSInt &Oversized) {
6015 QualType FixedTy
6016 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6017 SizeIsNegative, Oversized);
6018 if (FixedTy.isNull())
6019 return nullptr;
6020 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6021 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6022 FixedTInfo->getTypeLoc());
6023 return FixedTInfo;
6024}
6025
6026/// Register the given locally-scoped extern "C" declaration so
6027/// that it can be found later for redeclarations. We include any extern "C"
6028/// declaration that is not visible in the translation unit here, not just
6029/// function-scope declarations.
6030void
6031Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6032 if (!getLangOpts().CPlusPlus &&
6033 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6034 // Don't need to track declarations in the TU in C.
6035 return;
6036
6037 // Note that we have a locally-scoped external with this name.
6038 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6039}
6040
6041NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6042 // FIXME: We can have multiple results via __attribute__((overloadable)).
6043 auto Result = Context.getExternCContextDecl()->lookup(Name);
6044 return Result.empty() ? nullptr : *Result.begin();
6045}
6046
6047/// Diagnose function specifiers on a declaration of an identifier that
6048/// does not identify a function.
6049void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6050 // FIXME: We should probably indicate the identifier in question to avoid
6051 // confusion for constructs like "virtual int a(), b;"
6052 if (DS.isVirtualSpecified())
6053 Diag(DS.getVirtualSpecLoc(),
6054 diag::err_virtual_non_function);
6055
6056 if (DS.hasExplicitSpecifier())
6057 Diag(DS.getExplicitSpecLoc(),
6058 diag::err_explicit_non_function);
6059
6060 if (DS.isNoreturnSpecified())
6061 Diag(DS.getNoreturnSpecLoc(),
6062 diag::err_noreturn_non_function);
6063}
6064
6065NamedDecl*
6066Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6067 TypeSourceInfo *TInfo, LookupResult &Previous) {
6068 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6069 if (D.getCXXScopeSpec().isSet()) {
6070 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6071 << D.getCXXScopeSpec().getRange();
6072 D.setInvalidType();
6073 // Pretend we didn't see the scope specifier.
6074 DC = CurContext;
6075 Previous.clear();
6076 }
6077
6078 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6079
6080 if (D.getDeclSpec().isInlineSpecified())
6081 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6082 << getLangOpts().CPlusPlus17;
6083 if (D.getDeclSpec().hasConstexprSpecifier())
6084 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6085 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6086
6087 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6088 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6089 Diag(D.getName().StartLocation,
6090 diag::err_deduction_guide_invalid_specifier)
6091 << "typedef";
6092 else
6093 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6094 << D.getName().getSourceRange();
6095 return nullptr;
6096 }
6097
6098 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6099 if (!NewTD) return nullptr;
6100
6101 // Handle attributes prior to checking for duplicates in MergeVarDecl
6102 ProcessDeclAttributes(S, NewTD, D);
6103
6104 CheckTypedefForVariablyModifiedType(S, NewTD);
6105
6106 bool Redeclaration = D.isRedeclaration();
6107 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6108 D.setRedeclaration(Redeclaration);
6109 return ND;
6110}
6111
6112void
6113Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6114 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6115 // then it shall have block scope.
6116 // Note that variably modified types must be fixed before merging the decl so
6117 // that redeclarations will match.
6118 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6119 QualType T = TInfo->getType();
6120 if (T->isVariablyModifiedType()) {
6121 setFunctionHasBranchProtectedScope();
6122
6123 if (S->getFnParent() == nullptr) {
6124 bool SizeIsNegative;
6125 llvm::APSInt Oversized;
6126 TypeSourceInfo *FixedTInfo =
6127 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6128 SizeIsNegative,
6129 Oversized);
6130 if (FixedTInfo) {
6131 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6132 NewTD->setTypeSourceInfo(FixedTInfo);
6133 } else {
6134 if (SizeIsNegative)
6135 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6136 else if (T->isVariableArrayType())
6137 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6138 else if (Oversized.getBoolValue())
6139 Diag(NewTD->getLocation(), diag::err_array_too_large)
6140 << Oversized.toString(10);
6141 else
6142 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6143 NewTD->setInvalidDecl();
6144 }
6145 }
6146 }
6147}
6148
6149/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6150/// declares a typedef-name, either using the 'typedef' type specifier or via
6151/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6152NamedDecl*
6153Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6154 LookupResult &Previous, bool &Redeclaration) {
6155
6156 // Find the shadowed declaration before filtering for scope.
6157 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6158
6159 // Merge the decl with the existing one if appropriate. If the decl is
6160 // in an outer scope, it isn't the same thing.
6161 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6162 /*AllowInlineNamespace*/false);
6163 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6164 if (!Previous.empty()) {
6165 Redeclaration = true;
6166 MergeTypedefNameDecl(S, NewTD, Previous);
6167 } else {
6168 inferGslPointerAttribute(NewTD);
6169 }
6170
6171 if (ShadowedDecl && !Redeclaration)
6172 CheckShadow(NewTD, ShadowedDecl, Previous);
6173
6174 // If this is the C FILE type, notify the AST context.
6175 if (IdentifierInfo *II = NewTD->getIdentifier())
6176 if (!NewTD->isInvalidDecl() &&
6177 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6178 if (II->isStr("FILE"))
6179 Context.setFILEDecl(NewTD);
6180 else if (II->isStr("jmp_buf"))
6181 Context.setjmp_bufDecl(NewTD);
6182 else if (II->isStr("sigjmp_buf"))
6183 Context.setsigjmp_bufDecl(NewTD);
6184 else if (II->isStr("ucontext_t"))
6185 Context.setucontext_tDecl(NewTD);
6186 }
6187
6188 return NewTD;
6189}
6190
6191/// Determines whether the given declaration is an out-of-scope
6192/// previous declaration.
6193///
6194/// This routine should be invoked when name lookup has found a
6195/// previous declaration (PrevDecl) that is not in the scope where a
6196/// new declaration by the same name is being introduced. If the new
6197/// declaration occurs in a local scope, previous declarations with
6198/// linkage may still be considered previous declarations (C99
6199/// 6.2.2p4-5, C++ [basic.link]p6).
6200///
6201/// \param PrevDecl the previous declaration found by name
6202/// lookup
6203///
6204/// \param DC the context in which the new declaration is being
6205/// declared.
6206///
6207/// \returns true if PrevDecl is an out-of-scope previous declaration
6208/// for a new delcaration with the same name.
6209static bool
6210isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6211 ASTContext &Context) {
6212 if (!PrevDecl)
6213 return false;
6214
6215 if (!PrevDecl->hasLinkage())
6216 return false;
6217
6218 if (Context.getLangOpts().CPlusPlus) {
6219 // C++ [basic.link]p6:
6220 // If there is a visible declaration of an entity with linkage
6221 // having the same name and type, ignoring entities declared
6222 // outside the innermost enclosing namespace scope, the block
6223 // scope declaration declares that same entity and receives the
6224 // linkage of the previous declaration.
6225 DeclContext *OuterContext = DC->getRedeclContext();
6226 if (!OuterContext->isFunctionOrMethod())
6227 // This rule only applies to block-scope declarations.
6228 return false;
6229
6230 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6231 if (PrevOuterContext->isRecord())
6232 // We found a member function: ignore it.
6233 return false;
6234
6235 // Find the innermost enclosing namespace for the new and
6236 // previous declarations.
6237 OuterContext = OuterContext->getEnclosingNamespaceContext();
6238 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6239
6240 // The previous declaration is in a different namespace, so it
6241 // isn't the same function.
6242 if (!OuterContext->Equals(PrevOuterContext))
6243 return false;
6244 }
6245
6246 return true;
6247}
6248
6249static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6250 CXXScopeSpec &SS = D.getCXXScopeSpec();
6251 if (!SS.isSet()) return;
6252 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6253}
6254
6255bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6256 QualType type = decl->getType();
6257 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6258 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6259 // Various kinds of declaration aren't allowed to be __autoreleasing.
6260 unsigned kind = -1U;
6261 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6262 if (var->hasAttr<BlocksAttr>())
6263 kind = 0; // __block
6264 else if (!var->hasLocalStorage())
6265 kind = 1; // global
6266 } else if (isa<ObjCIvarDecl>(decl)) {
6267 kind = 3; // ivar
6268 } else if (isa<FieldDecl>(decl)) {
6269 kind = 2; // field
6270 }
6271
6272 if (kind != -1U) {
6273 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6274 << kind;
6275 }
6276 } else if (lifetime == Qualifiers::OCL_None) {
6277 // Try to infer lifetime.
6278 if (!type->isObjCLifetimeType())
6279 return false;
6280
6281 lifetime = type->getObjCARCImplicitLifetime();
6282 type = Context.getLifetimeQualifiedType(type, lifetime);
6283 decl->setType(type);
6284 }
6285
6286 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6287 // Thread-local variables cannot have lifetime.
6288 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6289 var->getTLSKind()) {
6290 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6291 << var->getType();
6292 return true;
6293 }
6294 }
6295
6296 return false;
6297}
6298
6299void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6300 if (Decl->getType().hasAddressSpace())
6301 return;
6302 if (Decl->getType()->isDependentType())
6303 return;
6304 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6305 QualType Type = Var->getType();
6306 if (Type->isSamplerT() || Type->isVoidType())
6307 return;
6308 LangAS ImplAS = LangAS::opencl_private;
6309 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6310 Var->hasGlobalStorage())
6311 ImplAS = LangAS::opencl_global;
6312 // If the original type from a decayed type is an array type and that array
6313 // type has no address space yet, deduce it now.
6314 if (auto DT = dyn_cast<DecayedType>(Type)) {
6315 auto OrigTy = DT->getOriginalType();
6316 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6317 // Add the address space to the original array type and then propagate
6318 // that to the element type through `getAsArrayType`.
6319 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6320 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6321 // Re-generate the decayed type.
6322 Type = Context.getDecayedType(OrigTy);
6323 }
6324 }
6325 Type = Context.getAddrSpaceQualType(Type, ImplAS);
6326 // Apply any qualifiers (including address space) from the array type to
6327 // the element type. This implements C99 6.7.3p8: "If the specification of
6328 // an array type includes any type qualifiers, the element type is so
6329 // qualified, not the array type."
6330 if (Type->isArrayType())
6331 Type = QualType(Context.getAsArrayType(Type), 0);
6332 Decl->setType(Type);
6333 }
6334}
6335
6336static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6337 // Ensure that an auto decl is deduced otherwise the checks below might cache
6338 // the wrong linkage.
6339 assert(S.ParsingInitForAutoVars.count(&ND) == 0)((S.ParsingInitForAutoVars.count(&ND) == 0) ? static_cast
<void> (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 6339, __PRETTY_FUNCTION__))
;
6340
6341 // 'weak' only applies to declarations with external linkage.
6342 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6343 if (!ND.isExternallyVisible()) {
6344 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6345 ND.dropAttr<WeakAttr>();
6346 }
6347 }
6348 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6349 if (ND.isExternallyVisible()) {
6350 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6351 ND.dropAttr<WeakRefAttr>();
6352 ND.dropAttr<AliasAttr>();
6353 }
6354 }
6355
6356 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6357 if (VD->hasInit()) {
6358 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6359 assert(VD->isThisDeclarationADefinition() &&((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible
() && "Broken AliasAttr handled late!") ? static_cast
<void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 6360, __PRETTY_FUNCTION__))
6360 !VD->isExternallyVisible() && "Broken AliasAttr handled late!")((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible
() && "Broken AliasAttr handled late!") ? static_cast
<void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 6360, __PRETTY_FUNCTION__))
;
6361 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6362 VD->dropAttr<AliasAttr>();
6363 }
6364 }
6365 }
6366
6367 // 'selectany' only applies to externally visible variable declarations.
6368 // It does not apply to functions.
6369 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6370 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6371 S.Diag(Attr->getLocation(),
6372 diag::err_attribute_selectany_non_extern_data);
6373 ND.dropAttr<SelectAnyAttr>();
6374 }
6375 }
6376
6377 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6378 auto *VD = dyn_cast<VarDecl>(&ND);
6379 bool IsAnonymousNS = false;
6380 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6381 if (VD) {
6382 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6383 while (NS && !IsAnonymousNS) {
6384 IsAnonymousNS = NS->isAnonymousNamespace();
6385 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6386 }
6387 }
6388 // dll attributes require external linkage. Static locals may have external
6389 // linkage but still cannot be explicitly imported or exported.
6390 // In Microsoft mode, a variable defined in anonymous namespace must have
6391 // external linkage in order to be exported.
6392 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6393 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6394 (!AnonNSInMicrosoftMode &&
6395 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6396 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6397 << &ND << Attr;
6398 ND.setInvalidDecl();
6399 }
6400 }
6401
6402 // Virtual functions cannot be marked as 'notail'.
6403 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6404 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6405 if (MD->isVirtual()) {
6406 S.Diag(ND.getLocation(),
6407 diag::err_invalid_attribute_on_virtual_function)
6408 << Attr;
6409 ND.dropAttr<NotTailCalledAttr>();
6410 }
6411
6412 // Check the attributes on the function type, if any.
6413 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6414 // Don't declare this variable in the second operand of the for-statement;
6415 // GCC miscompiles that by ending its lifetime before evaluating the
6416 // third operand. See gcc.gnu.org/PR86769.
6417 AttributedTypeLoc ATL;
6418 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6419 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6420 TL = ATL.getModifiedLoc()) {
6421 // The [[lifetimebound]] attribute can be applied to the implicit object
6422 // parameter of a non-static member function (other than a ctor or dtor)
6423 // by applying it to the function type.
6424 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6425 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6426 if (!MD || MD->isStatic()) {
6427 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6428 << !MD << A->getRange();
6429 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6430 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6431 << isa<CXXDestructorDecl>(MD) << A->getRange();
6432 }
6433 }
6434 }
6435 }
6436}
6437
6438static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6439 NamedDecl *NewDecl,
6440 bool IsSpecialization,
6441 bool IsDefinition) {
6442 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6443 return;
6444
6445 bool IsTemplate = false;
6446 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6447 OldDecl = OldTD->getTemplatedDecl();
6448 IsTemplate = true;
6449 if (!IsSpecialization)
6450 IsDefinition = false;
6451 }
6452 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6453 NewDecl = NewTD->getTemplatedDecl();
6454 IsTemplate = true;
6455 }
6456
6457 if (!OldDecl || !NewDecl)
6458 return;
6459
6460 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6461 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6462 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6463 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6464
6465 // dllimport and dllexport are inheritable attributes so we have to exclude
6466 // inherited attribute instances.
6467 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6468 (NewExportAttr && !NewExportAttr->isInherited());
6469
6470 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6471 // the only exception being explicit specializations.
6472 // Implicitly generated declarations are also excluded for now because there
6473 // is no other way to switch these to use dllimport or dllexport.
6474 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6475
6476 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6477 // Allow with a warning for free functions and global variables.
6478 bool JustWarn = false;
6479 if (!OldDecl->isCXXClassMember()) {
6480 auto *VD = dyn_cast<VarDecl>(OldDecl);
6481 if (VD && !VD->getDescribedVarTemplate())
6482 JustWarn = true;
6483 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6484 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6485 JustWarn = true;
6486 }
6487
6488 // We cannot change a declaration that's been used because IR has already
6489 // been emitted. Dllimported functions will still work though (modulo
6490 // address equality) as they can use the thunk.
6491 if (OldDecl->isUsed())
6492 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6493 JustWarn = false;
6494
6495 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6496 : diag::err_attribute_dll_redeclaration;
6497 S.Diag(NewDecl->getLocation(), DiagID)
6498 << NewDecl
6499 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6500 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6501 if (!JustWarn) {
6502 NewDecl->setInvalidDecl();
6503 return;
6504 }
6505 }
6506
6507 // A redeclaration is not allowed to drop a dllimport attribute, the only
6508 // exceptions being inline function definitions (except for function
6509 // templates), local extern declarations, qualified friend declarations or
6510 // special MSVC extension: in the last case, the declaration is treated as if
6511 // it were marked dllexport.
6512 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6513 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6514 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6515 // Ignore static data because out-of-line definitions are diagnosed
6516 // separately.
6517 IsStaticDataMember = VD->isStaticDataMember();
6518 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6519 VarDecl::DeclarationOnly;
6520 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6521 IsInline = FD->isInlined();
6522 IsQualifiedFriend = FD->getQualifier() &&
6523 FD->getFriendObjectKind() == Decl::FOK_Declared;
6524 }
6525
6526 if (OldImportAttr && !HasNewAttr &&
6527 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6528 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6529 if (IsMicrosoftABI && IsDefinition) {
6530 S.Diag(NewDecl->getLocation(),
6531 diag::warn_redeclaration_without_import_attribute)
6532 << NewDecl;
6533 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6534 NewDecl->dropAttr<DLLImportAttr>();
6535 NewDecl->addAttr(
6536 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6537 } else {
6538 S.Diag(NewDecl->getLocation(),
6539 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6540 << NewDecl << OldImportAttr;
6541 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6542 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6543 OldDecl->dropAttr<DLLImportAttr>();
6544 NewDecl->dropAttr<DLLImportAttr>();
6545 }
6546 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6547 // In MinGW, seeing a function declared inline drops the dllimport
6548 // attribute.
6549 OldDecl->dropAttr<DLLImportAttr>();
6550 NewDecl->dropAttr<DLLImportAttr>();
6551 S.Diag(NewDecl->getLocation(),
6552 diag::warn_dllimport_dropped_from_inline_function)
6553 << NewDecl << OldImportAttr;
6554 }
6555
6556 // A specialization of a class template member function is processed here
6557 // since it's a redeclaration. If the parent class is dllexport, the
6558 // specialization inherits that attribute. This doesn't happen automatically
6559 // since the parent class isn't instantiated until later.
6560 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6561 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6562 !NewImportAttr && !NewExportAttr) {
6563 if (const DLLExportAttr *ParentExportAttr =
6564 MD->getParent()->getAttr<DLLExportAttr>()) {
6565 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6566 NewAttr->setInherited(true);
6567 NewDecl->addAttr(NewAttr);
6568 }
6569 }
6570 }
6571}
6572
6573/// Given that we are within the definition of the given function,
6574/// will that definition behave like C99's 'inline', where the
6575/// definition is discarded except for optimization purposes?
6576static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6577 // Try to avoid calling GetGVALinkageForFunction.
6578
6579 // All cases of this require the 'inline' keyword.
6580 if (!FD->isInlined()) return false;
6581
6582 // This is only possible in C++ with the gnu_inline attribute.
6583 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6584 return false;
6585
6586 // Okay, go ahead and call the relatively-more-expensive function.
6587 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6588}
6589
6590/// Determine whether a variable is extern "C" prior to attaching
6591/// an initializer. We can't just call isExternC() here, because that
6592/// will also compute and cache whether the declaration is externally
6593/// visible, which might change when we attach the initializer.
6594///
6595/// This can only be used if the declaration is known to not be a
6596/// redeclaration of an internal linkage declaration.
6597///
6598/// For instance:
6599///
6600/// auto x = []{};
6601///
6602/// Attaching the initializer here makes this declaration not externally
6603/// visible, because its type has internal linkage.
6604///
6605/// FIXME: This is a hack.
6606template<typename T>
6607static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6608 if (S.getLangOpts().CPlusPlus) {
6609 // In C++, the overloadable attribute negates the effects of extern "C".
6610 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6611 return false;
6612
6613 // So do CUDA's host/device attributes.
6614 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6615 D->template hasAttr<CUDAHostAttr>()))
6616 return false;
6617 }
6618 return D->isExternC();
6619}
6620
6621static bool shouldConsiderLinkage(const VarDecl *VD) {
6622 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6623 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6624 isa<OMPDeclareMapperDecl>(DC))
6625 return VD->hasExternalStorage();
6626 if (DC->isFileContext())
6627 return true;
6628 if (DC->isRecord())
6629 return false;
6630 if (isa<RequiresExprBodyDecl>(DC))
6631 return false;
6632 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 6632)
;
6633}
6634
6635static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6636 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6637 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6638 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6639 return true;
6640 if (DC->isRecord())
6641 return false;
6642 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 6642)
;
6643}
6644
6645static bool hasParsedAttr(Scope *S, const Declarator &PD,
6646 ParsedAttr::Kind Kind) {
6647 // Check decl attributes on the DeclSpec.
6648 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6649 return true;
6650
6651 // Walk the declarator structure, checking decl attributes that were in a type
6652 // position to the decl itself.
6653 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6654 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6655 return true;
6656 }
6657
6658 // Finally, check attributes on the decl itself.
6659 return PD.getAttributes().hasAttribute(Kind);
6660}
6661
6662/// Adjust the \c DeclContext for a function or variable that might be a
6663/// function-local external declaration.
6664bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6665 if (!DC->isFunctionOrMethod())
6666 return false;
6667
6668 // If this is a local extern function or variable declared within a function
6669 // template, don't add it into the enclosing namespace scope until it is
6670 // instantiated; it might have a dependent type right now.
6671 if (DC->isDependentContext())
6672 return true;
6673
6674 // C++11 [basic.link]p7:
6675 // When a block scope declaration of an entity with linkage is not found to
6676 // refer to some other declaration, then that entity is a member of the
6677 // innermost enclosing namespace.
6678 //
6679 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6680 // semantically-enclosing namespace, not a lexically-enclosing one.
6681 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6682 DC = DC->getParent();
6683 return true;
6684}
6685
6686/// Returns true if given declaration has external C language linkage.
6687static bool isDeclExternC(const Decl *D) {
6688 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6689 return FD->isExternC();
6690 if (const auto *VD = dyn_cast<VarDecl>(D))
6691 return VD->isExternC();
6692
6693 llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 6693)
;
6694}
6695/// Returns true if there hasn't been any invalid type diagnosed.
6696static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6697 DeclContext *DC, QualType R) {
6698 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6699 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6700 // argument.
6701 if (R->isImageType() || R->isPipeType()) {
6702 Se.Diag(D.getIdentifierLoc(),
6703 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6704 << R;
6705 D.setInvalidType();
6706 return false;
6707 }
6708
6709 // OpenCL v1.2 s6.9.r:
6710 // The event type cannot be used to declare a program scope variable.
6711 // OpenCL v2.0 s6.9.q:
6712 // The clk_event_t and reserve_id_t types cannot be declared in program
6713 // scope.
6714 if (NULL__null == S->getParent()) {
6715 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6716 Se.Diag(D.getIdentifierLoc(),
6717 diag::err_invalid_type_for_program_scope_var)
6718 << R;
6719 D.setInvalidType();
6720 return false;
6721 }
6722 }
6723
6724 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6725 QualType NR = R;
6726 while (NR->isPointerType()) {
6727 if (NR->isFunctionPointerType()) {
6728 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6729 D.setInvalidType();
6730 return false;
6731 }
6732 NR = NR->getPointeeType();
6733 }
6734
6735 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6736 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6737 // half array type (unless the cl_khr_fp16 extension is enabled).
6738 if (Se.Context.getBaseElementType(R)->isHalfType()) {
6739 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6740 D.setInvalidType();
6741 return false;
6742 }
6743 }
6744
6745 // OpenCL v1.2 s6.9.r:
6746 // The event type cannot be used with the __local, __constant and __global
6747 // address space qualifiers.
6748 if (R->isEventT()) {
6749 if (R.getAddressSpace() != LangAS::opencl_private) {
6750 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6751 D.setInvalidType();
6752 return false;
6753 }
6754 }
6755
6756 // C++ for OpenCL does not allow the thread_local storage qualifier.
6757 // OpenCL C does not support thread_local either, and
6758 // also reject all other thread storage class specifiers.
6759 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6760 if (TSC != TSCS_unspecified) {
6761 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6762 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6763 diag::err_opencl_unknown_type_specifier)
6764 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6765 << DeclSpec::getSpecifierName(TSC) << 1;
6766 D.setInvalidType();
6767 return false;
6768 }
6769
6770 if (R->isSamplerT()) {
6771 // OpenCL v1.2 s6.9.b p4:
6772 // The sampler type cannot be used with the __local and __global address
6773 // space qualifiers.
6774 if (R.getAddressSpace() == LangAS::opencl_local ||
6775 R.getAddressSpace() == LangAS::opencl_global) {
6776 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6777 D.setInvalidType();
6778 }
6779
6780 // OpenCL v1.2 s6.12.14.1:
6781 // A global sampler must be declared with either the constant address
6782 // space qualifier or with the const qualifier.
6783 if (DC->isTranslationUnit() &&
6784 !(R.getAddressSpace() == LangAS::opencl_constant ||
6785 R.isConstQualified())) {
6786 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6787 D.setInvalidType();
6788 }
6789 if (D.isInvalidType())
6790 return false;
6791 }
6792 return true;
6793}
6794
6795NamedDecl *Sema::ActOnVariableDeclarator(
6796 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6797 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6798 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6799 QualType R = TInfo->getType();
6800 DeclarationName Name = GetNameForDeclarator(D).getName();
6801
6802 IdentifierInfo *II = Name.getAsIdentifierInfo();
6803
6804 if (D.isDecompositionDeclarator()) {
6805 // Take the name of the first declarator as our name for diagnostic
6806 // purposes.
6807 auto &Decomp = D.getDecompositionDeclarator();
6808 if (!Decomp.bindings().empty()) {
6809 II = Decomp.bindings()[0].Name;
6810 Name = II;
6811 }
6812 } else if (!II) {
6813 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6814 return nullptr;
6815 }
6816
6817
6818 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6819 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6820
6821 // dllimport globals without explicit storage class are treated as extern. We
6822 // have to change the storage class this early to get the right DeclContext.
6823 if (SC == SC_None && !DC->isRecord() &&
6824 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6825 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6826 SC = SC_Extern;
6827
6828 DeclContext *OriginalDC = DC;
6829 bool IsLocalExternDecl = SC == SC_Extern &&
6830 adjustContextForLocalExternDecl(DC);
6831
6832 if (SCSpec == DeclSpec::SCS_mutable) {
6833 // mutable can only appear on non-static class members, so it's always
6834 // an error here
6835 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6836 D.setInvalidType();
6837 SC = SC_None;
6838 }
6839
6840 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6841 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6842 D.getDeclSpec().getStorageClassSpecLoc())) {
6843 // In C++11, the 'register' storage class specifier is deprecated.
6844 // Suppress the warning in system macros, it's used in macros in some
6845 // popular C system headers, such as in glibc's htonl() macro.
6846 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6847 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6848 : diag::warn_deprecated_register)
6849 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6850 }
6851
6852 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6853
6854 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6855 // C99 6.9p2: The storage-class specifiers auto and register shall not
6856 // appear in the declaration specifiers in an external declaration.
6857 // Global Register+Asm is a GNU extension we support.
6858 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6859 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6860 D.setInvalidType();
6861 }
6862 }
6863
6864 bool IsMemberSpecialization = false;
6865 bool IsVariableTemplateSpecialization = false;
6866 bool IsPartialSpecialization = false;
6867 bool IsVariableTemplate = false;
6868 VarDecl *NewVD = nullptr;
6869 VarTemplateDecl *NewTemplate = nullptr;
6870 TemplateParameterList *TemplateParams = nullptr;
6871 if (!getLangOpts().CPlusPlus) {
6872 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6873 II, R, TInfo, SC);
6874
6875 if (R->getContainedDeducedType())
6876 ParsingInitForAutoVars.insert(NewVD);
6877
6878 if (D.isInvalidType())
6879 NewVD->setInvalidDecl();
6880
6881 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6882 NewVD->hasLocalStorage())
6883 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6884 NTCUC_AutoVar, NTCUK_Destruct);
6885 } else {
6886 bool Invalid = false;
6887
6888 if (DC->isRecord() && !CurContext->isRecord()) {
6889 // This is an out-of-line definition of a static data member.
6890 switch (SC) {
6891 case SC_None:
6892 break;
6893 case SC_Static:
6894 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6895 diag::err_static_out_of_line)
6896 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6897 break;
6898 case SC_Auto:
6899 case SC_Register:
6900 case SC_Extern:
6901 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6902 // to names of variables declared in a block or to function parameters.
6903 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6904 // of class members
6905
6906 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6907 diag::err_storage_class_for_static_member)
6908 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6909 break;
6910 case SC_PrivateExtern:
6911 llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 6911)
;
6912 }
6913 }
6914
6915 if (SC == SC_Static && CurContext->isRecord()) {
6916 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6917 // Walk up the enclosing DeclContexts to check for any that are
6918 // incompatible with static data members.
6919 const DeclContext *FunctionOrMethod = nullptr;
6920 const CXXRecordDecl *AnonStruct = nullptr;
6921 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6922 if (Ctxt->isFunctionOrMethod()) {
6923 FunctionOrMethod = Ctxt;
6924 break;
6925 }
6926 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6927 if (ParentDecl && !ParentDecl->getDeclName()) {
6928 AnonStruct = ParentDecl;
6929 break;
6930 }
6931 }
6932 if (FunctionOrMethod) {
6933 // C++ [class.static.data]p5: A local class shall not have static data
6934 // members.
6935 Diag(D.getIdentifierLoc(),
6936 diag::err_static_data_member_not_allowed_in_local_class)
6937 << Name << RD->getDeclName() << RD->getTagKind();
6938 } else if (AnonStruct) {
6939 // C++ [class.static.data]p4: Unnamed classes and classes contained
6940 // directly or indirectly within unnamed classes shall not contain
6941 // static data members.
6942 Diag(D.getIdentifierLoc(),
6943 diag::err_static_data_member_not_allowed_in_anon_struct)
6944 << Name << AnonStruct->getTagKind();
6945 Invalid = true;
6946 } else if (RD->isUnion()) {
6947 // C++98 [class.union]p1: If a union contains a static data member,
6948 // the program is ill-formed. C++11 drops this restriction.
6949 Diag(D.getIdentifierLoc(),
6950 getLangOpts().CPlusPlus11
6951 ? diag::warn_cxx98_compat_static_data_member_in_union
6952 : diag::ext_static_data_member_in_union) << Name;
6953 }
6954 }
6955 }
6956
6957 // Match up the template parameter lists with the scope specifier, then
6958 // determine whether we have a template or a template specialization.
6959 bool InvalidScope = false;
6960 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6961 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6962 D.getCXXScopeSpec(),
6963 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6964 ? D.getName().TemplateId
6965 : nullptr,
6966 TemplateParamLists,
6967 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6968 Invalid |= InvalidScope;
6969
6970 if (TemplateParams) {
6971 if (!TemplateParams->size() &&
6972 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6973 // There is an extraneous 'template<>' for this variable. Complain
6974 // about it, but allow the declaration of the variable.
6975 Diag(TemplateParams->getTemplateLoc(),
6976 diag::err_template_variable_noparams)
6977 << II
6978 << SourceRange(TemplateParams->getTemplateLoc(),
6979 TemplateParams->getRAngleLoc());
6980 TemplateParams = nullptr;
6981 } else {
6982 // Check that we can declare a template here.
6983 if (CheckTemplateDeclScope(S, TemplateParams))
6984 return nullptr;
6985
6986 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6987 // This is an explicit specialization or a partial specialization.
6988 IsVariableTemplateSpecialization = true;
6989 IsPartialSpecialization = TemplateParams->size() > 0;
6990 } else { // if (TemplateParams->size() > 0)
6991 // This is a template declaration.
6992 IsVariableTemplate = true;
6993
6994 // Only C++1y supports variable templates (N3651).
6995 Diag(D.getIdentifierLoc(),
6996 getLangOpts().CPlusPlus14
6997 ? diag::warn_cxx11_compat_variable_template
6998 : diag::ext_variable_template);
6999 }
7000 }
7001 } else {
7002 // Check that we can declare a member specialization here.
7003 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7004 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7005 return nullptr;
7006 assert((Invalid ||(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 7008, __PRETTY_FUNCTION__))
7007 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 7008, __PRETTY_FUNCTION__))
7008 "should have a 'template<>' for this decl")(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 7008, __PRETTY_FUNCTION__))
;
7009 }
7010
7011 if (IsVariableTemplateSpecialization) {
7012 SourceLocation TemplateKWLoc =
7013 TemplateParamLists.size() > 0
7014 ? TemplateParamLists[0]->getTemplateLoc()
7015 : SourceLocation();
7016 DeclResult Res = ActOnVarTemplateSpecialization(
7017 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7018 IsPartialSpecialization);
7019 if (Res.isInvalid())
7020 return nullptr;
7021 NewVD = cast<VarDecl>(Res.get());
7022 AddToScope = false;
7023 } else if (D.isDecompositionDeclarator()) {
7024 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7025 D.getIdentifierLoc(), R, TInfo, SC,
7026 Bindings);
7027 } else
7028 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7029 D.getIdentifierLoc(), II, R, TInfo, SC);
7030
7031 // If this is supposed to be a variable template, create it as such.
7032 if (IsVariableTemplate) {
7033 NewTemplate =
7034 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7035 TemplateParams, NewVD);
7036 NewVD->setDescribedVarTemplate(NewTemplate);
7037 }
7038
7039 // If this decl has an auto type in need of deduction, make a note of the
7040 // Decl so we can diagnose uses of it in its own initializer.
7041 if (R->getContainedDeducedType())
7042 ParsingInitForAutoVars.insert(NewVD);
7043
7044 if (D.isInvalidType() || Invalid) {
7045 NewVD->setInvalidDecl();
7046 if (NewTemplate)
7047 NewTemplate->setInvalidDecl();
7048 }
7049
7050 SetNestedNameSpecifier(*this, NewVD, D);
7051
7052 // If we have any template parameter lists that don't directly belong to
7053 // the variable (matching the scope specifier), store them.
7054 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7055 if (TemplateParamLists.size() > VDTemplateParamLists)
7056 NewVD->setTemplateParameterListsInfo(
7057 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7058 }
7059
7060 if (D.getDeclSpec().isInlineSpecified()) {
7061 if (!getLangOpts().CPlusPlus) {
7062 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7063 << 0;
7064 } else if (CurContext->isFunctionOrMethod()) {
7065 // 'inline' is not allowed on block scope variable declaration.
7066 Diag(D.getDeclSpec().getInlineSpecLoc(),
7067 diag::err_inline_declaration_block_scope) << Name
7068 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7069 } else {
7070 Diag(D.getDeclSpec().getInlineSpecLoc(),
7071 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7072 : diag::ext_inline_variable);
7073 NewVD->setInlineSpecified();
7074 }
7075 }
7076
7077 // Set the lexical context. If the declarator has a C++ scope specifier, the
7078 // lexical context will be different from the semantic context.
7079 NewVD->setLexicalDeclContext(CurContext);
7080 if (NewTemplate)
7081 NewTemplate->setLexicalDeclContext(CurContext);
7082
7083 if (IsLocalExternDecl) {
7084 if (D.isDecompositionDeclarator())
7085 for (auto *B : Bindings)
7086 B->setLocalExternDecl();
7087 else
7088 NewVD->setLocalExternDecl();
7089 }
7090
7091 bool EmitTLSUnsupportedError = false;
7092 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7093 // C++11 [dcl.stc]p4:
7094 // When thread_local is applied to a variable of block scope the
7095 // storage-class-specifier static is implied if it does not appear
7096 // explicitly.
7097 // Core issue: 'static' is not implied if the variable is declared
7098 // 'extern'.
7099 if (NewVD->hasLocalStorage() &&
7100 (SCSpec != DeclSpec::SCS_unspecified ||
7101 TSCS != DeclSpec::TSCS_thread_local ||
7102 !DC->isFunctionOrMethod()))
7103 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7104 diag::err_thread_non_global)
7105 << DeclSpec::getSpecifierName(TSCS);
7106 else if (!Context.getTargetInfo().isTLSSupported()) {
7107 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7108 getLangOpts().SYCLIsDevice) {
7109 // Postpone error emission until we've collected attributes required to
7110 // figure out whether it's a host or device variable and whether the
7111 // error should be ignored.
7112 EmitTLSUnsupportedError = true;
7113 // We still need to mark the variable as TLS so it shows up in AST with
7114 // proper storage class for other tools to use even if we're not going
7115 // to emit any code for it.
7116 NewVD->setTSCSpec(TSCS);
7117 } else
7118 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7119 diag::err_thread_unsupported);
7120 } else
7121 NewVD->setTSCSpec(TSCS);
7122 }
7123
7124 switch (D.getDeclSpec().getConstexprSpecifier()) {
7125 case ConstexprSpecKind::Unspecified:
7126 break;
7127
7128 case ConstexprSpecKind::Consteval:
7129 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7130 diag::err_constexpr_wrong_decl_kind)
7131 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7132 LLVM_FALLTHROUGH[[gnu::fallthrough]];
7133
7134 case ConstexprSpecKind::Constexpr:
7135 NewVD->setConstexpr(true);
7136 MaybeAddCUDAConstantAttr(NewVD);
7137 // C++1z [dcl.spec.constexpr]p1:
7138 // A static data member declared with the constexpr specifier is
7139 // implicitly an inline variable.
7140 if (NewVD->isStaticDataMember() &&
7141 (getLangOpts().CPlusPlus17 ||
7142 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7143 NewVD->setImplicitlyInline();
7144 break;
7145
7146 case ConstexprSpecKind::Constinit:
7147 if (!NewVD->hasGlobalStorage())
7148 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7149 diag::err_constinit_local_variable);
7150 else
7151 NewVD->addAttr(ConstInitAttr::Create(
7152 Context, D.getDeclSpec().getConstexprSpecLoc(),
7153 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7154 break;
7155 }
7156
7157 // C99 6.7.4p3
7158 // An inline definition of a function with external linkage shall
7159 // not contain a definition of a modifiable object with static or
7160 // thread storage duration...
7161 // We only apply this when the function is required to be defined
7162 // elsewhere, i.e. when the function is not 'extern inline'. Note
7163 // that a local variable with thread storage duration still has to
7164 // be marked 'static'. Also note that it's possible to get these
7165 // semantics in C++ using __attribute__((gnu_inline)).
7166 if (SC == SC_Static && S->getFnParent() != nullptr &&
7167 !NewVD->getType().isConstQualified()) {
7168 FunctionDecl *CurFD = getCurFunctionDecl();
7169 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7170 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7171 diag::warn_static_local_in_extern_inline);
7172 MaybeSuggestAddingStaticToDecl(CurFD);
7173 }
7174 }
7175
7176 if (D.getDeclSpec().isModulePrivateSpecified()) {
7177 if (IsVariableTemplateSpecialization)
7178 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7179 << (IsPartialSpecialization ? 1 : 0)
7180 << FixItHint::CreateRemoval(
7181 D.getDeclSpec().getModulePrivateSpecLoc());
7182 else if (IsMemberSpecialization)
7183 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7184 << 2
7185 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7186 else if (NewVD->hasLocalStorage())
7187 Diag(NewVD->getLocation(), diag::err_module_private_local)
7188 << 0 << NewVD
7189 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7190 << FixItHint::CreateRemoval(
7191 D.getDeclSpec().getModulePrivateSpecLoc());
7192 else {
7193 NewVD->setModulePrivate();
7194 if (NewTemplate)
7195 NewTemplate->setModulePrivate();
7196 for (auto *B : Bindings)
7197 B->setModulePrivate();
7198 }
7199 }
7200
7201 if (getLangOpts().OpenCL) {
7202
7203 deduceOpenCLAddressSpace(NewVD);
7204
7205 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7206 }
7207
7208 // Handle attributes prior to checking for duplicates in MergeVarDecl
7209 ProcessDeclAttributes(S, NewVD, D);
7210
7211 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7212 getLangOpts().SYCLIsDevice) {
7213 if (EmitTLSUnsupportedError &&
7214 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7215 (getLangOpts().OpenMPIsDevice &&
7216 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7217 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7218 diag::err_thread_unsupported);
7219
7220 if (EmitTLSUnsupportedError &&
7221 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7222 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7223 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7224 // storage [duration]."
7225 if (SC == SC_None && S->getFnParent() != nullptr &&
7226 (NewVD->hasAttr<CUDASharedAttr>() ||
7227 NewVD->hasAttr<CUDAConstantAttr>())) {
7228 NewVD->setStorageClass(SC_Static);
7229 }
7230 }
7231
7232 // Ensure that dllimport globals without explicit storage class are treated as
7233 // extern. The storage class is set above using parsed attributes. Now we can
7234 // check the VarDecl itself.
7235 assert(!NewVD->hasAttr<DLLImportAttr>() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 7237, __PRETTY_FUNCTION__))
7236 NewVD->getAttr<DLLImportAttr>()->isInherited() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 7237, __PRETTY_FUNCTION__))
7237 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 7237, __PRETTY_FUNCTION__))
;
7238
7239 // In auto-retain/release, infer strong retension for variables of
7240 // retainable type.
7241 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7242 NewVD->setInvalidDecl();
7243
7244 // Handle GNU asm-label extension (encoded as an attribute).
7245 if (Expr *E = (Expr*)D.getAsmLabel()) {
7246 // The parser guarantees this is a string.
7247 StringLiteral *SE = cast<StringLiteral>(E);
7248 StringRef Label = SE->getString();
7249 if (S->getFnParent() != nullptr) {
7250 switch (SC) {
7251 case SC_None:
7252 case SC_Auto:
7253 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7254 break;
7255 case SC_Register:
7256 // Local Named register
7257 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7258 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7259 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7260 break;
7261 case SC_Static:
7262 case SC_Extern:
7263 case SC_PrivateExtern:
7264 break;
7265 }
7266 } else if (SC == SC_Register) {
7267 // Global Named register
7268 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7269 const auto &TI = Context.getTargetInfo();
7270 bool HasSizeMismatch;
7271
7272 if (!TI.isValidGCCRegisterName(Label))
7273 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7274 else if (!TI.validateGlobalRegisterVariable(Label,
7275 Context.getTypeSize(R),
7276 HasSizeMismatch))
7277 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7278 else if (HasSizeMismatch)
7279 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7280 }
7281
7282 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7283 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7284 NewVD->setInvalidDecl(true);
7285 }
7286 }
7287
7288 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7289 /*IsLiteralLabel=*/true,
7290 SE->getStrTokenLoc(0)));
7291 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7292 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7293 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7294 if (I != ExtnameUndeclaredIdentifiers.end()) {
7295 if (isDeclExternC(NewVD)) {
7296 NewVD->addAttr(I->second);
7297 ExtnameUndeclaredIdentifiers.erase(I);
7298 } else
7299 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7300 << /*Variable*/1 << NewVD;
7301 }
7302 }
7303
7304 // Find the shadowed declaration before filtering for scope.
7305 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7306 ? getShadowedDeclaration(NewVD, Previous)
7307 : nullptr;
7308
7309 // Don't consider existing declarations that are in a different
7310 // scope and are out-of-semantic-context declarations (if the new
7311 // declaration has linkage).
7312 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7313 D.getCXXScopeSpec().isNotEmpty() ||
7314 IsMemberSpecialization ||
7315 IsVariableTemplateSpecialization);
7316
7317 // Check whether the previous declaration is in the same block scope. This
7318 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7319 if (getLangOpts().CPlusPlus &&
7320 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7321 NewVD->setPreviousDeclInSameBlockScope(
7322 Previous.isSingleResult() && !Previous.isShadowed() &&
7323 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7324
7325 if (!getLangOpts().CPlusPlus) {
7326 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7327 } else {
7328 // If this is an explicit specialization of a static data member, check it.
7329 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7330 CheckMemberSpecialization(NewVD, Previous))
7331 NewVD->setInvalidDecl();
7332
7333 // Merge the decl with the existing one if appropriate.
7334 if (!Previous.empty()) {
7335 if (Previous.isSingleResult() &&
7336 isa<FieldDecl>(Previous.getFoundDecl()) &&
7337 D.getCXXScopeSpec().isSet()) {
7338 // The user tried to define a non-static data member
7339 // out-of-line (C++ [dcl.meaning]p1).
7340 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7341 << D.getCXXScopeSpec().getRange();
7342 Previous.clear();
7343 NewVD->setInvalidDecl();
7344 }
7345 } else if (D.getCXXScopeSpec().isSet()) {
7346 // No previous declaration in the qualifying scope.
7347 Diag(D.getIdentifierLoc(), diag::err_no_member)
7348 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7349 << D.getCXXScopeSpec().getRange();
7350 NewVD->setInvalidDecl();
7351 }
7352
7353 if (!IsVariableTemplateSpecialization)
7354 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7355
7356 if (NewTemplate) {
7357 VarTemplateDecl *PrevVarTemplate =
7358 NewVD->getPreviousDecl()
7359 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7360 : nullptr;
7361
7362 // Check the template parameter list of this declaration, possibly
7363 // merging in the template parameter list from the previous variable
7364 // template declaration.
7365 if (CheckTemplateParameterList(
7366 TemplateParams,
7367 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7368 : nullptr,
7369 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7370 DC->isDependentContext())
7371 ? TPC_ClassTemplateMember
7372 : TPC_VarTemplate))
7373 NewVD->setInvalidDecl();
7374
7375 // If we are providing an explicit specialization of a static variable
7376 // template, make a note of that.
7377 if (PrevVarTemplate &&
7378 PrevVarTemplate->getInstantiatedFromMemberTemplate())
7379 PrevVarTemplate->setMemberSpecialization();
7380 }
7381 }
7382
7383 // Diagnose shadowed variables iff this isn't a redeclaration.
7384 if (ShadowedDecl && !D.isRedeclaration())
7385 CheckShadow(NewVD, ShadowedDecl, Previous);
7386
7387 ProcessPragmaWeak(S, NewVD);
7388
7389 // If this is the first declaration of an extern C variable, update
7390 // the map of such variables.
7391 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7392 isIncompleteDeclExternC(*this, NewVD))
7393 RegisterLocallyScopedExternCDecl(NewVD, S);
7394
7395 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7396 MangleNumberingContext *MCtx;
7397 Decl *ManglingContextDecl;
7398 std::tie(MCtx, ManglingContextDecl) =
7399 getCurrentMangleNumberContext(NewVD->getDeclContext());
7400 if (MCtx) {
7401 Context.setManglingNumber(
7402 NewVD, MCtx->getManglingNumber(
7403 NewVD, getMSManglingNumber(getLangOpts(), S)));
7404 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7405 }
7406 }
7407
7408 // Special handling of variable named 'main'.
7409 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7410 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7411 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7412
7413 // C++ [basic.start.main]p3
7414 // A program that declares a variable main at global scope is ill-formed.
7415 if (getLangOpts().CPlusPlus)
7416 Diag(D.getBeginLoc(), diag::err_main_global_variable);
7417
7418 // In C, and external-linkage variable named main results in undefined
7419 // behavior.
7420 else if (NewVD->hasExternalFormalLinkage())
7421 Diag(D.getBeginLoc(), diag::warn_main_redefined);
7422 }
7423
7424 if (D.isRedeclaration() && !Previous.empty()) {
7425 NamedDecl *Prev = Previous.getRepresentativeDecl();
7426 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7427 D.isFunctionDefinition());
7428 }
7429
7430 if (NewTemplate) {
7431 if (NewVD->isInvalidDecl())
7432 NewTemplate->setInvalidDecl();
7433 ActOnDocumentableDecl(NewTemplate);
7434 return NewTemplate;
7435 }
7436
7437 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7438 CompleteMemberSpecialization(NewVD, Previous);
7439
7440 return NewVD;
7441}
7442
7443/// Enum describing the %select options in diag::warn_decl_shadow.
7444enum ShadowedDeclKind {
7445 SDK_Local,
7446 SDK_Global,
7447 SDK_StaticMember,
7448 SDK_Field,
7449 SDK_Typedef,
7450 SDK_Using
7451};
7452
7453/// Determine what kind of declaration we're shadowing.
7454static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7455 const DeclContext *OldDC) {
7456 if (isa<TypeAliasDecl>(ShadowedDecl))
7457 return SDK_Using;
7458 else if (isa<TypedefDecl>(ShadowedDecl))
7459 return SDK_Typedef;
7460 else if (isa<RecordDecl>(OldDC))
7461 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7462
7463 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7464}
7465
7466/// Return the location of the capture if the given lambda captures the given
7467/// variable \p VD, or an invalid source location otherwise.
7468static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7469 const VarDecl *VD) {
7470 for (const Capture &Capture : LSI->Captures) {
7471 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7472 return Capture.getLocation();
7473 }
7474 return SourceLocation();
7475}
7476
7477static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7478 const LookupResult &R) {
7479 // Only diagnose if we're shadowing an unambiguous field or variable.
7480 if (R.getResultKind() != LookupResult::Found)
7481 return false;
7482
7483 // Return false if warning is ignored.
7484 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7485}
7486
7487/// Return the declaration shadowed by the given variable \p D, or null
7488/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7489NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7490 const LookupResult &R) {
7491 if (!shouldWarnIfShadowedDecl(Diags, R))
7492 return nullptr;
7493
7494 // Don't diagnose declarations at file scope.
7495 if (D->hasGlobalStorage())
7496 return nullptr;
7497
7498 NamedDecl *ShadowedDecl = R.getFoundDecl();
7499 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7500 ? ShadowedDecl
7501 : nullptr;
7502}
7503
7504/// Return the declaration shadowed by the given typedef \p D, or null
7505/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7506NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7507 const LookupResult &R) {
7508 // Don't warn if typedef declaration is part of a class
7509 if (D->getDeclContext()->isRecord())
7510 return nullptr;
7511
7512 if (!shouldWarnIfShadowedDecl(Diags, R))
7513 return nullptr;
7514
7515 NamedDecl *ShadowedDecl = R.getFoundDecl();
7516 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7517}
7518
7519/// Diagnose variable or built-in function shadowing. Implements
7520/// -Wshadow.
7521///
7522/// This method is called whenever a VarDecl is added to a "useful"
7523/// scope.
7524///
7525/// \param ShadowedDecl the declaration that is shadowed by the given variable
7526/// \param R the lookup of the name
7527///
7528void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7529 const LookupResult &R) {
7530 DeclContext *NewDC = D->getDeclContext();
7531
7532 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7533 // Fields are not shadowed by variables in C++ static methods.
7534 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7535 if (MD->isStatic())
7536 return;
7537
7538 // Fields shadowed by constructor parameters are a special case. Usually
7539 // the constructor initializes the field with the parameter.
7540 if (isa<CXXConstructorDecl>(NewDC))
7541 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7542 // Remember that this was shadowed so we can either warn about its
7543 // modification or its existence depending on warning settings.
7544 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7545 return;
7546 }
7547 }
7548
7549 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7550 if (shadowedVar->isExternC()) {
7551 // For shadowing external vars, make sure that we point to the global
7552 // declaration, not a locally scoped extern declaration.
7553 for (auto I : shadowedVar->redecls())
7554 if (I->isFileVarDecl()) {
7555 ShadowedDecl = I;
7556 break;
7557 }
7558 }
7559
7560 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7561
7562 unsigned WarningDiag = diag::warn_decl_shadow;
7563 SourceLocation CaptureLoc;
7564 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7565 isa<CXXMethodDecl>(NewDC)) {
7566 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7567 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7568 if (RD->getLambdaCaptureDefault() == LCD_None) {
7569 // Try to avoid warnings for lambdas with an explicit capture list.
7570 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7571 // Warn only when the lambda captures the shadowed decl explicitly.
7572 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7573 if (CaptureLoc.isInvalid())
7574 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7575 } else {
7576 // Remember that this was shadowed so we can avoid the warning if the
7577 // shadowed decl isn't captured and the warning settings allow it.
7578 cast<LambdaScopeInfo>(getCurFunction())
7579 ->ShadowingDecls.push_back(
7580 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7581 return;
7582 }
7583 }
7584
7585 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7586 // A variable can't shadow a local variable in an enclosing scope, if
7587 // they are separated by a non-capturing declaration context.
7588 for (DeclContext *ParentDC = NewDC;
7589 ParentDC && !ParentDC->Equals(OldDC);
7590 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7591 // Only block literals, captured statements, and lambda expressions
7592 // can capture; other scopes don't.
7593 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7594 !isLambdaCallOperator(ParentDC)) {
7595 return;
7596 }
7597 }
7598 }
7599 }
7600 }
7601
7602 // Only warn about certain kinds of shadowing for class members.
7603 if (NewDC && NewDC->isRecord()) {
7604 // In particular, don't warn about shadowing non-class members.
7605 if (!OldDC->isRecord())
7606 return;
7607
7608 // TODO: should we warn about static data members shadowing
7609 // static data members from base classes?
7610
7611 // TODO: don't diagnose for inaccessible shadowed members.
7612 // This is hard to do perfectly because we might friend the
7613 // shadowing context, but that's just a false negative.
7614 }
7615
7616
7617 DeclarationName Name = R.getLookupName();
7618
7619 // Emit warning and note.
7620 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7621 return;
7622 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7623 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7624 if (!CaptureLoc.isInvalid())
7625 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7626 << Name << /*explicitly*/ 1;
7627 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7628}
7629
7630/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7631/// when these variables are captured by the lambda.
7632void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7633 for (const auto &Shadow : LSI->ShadowingDecls) {
7634 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7635 // Try to avoid the warning when the shadowed decl isn't captured.
7636 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7637 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7638 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7639 ? diag::warn_decl_shadow_uncaptured_local
7640 : diag::warn_decl_shadow)
7641 << Shadow.VD->getDeclName()
7642 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7643 if (!CaptureLoc.isInvalid())
7644 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7645 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7646 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7647 }
7648}
7649
7650/// Check -Wshadow without the advantage of a previous lookup.
7651void Sema::CheckShadow(Scope *S, VarDecl *D) {
7652 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7653 return;
7654
7655 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7656 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7657 LookupName(R, S);
7658 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7659 CheckShadow(D, ShadowedDecl, R);
7660}
7661
7662/// Check if 'E', which is an expression that is about to be modified, refers
7663/// to a constructor parameter that shadows a field.
7664void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7665 // Quickly ignore expressions that can't be shadowing ctor parameters.
7666 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7667 return;
7668 E = E->IgnoreParenImpCasts();
7669 auto *DRE = dyn_cast<DeclRefExpr>(E);
7670 if (!DRE)
7671 return;
7672 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7673 auto I = ShadowingDecls.find(D);
7674 if (I == ShadowingDecls.end())
7675 return;
7676 const NamedDecl *ShadowedDecl = I->second;
7677 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7678 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7679 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7680 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7681
7682 // Avoid issuing multiple warnings about the same decl.
7683 ShadowingDecls.erase(I);
7684}
7685
7686/// Check for conflict between this global or extern "C" declaration and
7687/// previous global or extern "C" declarations. This is only used in C++.
7688template<typename T>
7689static bool checkGlobalOrExternCConflict(
7690 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7691 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")((S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 7691, __PRETTY_FUNCTION__))
;
7692 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7693
7694 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7695 // The common case: this global doesn't conflict with any extern "C"
7696 // declaration.
7697 return false;
7698 }
7699
7700 if (Prev) {
7701 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7702 // Both the old and new declarations have C language linkage. This is a
7703 // redeclaration.
7704 Previous.clear();
7705 Previous.addDecl(Prev);
7706 return true;
7707 }
7708
7709 // This is a global, non-extern "C" declaration, and there is a previous
7710 // non-global extern "C" declaration. Diagnose if this is a variable
7711 // declaration.
7712 if (!isa<VarDecl>(ND))
7713 return false;
7714 } else {
7715 // The declaration is extern "C". Check for any declaration in the
7716 // translation unit which might conflict.
7717 if (IsGlobal) {
7718 // We have already performed the lookup into the translation unit.
7719 IsGlobal = false;
7720 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7721 I != E; ++I) {
7722 if (isa<VarDecl>(*I)) {
7723 Prev = *I;
7724 break;
7725 }
7726 }
7727 } else {
7728 DeclContext::lookup_result R =
7729 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7730 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7731 I != E; ++I) {
7732 if (isa<VarDecl>(*I)) {
7733 Prev = *I;
7734 break;
7735 }
7736 // FIXME: If we have any other entity with this name in global scope,
7737 // the declaration is ill-formed, but that is a defect: it breaks the
7738 // 'stat' hack, for instance. Only variables can have mangled name
7739 // clashes with extern "C" declarations, so only they deserve a
7740 // diagnostic.
7741 }
7742 }
7743
7744 if (!Prev)
7745 return false;
7746 }
7747
7748 // Use the first declaration's location to ensure we point at something which
7749 // is lexically inside an extern "C" linkage-spec.
7750 assert(Prev && "should have found a previous declaration to diagnose")((Prev && "should have found a previous declaration to diagnose"
) ? static_cast<void> (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 7750, __PRETTY_FUNCTION__))
;
7751 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7752 Prev = FD->getFirstDecl();
7753 else
7754 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7755
7756 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7757 << IsGlobal << ND;
7758 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7759 << IsGlobal;
7760 return false;
7761}
7762
7763/// Apply special rules for handling extern "C" declarations. Returns \c true
7764/// if we have found that this is a redeclaration of some prior entity.
7765///
7766/// Per C++ [dcl.link]p6:
7767/// Two declarations [for a function or variable] with C language linkage
7768/// with the same name that appear in different scopes refer to the same
7769/// [entity]. An entity with C language linkage shall not be declared with
7770/// the same name as an entity in global scope.
7771template<typename T>
7772static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7773 LookupResult &Previous) {
7774 if (!S.getLangOpts().CPlusPlus) {
7775 // In C, when declaring a global variable, look for a corresponding 'extern'
7776 // variable declared in function scope. We don't need this in C++, because
7777 // we find local extern decls in the surrounding file-scope DeclContext.
7778 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7779 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7780 Previous.clear();
7781 Previous.addDecl(Prev);
7782 return true;
7783 }
7784 }
7785 return false;
7786 }
7787
7788 // A declaration in the translation unit can conflict with an extern "C"
7789 // declaration.
7790 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7791 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7792
7793 // An extern "C" declaration can conflict with a declaration in the
7794 // translation unit or can be a redeclaration of an extern "C" declaration
7795 // in another scope.
7796 if (isIncompleteDeclExternC(S,ND))
7797 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7798
7799 // Neither global nor extern "C": nothing to do.
7800 return false;
7801}
7802
7803void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7804 // If the decl is already known invalid, don't check it.
7805 if (NewVD->isInvalidDecl())
7806 return;
7807
7808 QualType T = NewVD->getType();
7809
7810 // Defer checking an 'auto' type until its initializer is attached.
7811 if (T->isUndeducedType())
7812 return;
7813
7814 if (NewVD->hasAttrs())
7815 CheckAlignasUnderalignment(NewVD);
7816
7817 if (T->isObjCObjectType()) {
7818 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7819 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7820 T = Context.getObjCObjectPointerType(T);
7821 NewVD->setType(T);
7822 }
7823
7824 // Emit an error if an address space was applied to decl with local storage.
7825 // This includes arrays of objects with address space qualifiers, but not
7826 // automatic variables that point to other address spaces.
7827 // ISO/IEC TR 18037 S5.1.2
7828 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7829 T.getAddressSpace() != LangAS::Default) {
7830 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7831 NewVD->setInvalidDecl();
7832 return;
7833 }
7834
7835 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7836 // scope.
7837 if (getLangOpts().OpenCLVersion == 120 &&
7838 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7839 NewVD->isStaticLocal()) {
7840 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7841 NewVD->setInvalidDecl();
7842 return;
7843 }
7844
7845 if (getLangOpts().OpenCL) {
7846 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7847 if (NewVD->hasAttr<BlocksAttr>()) {
7848 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7849 return;
7850 }
7851
7852 if (T->isBlockPointerType()) {
7853 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7854 // can't use 'extern' storage class.
7855 if (!T.isConstQualified()) {
7856 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7857 << 0 /*const*/;
7858 NewVD->setInvalidDecl();
7859 return;
7860 }
7861 if (NewVD->hasExternalStorage()) {
7862 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7863 NewVD->setInvalidDecl();
7864 return;
7865 }
7866 }
7867 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7868 // __constant address space.
7869 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7870 // variables inside a function can also be declared in the global
7871 // address space.
7872 // C++ for OpenCL inherits rule from OpenCL C v2.0.
7873 // FIXME: Adding local AS in C++ for OpenCL might make sense.
7874 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7875 NewVD->hasExternalStorage()) {
7876 if (!T->isSamplerT() &&
7877 !T->isDependentType() &&
7878 !(T.getAddressSpace() == LangAS::opencl_constant ||
7879 (T.getAddressSpace() == LangAS::opencl_global &&
7880 (getLangOpts().OpenCLVersion == 200 ||
7881 getLangOpts().OpenCLCPlusPlus)))) {
7882 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7883 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7884 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7885 << Scope << "global or constant";
7886 else
7887 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7888 << Scope << "constant";
7889 NewVD->setInvalidDecl();
7890 return;
7891 }
7892 } else {
7893 if (T.getAddressSpace() == LangAS::opencl_global) {
7894 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7895 << 1 /*is any function*/ << "global";
7896 NewVD->setInvalidDecl();
7897 return;
7898 }
7899 if (T.getAddressSpace() == LangAS::opencl_constant ||
7900 T.getAddressSpace() == LangAS::opencl_local) {
7901 FunctionDecl *FD = getCurFunctionDecl();
7902 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7903 // in functions.
7904 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7905 if (T.getAddressSpace() == LangAS::opencl_constant)
7906 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7907 << 0 /*non-kernel only*/ << "constant";
7908 else
7909 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7910 << 0 /*non-kernel only*/ << "local";
7911 NewVD->setInvalidDecl();
7912 return;
7913 }
7914 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7915 // in the outermost scope of a kernel function.
7916 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7917 if (!getCurScope()->isFunctionScope()) {
7918 if (T.getAddressSpace() == LangAS::opencl_constant)
7919 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7920 << "constant";
7921 else
7922 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7923 << "local";
7924 NewVD->setInvalidDecl();
7925 return;
7926 }
7927 }
7928 } else if (T.getAddressSpace() != LangAS::opencl_private &&
7929 // If we are parsing a template we didn't deduce an addr
7930 // space yet.
7931 T.getAddressSpace() != LangAS::Default) {
7932 // Do not allow other address spaces on automatic variable.
7933 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7934 NewVD->setInvalidDecl();
7935 return;
7936 }
7937 }
7938 }
7939
7940 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7941 && !NewVD->hasAttr<BlocksAttr>()) {
7942 if (getLangOpts().getGC() != LangOptions::NonGC)
7943 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7944 else {
7945 assert(!getLangOpts().ObjCAutoRefCount)((!getLangOpts().ObjCAutoRefCount) ? static_cast<void> (
0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 7945, __PRETTY_FUNCTION__))
;
7946 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7947 }
7948 }
7949
7950 bool isVM = T->isVariablyModifiedType();
7951 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7952 NewVD->hasAttr<BlocksAttr>())
7953 setFunctionHasBranchProtectedScope();
7954
7955 if ((isVM && NewVD->hasLinkage()) ||
7956 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7957 bool SizeIsNegative;
7958 llvm::APSInt Oversized;
7959 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7960 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7961 QualType FixedT;
7962 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
7963 FixedT = FixedTInfo->getType();
7964 else if (FixedTInfo) {
7965 // Type and type-as-written are canonically different. We need to fix up
7966 // both types separately.
7967 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7968 Oversized);
7969 }
7970 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7971 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7972 // FIXME: This won't give the correct result for
7973 // int a[10][n];
7974 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7975
7976 if (NewVD->isFileVarDecl())
7977 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7978 << SizeRange;
7979 else if (NewVD->isStaticLocal())
7980 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7981 << SizeRange;
7982 else
7983 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7984 << SizeRange;
7985 NewVD->setInvalidDecl();
7986 return;
7987 }
7988
7989 if (!FixedTInfo) {
7990 if (NewVD->isFileVarDecl())
7991 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7992 else
7993 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7994 NewVD->setInvalidDecl();
7995 return;
7996 }
7997
7998 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
7999 NewVD->setType(FixedT);
8000 NewVD->setTypeSourceInfo(FixedTInfo);
8001 }
8002
8003 if (T->isVoidType()) {
8004 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8005 // of objects and functions.
8006 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8007 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8008 << T;
8009 NewVD->setInvalidDecl();
8010 return;
8011 }
8012 }
8013
8014 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8015 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8016 NewVD->setInvalidDecl();
8017 return;
8018 }
8019
8020 if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8021 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8022 NewVD->setInvalidDecl();
8023 return;
8024 }
8025
8026 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8027 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8028 NewVD->setInvalidDecl();
8029 return;
8030 }
8031
8032 if (NewVD->isConstexpr() && !T->isDependentType() &&
8033 RequireLiteralType(NewVD->getLocation(), T,
8034 diag::err_constexpr_var_non_literal)) {
8035 NewVD->setInvalidDecl();
8036 return;
8037 }
8038
8039 // PPC MMA non-pointer types are not allowed as non-local variable types.
8040 if (Context.getTargetInfo().getTriple().isPPC64() &&
8041 !NewVD->isLocalVarDecl() &&
8042 CheckPPCMMAType(T, NewVD->getLocation())) {
8043 NewVD->setInvalidDecl();
8044 return;
8045 }
8046}
8047
8048/// Perform semantic checking on a newly-created variable
8049/// declaration.
8050///
8051/// This routine performs all of the type-checking required for a
8052/// variable declaration once it has been built. It is used both to
8053/// check variables after they have been parsed and their declarators
8054/// have been translated into a declaration, and to check variables
8055/// that have been instantiated from a template.
8056///
8057/// Sets NewVD->isInvalidDecl() if an error was encountered.
8058///
8059/// Returns true if the variable declaration is a redeclaration.
8060bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8061 CheckVariableDeclarationType(NewVD);
8062
8063 // If the decl is already known invalid, don't check it.
8064 if (NewVD->isInvalidDecl())
8065 return false;
8066
8067 // If we did not find anything by this name, look for a non-visible
8068 // extern "C" declaration with the same name.
8069 if (Previous.empty() &&
8070 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8071 Previous.setShadowed();
8072
8073 if (!Previous.empty()) {
8074 MergeVarDecl(NewVD, Previous);
8075 return true;
8076 }
8077 return false;
8078}
8079
8080namespace {
8081struct FindOverriddenMethod {
8082 Sema *S;
8083 CXXMethodDecl *Method;
8084
8085 /// Member lookup function that determines whether a given C++
8086 /// method overrides a method in a base class, to be used with
8087 /// CXXRecordDecl::lookupInBases().
8088 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8089 RecordDecl *BaseRecord =
8090 Specifier->getType()->castAs<RecordType>()->getDecl();
8091
8092 DeclarationName Name = Method->getDeclName();
8093
8094 // FIXME: Do we care about other names here too?
8095 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8096 // We really want to find the base class destructor here.
8097 QualType T = S->Context.getTypeDeclType(BaseRecord);
8098 CanQualType CT = S->Context.getCanonicalType(T);
8099
8100 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8101 }
8102
8103 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8104 Path.Decls = Path.Decls.slice(1)) {
8105 NamedDecl *D = Path.Decls.front();
8106 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8107 if (MD->isVirtual() &&
8108 !S->IsOverload(
8109 Method, MD, /*UseMemberUsingDeclRules=*/false,
8110 /*ConsiderCudaAttrs=*/true,
8111 // C++2a [class.virtual]p2 does not consider requires clauses
8112 // when overriding.
8113 /*ConsiderRequiresClauses=*/false))
8114 return true;
8115 }
8116 }
8117
8118 return false;
8119 }
8120};
8121} // end anonymous namespace
8122
8123/// AddOverriddenMethods - See if a method overrides any in the base classes,
8124/// and if so, check that it's a valid override and remember it.
8125bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8126 // Look for methods in base classes that this method might override.
8127 CXXBasePaths Paths;
8128 FindOverriddenMethod FOM;
8129 FOM.Method = MD;
8130 FOM.S = this;
8131 bool AddedAny = false;
8132 if (DC->lookupInBases(FOM, Paths)) {
8133 for (auto *I : Paths.found_decls()) {
8134 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8135 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8136 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8137 !CheckOverridingFunctionAttributes(MD, OldMD) &&
8138 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8139 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8140 AddedAny = true;
8141 }
8142 }
8143 }
8144 }
8145
8146 return AddedAny;
8147}
8148
8149namespace {
8150 // Struct for holding all of the extra arguments needed by
8151 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8152 struct ActOnFDArgs {
8153 Scope *S;
8154 Declarator &D;
8155 MultiTemplateParamsArg TemplateParamLists;
8156 bool AddToScope;
8157 };
8158} // end anonymous namespace
8159
8160namespace {
8161
8162// Callback to only accept typo corrections that have a non-zero edit distance.
8163// Also only accept corrections that have the same parent decl.
8164class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8165 public:
8166 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8167 CXXRecordDecl *Parent)
8168 : Context(Context), OriginalFD(TypoFD),
8169 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8170
8171 bool ValidateCandidate(const TypoCorrection &candidate) override {
8172 if (candidate.getEditDistance() == 0)
8173 return false;
8174
8175 SmallVector<unsigned, 1> MismatchedParams;
8176 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8177 CDeclEnd = candidate.end();
8178 CDecl != CDeclEnd; ++CDecl) {
8179 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8180
8181 if (FD && !FD->hasBody() &&
8182 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8183 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8184 CXXRecordDecl *Parent = MD->getParent();
8185 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8186 return true;
8187 } else if (!ExpectedParent) {
8188 return true;
8189 }
8190 }
8191 }
8192
8193 return false;
8194 }
8195
8196 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8197 return std::make_unique<DifferentNameValidatorCCC>(*this);
8198 }
8199
8200 private:
8201 ASTContext &Context;
8202 FunctionDecl *OriginalFD;
8203 CXXRecordDecl *ExpectedParent;
8204};
8205
8206} // end anonymous namespace
8207
8208void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8209 TypoCorrectedFunctionDefinitions.insert(F);
8210}
8211
8212/// Generate diagnostics for an invalid function redeclaration.
8213///
8214/// This routine handles generating the diagnostic messages for an invalid
8215/// function redeclaration, including finding possible similar declarations
8216/// or performing typo correction if there are no previous declarations with
8217/// the same name.
8218///
8219/// Returns a NamedDecl iff typo correction was performed and substituting in
8220/// the new declaration name does not cause new errors.
8221static NamedDecl *DiagnoseInvalidRedeclaration(
8222 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8223 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8224 DeclarationName Name = NewFD->getDeclName();
8225 DeclContext *NewDC = NewFD->getDeclContext();
8226 SmallVector<unsigned, 1> MismatchedParams;
8227 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8228 TypoCorrection Correction;
8229 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8230 unsigned DiagMsg =
8231 IsLocalFriend ? diag::err_no_matching_local_friend :
8232 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8233 diag::err_member_decl_does_not_match;
8234 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8235 IsLocalFriend ? Sema::LookupLocalFriendName
8236 : Sema::LookupOrdinaryName,
8237 Sema::ForVisibleRedeclaration);
8238
8239 NewFD->setInvalidDecl();
8240 if (IsLocalFriend)
8241 SemaRef.LookupName(Prev, S);
8242 else
8243 SemaRef.LookupQualifiedName(Prev, NewDC);
8244 assert(!Prev.isAmbiguous() &&((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 8245, __PRETTY_FUNCTION__))
8245 "Cannot have an ambiguity in previous-declaration lookup")((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 8245, __PRETTY_FUNCTION__))
;
8246 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8247 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8248 MD ? MD->getParent() : nullptr);
8249 if (!Prev.empty()) {
8250 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8251 Func != FuncEnd; ++Func) {
8252 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8253 if (FD &&
8254 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8255 // Add 1 to the index so that 0 can mean the mismatch didn't
8256 // involve a parameter
8257 unsigned ParamNum =
8258 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8259 NearMatches.push_back(std::make_pair(FD, ParamNum));
8260 }
8261 }
8262 // If the qualified name lookup yielded nothing, try typo correction
8263 } else if ((Correction = SemaRef.CorrectTypo(
8264 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8265 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8266 IsLocalFriend ? nullptr : NewDC))) {
8267 // Set up everything for the call to ActOnFunctionDeclarator
8268 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8269 ExtraArgs.D.getIdentifierLoc());
8270 Previous.clear();
8271 Previous.setLookupName(Correction.getCorrection());
8272 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8273 CDeclEnd = Correction.end();
8274 CDecl != CDeclEnd; ++CDecl) {
8275 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8276 if (FD && !FD->hasBody() &&
8277 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8278 Previous.addDecl(FD);
8279 }
8280 }
8281 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8282
8283 NamedDecl *Result;
8284 // Retry building the function declaration with the new previous
8285 // declarations, and with errors suppressed.
8286 {
8287 // Trap errors.
8288 Sema::SFINAETrap Trap(SemaRef);
8289
8290 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8291 // pieces need to verify the typo-corrected C++ declaration and hopefully
8292 // eliminate the need for the parameter pack ExtraArgs.
8293 Result = SemaRef.ActOnFunctionDeclarator(
8294 ExtraArgs.S, ExtraArgs.D,
8295 Correction.getCorrectionDecl()->getDeclContext(),
8296 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8297 ExtraArgs.AddToScope);
8298
8299 if (Trap.hasErrorOccurred())
8300 Result = nullptr;
8301 }
8302
8303 if (Result) {
8304 // Determine which correction we picked.
8305 Decl *Canonical = Result->getCanonicalDecl();
8306 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8307 I != E; ++I)
8308 if ((*I)->getCanonicalDecl() == Canonical)
8309 Correction.setCorrectionDecl(*I);
8310
8311 // Let Sema know about the correction.
8312 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8313 SemaRef.diagnoseTypo(
8314 Correction,
8315 SemaRef.PDiag(IsLocalFriend
8316 ? diag::err_no_matching_local_friend_suggest
8317 : diag::err_member_decl_does_not_match_suggest)
8318 << Name << NewDC << IsDefinition);
8319 return Result;
8320 }
8321
8322 // Pretend the typo correction never occurred
8323 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8324 ExtraArgs.D.getIdentifierLoc());
8325 ExtraArgs.D.setRedeclaration(wasRedeclaration);
8326 Previous.clear();
8327 Previous.setLookupName(Name);
8328 }
8329
8330 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8331 << Name << NewDC << IsDefinition << NewFD->getLocation();
8332
8333 bool NewFDisConst = false;
8334 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8335 NewFDisConst = NewMD->isConst();
8336
8337 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8338 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8339 NearMatch != NearMatchEnd; ++NearMatch) {
8340 FunctionDecl *FD = NearMatch->first;
8341 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8342 bool FDisConst = MD && MD->isConst();
8343 bool IsMember = MD || !IsLocalFriend;
8344
8345 // FIXME: These notes are poorly worded for the local friend case.
8346 if (unsigned Idx = NearMatch->second) {
8347 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8348 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8349 if (Loc.isInvalid()) Loc = FD->getLocation();
8350 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8351 : diag::note_local_decl_close_param_match)
8352 << Idx << FDParam->getType()
8353 << NewFD->getParamDecl(Idx - 1)->getType();
8354 } else if (FDisConst != NewFDisConst) {
8355 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8356 << NewFDisConst << FD->getSourceRange().getEnd();
8357 } else
8358 SemaRef.Diag(FD->getLocation(),
8359 IsMember ? diag::note_member_def_close_match
8360 : diag::note_local_decl_close_match);
8361 }
8362 return nullptr;
8363}
8364
8365static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8366 switch (D.getDeclSpec().getStorageClassSpec()) {
8367 default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 8367)
;
8368 case DeclSpec::SCS_auto:
8369 case DeclSpec::SCS_register:
8370 case DeclSpec::SCS_mutable:
8371 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8372 diag::err_typecheck_sclass_func);
8373 D.getMutableDeclSpec().ClearStorageClassSpecs();
8374 D.setInvalidType();
8375 break;
8376 case DeclSpec::SCS_unspecified: break;
8377 case DeclSpec::SCS_extern:
8378 if (D.getDeclSpec().isExternInLinkageSpec())
8379 return SC_None;
8380 return SC_Extern;
8381 case DeclSpec::SCS_static: {
8382 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8383 // C99 6.7.1p5:
8384 // The declaration of an identifier for a function that has
8385 // block scope shall have no explicit storage-class specifier
8386 // other than extern
8387 // See also (C++ [dcl.stc]p4).
8388 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8389 diag::err_static_block_func);
8390 break;
8391 } else
8392 return SC_Static;
8393 }
8394 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8395 }
8396
8397 // No explicit storage class has already been returned
8398 return SC_None;
8399}
8400
8401static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8402 DeclContext *DC, QualType &R,
8403 TypeSourceInfo *TInfo,
8404 StorageClass SC,
8405 bool &IsVirtualOkay) {
8406 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8407 DeclarationName Name = NameInfo.getName();
8408
8409 FunctionDecl *NewFD = nullptr;
8410 bool isInline = D.getDeclSpec().isInlineSpecified();
8411
8412 if (!SemaRef.getLangOpts().CPlusPlus) {
8413 // Determine whether the function was written with a
8414 // prototype. This true when:
8415 // - there is a prototype in the declarator, or
8416 // - the type R of the function is some kind of typedef or other non-
8417 // attributed reference to a type name (which eventually refers to a
8418 // function type).
8419 bool HasPrototype =
8420 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8421 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8422
8423 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8424 R, TInfo, SC, isInline, HasPrototype,
8425 ConstexprSpecKind::Unspecified,
8426 /*TrailingRequiresClause=*/nullptr);
8427 if (D.isInvalidType())
8428 NewFD->setInvalidDecl();
8429
8430 return NewFD;
8431 }
8432
8433 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8434
8435 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8436 if (ConstexprKind == ConstexprSpecKind::Constinit) {
8437 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8438 diag::err_constexpr_wrong_decl_kind)
8439 << static_cast<int>(ConstexprKind);
8440 ConstexprKind = ConstexprSpecKind::Unspecified;
8441 D.getMutableDeclSpec().ClearConstexprSpec();
8442 }
8443 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8444
8445 // Check that the return type is not an abstract class type.
8446 // For record types, this is done by the AbstractClassUsageDiagnoser once
8447 // the class has been completely parsed.
8448 if (!DC->isRecord() &&
8449 SemaRef.RequireNonAbstractType(
8450 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8451 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8452 D.setInvalidType();
8453
8454 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8455 // This is a C++ constructor declaration.
8456 assert(DC->isRecord() &&((DC->isRecord() && "Constructors can only be declared in a member context"
) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 8457, __PRETTY_FUNCTION__))
8457 "Constructors can only be declared in a member context")((DC->isRecord() && "Constructors can only be declared in a member context"
) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 8457, __PRETTY_FUNCTION__))
;
8458
8459 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8460 return CXXConstructorDecl::Create(
8461 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8462 TInfo, ExplicitSpecifier, isInline,
8463 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8464 TrailingRequiresClause);
8465
8466 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8467 // This is a C++ destructor declaration.
8468 if (DC->isRecord()) {
8469 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8470 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8471 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8472 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8473 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8474 TrailingRequiresClause);
8475
8476 // If the destructor needs an implicit exception specification, set it
8477 // now. FIXME: It'd be nice to be able to create the right type to start
8478 // with, but the type needs to reference the destructor declaration.
8479 if (SemaRef.getLangOpts().CPlusPlus11)
8480 SemaRef.AdjustDestructorExceptionSpec(NewDD);
8481
8482 IsVirtualOkay = true;
8483 return NewDD;
8484
8485 } else {
8486 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8487 D.setInvalidType();
8488
8489 // Create a FunctionDecl to satisfy the function definition parsing
8490 // code path.
8491 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8492 D.getIdentifierLoc(), Name, R, TInfo, SC,
8493 isInline,
8494 /*hasPrototype=*/true, ConstexprKind,
8495 TrailingRequiresClause);
8496 }
8497
8498 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8499 if (!DC->isRecord()) {
8500 SemaRef.Diag(D.getIdentifierLoc(),
8501 diag::err_conv_function_not_member);
8502 return nullptr;
8503 }
8504
8505 SemaRef.CheckConversionDeclarator(D, R, SC);
8506 if (D.isInvalidType())
8507 return nullptr;
8508
8509 IsVirtualOkay = true;
8510 return CXXConversionDecl::Create(
8511 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8512 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8513 TrailingRequiresClause);
8514
8515 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8516 if (TrailingRequiresClause)
8517 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8518 diag::err_trailing_requires_clause_on_deduction_guide)
8519 << TrailingRequiresClause->getSourceRange();
8520 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8521
8522 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8523 ExplicitSpecifier, NameInfo, R, TInfo,
8524 D.getEndLoc());
8525 } else if (DC->isRecord()) {
8526 // If the name of the function is the same as the name of the record,
8527 // then this must be an invalid constructor that has a return type.
8528 // (The parser checks for a return type and makes the declarator a
8529 // constructor if it has no return type).
8530 if (Name.getAsIdentifierInfo() &&
8531 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8532 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8533 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8534 << SourceRange(D.getIdentifierLoc());
8535 return nullptr;
8536 }
8537
8538 // This is a C++ method declaration.
8539 CXXMethodDecl *Ret = CXXMethodDecl::Create(
8540 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8541 TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8542 TrailingRequiresClause);
8543 IsVirtualOkay = !Ret->isStatic();
8544 return Ret;
8545 } else {
8546 bool isFriend =
8547 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8548 if (!isFriend && SemaRef.CurContext->isRecord())
8549 return nullptr;
8550
8551 // Determine whether the function was written with a
8552 // prototype. This true when:
8553 // - we're in C++ (where every function has a prototype),
8554 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8555 R, TInfo, SC, isInline, true /*HasPrototype*/,
8556 ConstexprKind, TrailingRequiresClause);
8557 }
8558}
8559
8560enum OpenCLParamType {
8561 ValidKernelParam,
8562 PtrPtrKernelParam,
8563 PtrKernelParam,
8564 InvalidAddrSpacePtrKernelParam,
8565 InvalidKernelParam,
8566 RecordKernelParam
8567};
8568
8569static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8570 // Size dependent types are just typedefs to normal integer types
8571 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8572 // integers other than by their names.
8573 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8574
8575 // Remove typedefs one by one until we reach a typedef
8576 // for a size dependent type.
8577 QualType DesugaredTy = Ty;
8578 do {
19
Loop condition is false. Exiting loop
80
Loop condition is false. Exiting loop
141
Loop condition is false. Exiting loop
8579 ArrayRef<StringRef> Names(SizeTypeNames);
8580 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8581 if (Names.end() != Match)
10
Assuming the condition is false
11
Taking false branch
71
Assuming the condition is false
72
Taking false branch
132
Assuming the condition is false
133
Taking false branch
8582 return true;
8583
8584 Ty = DesugaredTy;
8585 DesugaredTy = Ty.getSingleStepDesugaredType(C);
8586 } while (DesugaredTy != Ty);
12
Calling 'operator!='
18
Returning from 'operator!='
73
Calling 'operator!='
79
Returning from 'operator!='
134
Calling 'operator!='
140
Returning from 'operator!='
8587
8588 return false;
20
Returning zero, which participates in a condition later
81
Returning zero, which participates in a condition later
142
Returning zero, which participates in a condition later
8589}
8590
8591static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8592 if (PT->isPointerType()) {
4
Calling 'Type::isPointerType'
7
Returning from 'Type::isPointerType'
8
Taking false branch
65
Calling 'Type::isPointerType'
68
Returning from 'Type::isPointerType'
69
Taking false branch
126
Calling 'Type::isPointerType'
129
Returning from 'Type::isPointerType'
130
Taking false branch
219
Calling 'Type::isPointerType'
222
Returning from 'Type::isPointerType'
223
Taking false branch
8593 QualType PointeeType = PT->getPointeeType();
8594 if (PointeeType->isPointerType())
8595 return PtrPtrKernelParam;
8596 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8597 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8598 PointeeType.getAddressSpace() == LangAS::Default)
8599 return InvalidAddrSpacePtrKernelParam;
8600 return PtrKernelParam;
8601 }
8602
8603 // OpenCL v1.2 s6.9.k:
8604 // Arguments to kernel functions in a program cannot be declared with the
8605 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8606 // uintptr_t or a struct and/or union that contain fields declared to be one
8607 // of these built-in scalar types.
8608 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9
Calling 'isOpenCLSizeDependentType'
21
Returning from 'isOpenCLSizeDependentType'
22
Taking false branch
70
Calling 'isOpenCLSizeDependentType'
82
Returning from 'isOpenCLSizeDependentType'
83
Taking false branch
131
Calling 'isOpenCLSizeDependentType'
143
Returning from 'isOpenCLSizeDependentType'
144
Taking false branch
224
Assuming the condition is false
225
Taking false branch
8609 return InvalidKernelParam;
8610
8611 if (PT->isImageType())
23
Calling 'Type::isImageType'
25
Returning from 'Type::isImageType'
26
Taking false branch
84
Calling 'Type::isImageType'
86
Returning from 'Type::isImageType'
87
Taking false branch
145
Calling 'Type::isImageType'
183
Returning from 'Type::isImageType'
184
Taking false branch
226
Assuming the condition is false
227
Taking false branch
8612 return PtrKernelParam;
8613
8614 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
27
Calling 'Type::isBooleanType'
35
Returning from 'Type::isBooleanType'
36
Calling 'Type::isEventT'
43
Returning from 'Type::isEventT'
44
Calling 'Type::isReserveIDT'
51
Returning from 'Type::isReserveIDT'
52
Taking false branch
88
Calling 'Type::isBooleanType'
96
Returning from 'Type::isBooleanType'
97
Calling 'Type::isEventT'
104
Returning from 'Type::isEventT'
105
Calling 'Type::isReserveIDT'
112
Returning from 'Type::isReserveIDT'
113
Taking false branch
185
Calling 'Type::isBooleanType'
189
Returning from 'Type::isBooleanType'
190
Calling 'Type::isEventT'
197
Returning from 'Type::isEventT'
198
Calling 'Type::isReserveIDT'
205
Returning from 'Type::isReserveIDT'
206
Taking false branch
228
Assuming the condition is false
229
Assuming the condition is false
230
Assuming the condition is false
231
Taking false branch
8615 return InvalidKernelParam;
8616
8617 // OpenCL extension spec v1.2 s9.5:
8618 // This extension adds support for half scalar and vector types as built-in
8619 // types that can be used for arithmetic operations, conversions etc.
8620 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
53
Taking false branch
114
Taking false branch
207
Taking false branch
232
Assuming the condition is false
233
Taking false branch
8621 return InvalidKernelParam;
8622
8623 if (PT->isRecordType())
54
Calling 'Type::isRecordType'
57
Returning from 'Type::isRecordType'
58
Taking false branch
115
Calling 'Type::isRecordType'
118
Returning from 'Type::isRecordType'
119
Taking false branch
208
Calling 'Type::isRecordType'
211
Returning from 'Type::isRecordType'
212
Taking false branch
234
Calling 'Type::isRecordType'
237
Returning from 'Type::isRecordType'
238
Taking false branch
8624 return RecordKernelParam;
8625
8626 // Look into an array argument to check if it has a forbidden type.
8627 if (PT->isArrayType()) {
59
Calling 'Type::isArrayType'
62
Returning from 'Type::isArrayType'
63
Taking true branch
120
Calling 'Type::isArrayType'
123
Returning from 'Type::isArrayType'
124
Taking true branch
213
Calling 'Type::isArrayType'
216
Returning from 'Type::isArrayType'
217
Taking true branch
239
Calling 'Type::isArrayType'
242
Returning from 'Type::isArrayType'
243
Taking true branch
8628 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8629 // Call ourself to check an underlying type of an array. Since the
8630 // getPointeeOrArrayElementType returns an innermost type which is not an
8631 // array, this recursive call only happens once.
8632 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
64
Calling 'getOpenCLKernelParameterType'
125
Calling 'getOpenCLKernelParameterType'
218
Calling 'getOpenCLKernelParameterType'
244
Returning value, which participates in a condition later
245
Returning from 'getOpenCLKernelParameterType'
246
Returning value, which participates in a condition later
247
Returning from 'getOpenCLKernelParameterType'
248
Returning value, which participates in a condition later
249
Returning from 'getOpenCLKernelParameterType'
250
Returning value, which participates in a condition later
8633 }
8634
8635 return ValidKernelParam;
8636}
8637
8638static void checkIsValidOpenCLKernelParameter(
8639 Sema &S,
8640 Declarator &D,
8641 ParmVarDecl *Param,
8642 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8643 QualType PT = Param->getType();
8644
8645 // Cache the valid types we encounter to avoid rechecking structs that are
8646 // used again
8647 if (ValidTypes.count(PT.getTypePtr()))
1
Assuming the condition is false
2
Taking false branch
8648 return;
8649
8650 switch (getOpenCLKernelParameterType(S, PT)) {
3
Calling 'getOpenCLKernelParameterType'
251
Returning from 'getOpenCLKernelParameterType'
252
Control jumps to 'case RecordKernelParam:' at line 8702
8651 case PtrPtrKernelParam:
8652 // OpenCL v1.2 s6.9.a:
8653 // A kernel function argument cannot be declared as a
8654 // pointer to a pointer type.
8655 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8656 D.setInvalidType();
8657 return;
8658
8659 case InvalidAddrSpacePtrKernelParam:
8660 // OpenCL v1.0 s6.5:
8661 // __kernel function arguments declared to be a pointer of a type can point
8662 // to one of the following address spaces only : __global, __local or
8663 // __constant.
8664 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8665 D.setInvalidType();
8666 return;
8667
8668 // OpenCL v1.2 s6.9.k:
8669 // Arguments to kernel functions in a program cannot be declared with the
8670 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8671 // uintptr_t or a struct and/or union that contain fields declared to be
8672 // one of these built-in scalar types.
8673
8674 case InvalidKernelParam:
8675 // OpenCL v1.2 s6.8 n:
8676 // A kernel function argument cannot be declared
8677 // of event_t type.
8678 // Do not diagnose half type since it is diagnosed as invalid argument
8679 // type for any function elsewhere.
8680 if (!PT->isHalfType()) {
8681 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8682
8683 // Explain what typedefs are involved.
8684 const TypedefType *Typedef = nullptr;
8685 while ((Typedef = PT->getAs<TypedefType>())) {
8686 SourceLocation Loc = Typedef->getDecl()->getLocation();
8687 // SourceLocation may be invalid for a built-in type.
8688 if (Loc.isValid())
8689 S.Diag(Loc, diag::note_entity_declared_at) << PT;
8690 PT = Typedef->desugar();
8691 }
8692 }
8693
8694 D.setInvalidType();
8695 return;
8696
8697 case PtrKernelParam:
8698 case ValidKernelParam:
8699 ValidTypes.insert(PT.getTypePtr());
8700 return;
8701
8702 case RecordKernelParam:
8703 break;
253
Execution continues on line 8707
8704 }
8705
8706 // Track nested structs we will inspect
8707 SmallVector<const Decl *, 4> VisitStack;
8708
8709 // Track where we are in the nested structs. Items will migrate from
8710 // VisitStack to HistoryStack as we do the DFS for bad field.
8711 SmallVector<const FieldDecl *, 4> HistoryStack;
8712 HistoryStack.push_back(nullptr);
8713
8714 // At this point we already handled everything except of a RecordType or
8715 // an ArrayType of a RecordType.
8716 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.")(((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."
) ? static_cast<void> (0) : __assert_fail ("(PT->isArrayType() || PT->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 8716, __PRETTY_FUNCTION__))
;
254
'?' condition is true
8717 const RecordType *RecTy =
256
'RecTy' initialized to a null pointer value
8718 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
255
Assuming the object is not a 'RecordType'
8719 const RecordDecl *OrigRecDecl = RecTy->getDecl();
257
Called C++ object pointer is null
8720
8721 VisitStack.push_back(RecTy->getDecl());
8722 assert(VisitStack.back() && "First decl null?")((VisitStack.back() && "First decl null?") ? static_cast
<void> (0) : __assert_fail ("VisitStack.back() && \"First decl null?\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 8722, __PRETTY_FUNCTION__))
;
8723
8724 do {
8725 const Decl *Next = VisitStack.pop_back_val();
8726 if (!Next) {
8727 assert(!HistoryStack.empty())((!HistoryStack.empty()) ? static_cast<void> (0) : __assert_fail
("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 8727, __PRETTY_FUNCTION__))
;
8728 // Found a marker, we have gone up a level
8729 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8730 ValidTypes.insert(Hist->getType().getTypePtr());
8731
8732 continue;
8733 }
8734
8735 // Adds everything except the original parameter declaration (which is not a
8736 // field itself) to the history stack.
8737 const RecordDecl *RD;
8738 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8739 HistoryStack.push_back(Field);
8740
8741 QualType FieldTy = Field->getType();
8742 // Other field types (known to be valid or invalid) are handled while we
8743 // walk around RecordDecl::fields().
8744 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&(((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
"Unexpected type.") ? static_cast<void> (0) : __assert_fail
("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 8745, __PRETTY_FUNCTION__))
8745 "Unexpected type.")(((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
"Unexpected type.") ? static_cast<void> (0) : __assert_fail
("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 8745, __PRETTY_FUNCTION__))
;
8746 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8747
8748 RD = FieldRecTy->castAs<RecordType>()->getDecl();
8749 } else {
8750 RD = cast<RecordDecl>(Next);
8751 }
8752
8753 // Add a null marker so we know when we've gone back up a level
8754 VisitStack.push_back(nullptr);
8755
8756 for (const auto *FD : RD->fields()) {
8757 QualType QT = FD->getType();
8758
8759 if (ValidTypes.count(QT.getTypePtr()))
8760 continue;
8761
8762 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8763 if (ParamType == ValidKernelParam)
8764 continue;
8765
8766 if (ParamType == RecordKernelParam) {
8767 VisitStack.push_back(FD);
8768 continue;
8769 }
8770
8771 // OpenCL v1.2 s6.9.p:
8772 // Arguments to kernel functions that are declared to be a struct or union
8773 // do not allow OpenCL objects to be passed as elements of the struct or
8774 // union.
8775 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8776 ParamType == InvalidAddrSpacePtrKernelParam) {
8777 S.Diag(Param->getLocation(),
8778 diag::err_record_with_pointers_kernel_param)
8779 << PT->isUnionType()
8780 << PT;
8781 } else {
8782 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8783 }
8784
8785 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8786 << OrigRecDecl->getDeclName();
8787
8788 // We have an error, now let's go back up through history and show where
8789 // the offending field came from
8790 for (ArrayRef<const FieldDecl *>::const_iterator
8791 I = HistoryStack.begin() + 1,
8792 E = HistoryStack.end();
8793 I != E; ++I) {
8794 const FieldDecl *OuterField = *I;
8795 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8796 << OuterField->getType();
8797 }
8798
8799 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8800 << QT->isPointerType()
8801 << QT;
8802 D.setInvalidType();
8803 return;
8804 }
8805 } while (!VisitStack.empty());
8806}
8807
8808/// Find the DeclContext in which a tag is implicitly declared if we see an
8809/// elaborated type specifier in the specified context, and lookup finds
8810/// nothing.
8811static DeclContext *getTagInjectionContext(DeclContext *DC) {
8812 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8813 DC = DC->getParent();
8814 return DC;
8815}
8816
8817/// Find the Scope in which a tag is implicitly declared if we see an
8818/// elaborated type specifier in the specified context, and lookup finds
8819/// nothing.
8820static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8821 while (S->isClassScope() ||
8822 (LangOpts.CPlusPlus &&
8823 S->isFunctionPrototypeScope()) ||
8824 ((S->getFlags() & Scope::DeclScope) == 0) ||
8825 (S->getEntity() && S->getEntity()->isTransparentContext()))
8826 S = S->getParent();
8827 return S;
8828}
8829
8830NamedDecl*
8831Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8832 TypeSourceInfo *TInfo, LookupResult &Previous,
8833 MultiTemplateParamsArg TemplateParamListsRef,
8834 bool &AddToScope) {
8835 QualType R = TInfo->getType();
8836
8837 assert(R->isFunctionType())((R->isFunctionType()) ? static_cast<void> (0) : __assert_fail
("R->isFunctionType()", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 8837, __PRETTY_FUNCTION__))
;
8838 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8839 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8840
8841 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8842 for (TemplateParameterList *TPL : TemplateParamListsRef)
8843 TemplateParamLists.push_back(TPL);
8844 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8845 if (!TemplateParamLists.empty() &&
8846 Invented->getDepth() == TemplateParamLists.back()->getDepth())
8847 TemplateParamLists.back() = Invented;
8848 else
8849 TemplateParamLists.push_back(Invented);
8850 }
8851
8852 // TODO: consider using NameInfo for diagnostic.
8853 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8854 DeclarationName Name = NameInfo.getName();
8855 StorageClass SC = getFunctionStorageClass(*this, D);
8856
8857 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8858 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8859 diag::err_invalid_thread)
8860 << DeclSpec::getSpecifierName(TSCS);
8861
8862 if (D.isFirstDeclarationOfMember())
8863 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8864 D.getIdentifierLoc());
8865
8866 bool isFriend = false;
8867 FunctionTemplateDecl *FunctionTemplate = nullptr;
8868 bool isMemberSpecialization = false;
8869 bool isFunctionTemplateSpecialization = false;
8870
8871 bool isDependentClassScopeExplicitSpecialization = false;
8872 bool HasExplicitTemplateArgs = false;
8873 TemplateArgumentListInfo TemplateArgs;
8874
8875 bool isVirtualOkay = false;
8876
8877 DeclContext *OriginalDC = DC;
8878 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8879
8880 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8881 isVirtualOkay);
8882 if (!NewFD) return nullptr;
8883
8884 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8885 NewFD->setTopLevelDeclInObjCContainer();
8886
8887 // Set the lexical context. If this is a function-scope declaration, or has a
8888 // C++ scope specifier, or is the object of a friend declaration, the lexical
8889 // context will be different from the semantic context.
8890 NewFD->setLexicalDeclContext(CurContext);
8891
8892 if (IsLocalExternDecl)
8893 NewFD->setLocalExternDecl();
8894
8895 if (getLangOpts().CPlusPlus) {
8896 bool isInline = D.getDeclSpec().isInlineSpecified();
8897 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8898 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8899 isFriend = D.getDeclSpec().isFriendSpecified();
8900 if (isFriend && !isInline && D.isFunctionDefinition()) {
8901 // C++ [class.friend]p5
8902 // A function can be defined in a friend declaration of a
8903 // class . . . . Such a function is implicitly inline.
8904 NewFD->setImplicitlyInline();
8905 }
8906
8907 // If this is a method defined in an __interface, and is not a constructor
8908 // or an overloaded operator, then set the pure flag (isVirtual will already
8909 // return true).
8910 if (const CXXRecordDecl *Parent =
8911 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8912 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8913 NewFD->setPure(true);
8914
8915 // C++ [class.union]p2
8916 // A union can have member functions, but not virtual functions.
8917 if (isVirtual && Parent->isUnion())
8918 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8919 }
8920
8921 SetNestedNameSpecifier(*this, NewFD, D);
8922 isMemberSpecialization = false;
8923 isFunctionTemplateSpecialization = false;
8924 if (D.isInvalidType())
8925 NewFD->setInvalidDecl();
8926
8927 // Match up the template parameter lists with the scope specifier, then
8928 // determine whether we have a template or a template specialization.
8929 bool Invalid = false;
8930 TemplateParameterList *TemplateParams =
8931 MatchTemplateParametersToScopeSpecifier(
8932 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8933 D.getCXXScopeSpec(),
8934 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8935 ? D.getName().TemplateId
8936 : nullptr,
8937 TemplateParamLists, isFriend, isMemberSpecialization,
8938 Invalid);
8939 if (TemplateParams) {
8940 // Check that we can declare a template here.
8941 if (CheckTemplateDeclScope(S, TemplateParams))
8942 NewFD->setInvalidDecl();
8943
8944 if (TemplateParams->size() > 0) {
8945 // This is a function template
8946
8947 // A destructor cannot be a template.
8948 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8949 Diag(NewFD->getLocation(), diag::err_destructor_template);
8950 NewFD->setInvalidDecl();
8951 }
8952
8953 // If we're adding a template to a dependent context, we may need to
8954 // rebuilding some of the types used within the template parameter list,
8955 // now that we know what the current instantiation is.
8956 if (DC->isDependentContext()) {
8957 ContextRAII SavedContext(*this, DC);
8958 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8959 Invalid = true;
8960 }
8961
8962 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8963 NewFD->getLocation(),
8964 Name, TemplateParams,
8965 NewFD);
8966 FunctionTemplate->setLexicalDeclContext(CurContext);
8967 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8968
8969 // For source fidelity, store the other template param lists.
8970 if (TemplateParamLists.size() > 1) {
8971 NewFD->setTemplateParameterListsInfo(Context,
8972 ArrayRef<TemplateParameterList *>(TemplateParamLists)
8973 .drop_back(1));
8974 }
8975 } else {
8976 // This is a function template specialization.
8977 isFunctionTemplateSpecialization = true;
8978 // For source fidelity, store all the template param lists.
8979 if (TemplateParamLists.size() > 0)
8980 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8981
8982 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8983 if (isFriend) {
8984 // We want to remove the "template<>", found here.
8985 SourceRange RemoveRange = TemplateParams->getSourceRange();
8986
8987 // If we remove the template<> and the name is not a
8988 // template-id, we're actually silently creating a problem:
8989 // the friend declaration will refer to an untemplated decl,
8990 // and clearly the user wants a template specialization. So
8991 // we need to insert '<>' after the name.
8992 SourceLocation InsertLoc;
8993 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8994 InsertLoc = D.getName().getSourceRange().getEnd();
8995 InsertLoc = getLocForEndOfToken(InsertLoc);
8996 }
8997
8998 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8999 << Name << RemoveRange
9000 << FixItHint::CreateRemoval(RemoveRange)
9001 << FixItHint::CreateInsertion(InsertLoc, "<>");
9002 }
9003 }
9004 } else {
9005 // Check that we can declare a template here.
9006 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9007 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9008 NewFD->setInvalidDecl();
9009
9010 // All template param lists were matched against the scope specifier:
9011 // this is NOT (an explicit specialization of) a template.
9012 if (TemplateParamLists.size() > 0)
9013 // For source fidelity, store all the template param lists.
9014 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9015 }
9016
9017 if (Invalid) {
9018 NewFD->setInvalidDecl();
9019 if (FunctionTemplate)
9020 FunctionTemplate->setInvalidDecl();
9021 }
9022
9023 // C++ [dcl.fct.spec]p5:
9024 // The virtual specifier shall only be used in declarations of
9025 // nonstatic class member functions that appear within a
9026 // member-specification of a class declaration; see 10.3.
9027 //
9028 if (isVirtual && !NewFD->isInvalidDecl()) {
9029 if (!isVirtualOkay) {
9030 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9031 diag::err_virtual_non_function);
9032 } else if (!CurContext->isRecord()) {
9033 // 'virtual' was specified outside of the class.
9034 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9035 diag::err_virtual_out_of_class)
9036 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9037 } else if (NewFD->getDescribedFunctionTemplate()) {
9038 // C++ [temp.mem]p3:
9039 // A member function template shall not be virtual.
9040 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9041 diag::err_virtual_member_function_template)
9042 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9043 } else {
9044 // Okay: Add virtual to the method.
9045 NewFD->setVirtualAsWritten(true);
9046 }
9047
9048 if (getLangOpts().CPlusPlus14 &&
9049 NewFD->getReturnType()->isUndeducedType())
9050 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9051 }
9052
9053 if (getLangOpts().CPlusPlus14 &&
9054 (NewFD->isDependentContext() ||
9055 (isFriend && CurContext->isDependentContext())) &&
9056 NewFD->getReturnType()->isUndeducedType()) {
9057 // If the function template is referenced directly (for instance, as a
9058 // member of the current instantiation), pretend it has a dependent type.
9059 // This is not really justified by the standard, but is the only sane
9060 // thing to do.
9061 // FIXME: For a friend function, we have not marked the function as being
9062 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9063 const FunctionProtoType *FPT =
9064 NewFD->getType()->castAs<FunctionProtoType>();
9065 QualType Result =
9066 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9067 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9068 FPT->getExtProtoInfo()));
9069 }
9070
9071 // C++ [dcl.fct.spec]p3:
9072 // The inline specifier shall not appear on a block scope function
9073 // declaration.
9074 if (isInline && !NewFD->isInvalidDecl()) {
9075 if (CurContext->isFunctionOrMethod()) {
9076 // 'inline' is not allowed on block scope function declaration.
9077 Diag(D.getDeclSpec().getInlineSpecLoc(),
9078 diag::err_inline_declaration_block_scope) << Name
9079 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9080 }
9081 }
9082
9083 // C++ [dcl.fct.spec]p6:
9084 // The explicit specifier shall be used only in the declaration of a
9085 // constructor or conversion function within its class definition;
9086 // see 12.3.1 and 12.3.2.
9087 if (hasExplicit && !NewFD->isInvalidDecl() &&
9088 !isa<CXXDeductionGuideDecl>(NewFD)) {
9089 if (!CurContext->isRecord()) {
9090 // 'explicit' was specified outside of the class.
9091 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9092 diag::err_explicit_out_of_class)
9093 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9094 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9095 !isa<CXXConversionDecl>(NewFD)) {
9096 // 'explicit' was specified on a function that wasn't a constructor
9097 // or conversion function.
9098 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9099 diag::err_explicit_non_ctor_or_conv_function)
9100 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9101 }
9102 }
9103
9104 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9105 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9106 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9107 // are implicitly inline.
9108 NewFD->setImplicitlyInline();
9109
9110 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9111 // be either constructors or to return a literal type. Therefore,
9112 // destructors cannot be declared constexpr.
9113 if (isa<CXXDestructorDecl>(NewFD) &&
9114 (!getLangOpts().CPlusPlus20 ||
9115 ConstexprKind == ConstexprSpecKind::Consteval)) {
9116 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9117 << static_cast<int>(ConstexprKind);
9118 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9119 ? ConstexprSpecKind::Unspecified
9120 : ConstexprSpecKind::Constexpr);
9121 }
9122 // C++20 [dcl.constexpr]p2: An allocation function, or a
9123 // deallocation function shall not be declared with the consteval
9124 // specifier.
9125 if (ConstexprKind == ConstexprSpecKind::Consteval &&
9126 (NewFD->getOverloadedOperator() == OO_New ||
9127 NewFD->getOverloadedOperator() == OO_Array_New ||
9128 NewFD->getOverloadedOperator() == OO_Delete ||
9129 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9130 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9131 diag::err_invalid_consteval_decl_kind)
9132 << NewFD;
9133 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9134 }
9135 }
9136
9137 // If __module_private__ was specified, mark the function accordingly.
9138 if (D.getDeclSpec().isModulePrivateSpecified()) {
9139 if (isFunctionTemplateSpecialization) {
9140 SourceLocation ModulePrivateLoc
9141 = D.getDeclSpec().getModulePrivateSpecLoc();
9142 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9143 << 0
9144 << FixItHint::CreateRemoval(ModulePrivateLoc);
9145 } else {
9146 NewFD->setModulePrivate();
9147 if (FunctionTemplate)
9148 FunctionTemplate->setModulePrivate();
9149 }
9150 }
9151
9152 if (isFriend) {
9153 if (FunctionTemplate) {
9154 FunctionTemplate->setObjectOfFriendDecl();
9155 FunctionTemplate->setAccess(AS_public);
9156 }
9157 NewFD->setObjectOfFriendDecl();
9158 NewFD->setAccess(AS_public);
9159 }
9160
9161 // If a function is defined as defaulted or deleted, mark it as such now.
9162 // We'll do the relevant checks on defaulted / deleted functions later.
9163 switch (D.getFunctionDefinitionKind()) {
9164 case FunctionDefinitionKind::Declaration:
9165 case FunctionDefinitionKind::Definition:
9166 break;
9167
9168 case FunctionDefinitionKind::Defaulted:
9169 NewFD->setDefaulted();
9170 break;
9171
9172 case FunctionDefinitionKind::Deleted:
9173 NewFD->setDeletedAsWritten();
9174 break;
9175 }
9176
9177 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9178 D.isFunctionDefinition()) {
9179 // C++ [class.mfct]p2:
9180 // A member function may be defined (8.4) in its class definition, in
9181 // which case it is an inline member function (7.1.2)
9182 NewFD->setImplicitlyInline();
9183 }
9184
9185 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9186 !CurContext->isRecord()) {
9187 // C++ [class.static]p1:
9188 // A data or function member of a class may be declared static
9189 // in a class definition, in which case it is a static member of
9190 // the class.
9191
9192 // Complain about the 'static' specifier if it's on an out-of-line
9193 // member function definition.
9194
9195 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9196 // member function template declaration and class member template
9197 // declaration (MSVC versions before 2015), warn about this.
9198 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9199 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9200 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9201 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9202 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9203 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9204 }
9205
9206 // C++11 [except.spec]p15:
9207 // A deallocation function with no exception-specification is treated
9208 // as if it were specified with noexcept(true).
9209 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9210 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9211 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9212 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9213 NewFD->setType(Context.getFunctionType(
9214 FPT->getReturnType(), FPT->getParamTypes(),
9215 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9216 }
9217
9218 // Filter out previous declarations that don't match the scope.
9219 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9220 D.getCXXScopeSpec().isNotEmpty() ||
9221 isMemberSpecialization ||
9222 isFunctionTemplateSpecialization);
9223
9224 // Handle GNU asm-label extension (encoded as an attribute).
9225 if (Expr *E = (Expr*) D.getAsmLabel()) {
9226 // The parser guarantees this is a string.
9227 StringLiteral *SE = cast<StringLiteral>(E);
9228 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9229 /*IsLiteralLabel=*/true,
9230 SE->getStrTokenLoc(0)));
9231 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9232 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9233 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9234 if (I != ExtnameUndeclaredIdentifiers.end()) {
9235 if (isDeclExternC(NewFD)) {
9236 NewFD->addAttr(I->second);
9237 ExtnameUndeclaredIdentifiers.erase(I);
9238 } else
9239 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9240 << /*Variable*/0 << NewFD;
9241 }
9242 }
9243
9244 // Copy the parameter declarations from the declarator D to the function
9245 // declaration NewFD, if they are available. First scavenge them into Params.
9246 SmallVector<ParmVarDecl*, 16> Params;
9247 unsigned FTIIdx;
9248 if (D.isFunctionDeclarator(FTIIdx)) {
9249 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9250
9251 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9252 // function that takes no arguments, not a function that takes a
9253 // single void argument.
9254 // We let through "const void" here because Sema::GetTypeForDeclarator
9255 // already checks for that case.
9256 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9257 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9258 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9259 assert(Param->getDeclContext() != NewFD && "Was set before ?")((Param->getDeclContext() != NewFD && "Was set before ?"
) ? static_cast<void> (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 9259, __PRETTY_FUNCTION__))
;
9260 Param->setDeclContext(NewFD);
9261 Params.push_back(Param);
9262
9263 if (Param->isInvalidDecl())
9264 NewFD->setInvalidDecl();
9265 }
9266 }
9267
9268 if (!getLangOpts().CPlusPlus) {
9269 // In C, find all the tag declarations from the prototype and move them
9270 // into the function DeclContext. Remove them from the surrounding tag
9271 // injection context of the function, which is typically but not always
9272 // the TU.
9273 DeclContext *PrototypeTagContext =
9274 getTagInjectionContext(NewFD->getLexicalDeclContext());
9275 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9276 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9277
9278 // We don't want to reparent enumerators. Look at their parent enum
9279 // instead.
9280 if (!TD) {
9281 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9282 TD = cast<EnumDecl>(ECD->getDeclContext());
9283 }
9284 if (!TD)
9285 continue;
9286 DeclContext *TagDC = TD->getLexicalDeclContext();
9287 if (!TagDC->containsDecl(TD))
9288 continue;
9289 TagDC->removeDecl(TD);
9290 TD->setDeclContext(NewFD);
9291 NewFD->addDecl(TD);
9292
9293 // Preserve the lexical DeclContext if it is not the surrounding tag
9294 // injection context of the FD. In this example, the semantic context of
9295 // E will be f and the lexical context will be S, while both the
9296 // semantic and lexical contexts of S will be f:
9297 // void f(struct S { enum E { a } f; } s);
9298 if (TagDC != PrototypeTagContext)
9299 TD->setLexicalDeclContext(TagDC);
9300 }
9301 }
9302 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9303 // When we're declaring a function with a typedef, typeof, etc as in the
9304 // following example, we'll need to synthesize (unnamed)
9305 // parameters for use in the declaration.
9306 //
9307 // @code
9308 // typedef void fn(int);
9309 // fn f;
9310 // @endcode
9311
9312 // Synthesize a parameter for each argument type.
9313 for (const auto &AI : FT->param_types()) {
9314 ParmVarDecl *Param =
9315 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9316 Param->setScopeInfo(0, Params.size());
9317 Params.push_back(Param);
9318 }
9319 } else {
9320 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&((R->isFunctionNoProtoType() && NewFD->getNumParams
() == 0 && "Should not need args for typedef of non-prototype fn"
) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 9321, __PRETTY_FUNCTION__))
9321 "Should not need args for typedef of non-prototype fn")((R->isFunctionNoProtoType() && NewFD->getNumParams
() == 0 && "Should not need args for typedef of non-prototype fn"
) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 9321, __PRETTY_FUNCTION__))
;
9322 }
9323
9324 // Finally, we know we have the right number of parameters, install them.
9325 NewFD->setParams(Params);
9326
9327 if (D.getDeclSpec().isNoreturnSpecified())
9328 NewFD->addAttr(C11NoReturnAttr::Create(Context,
9329 D.getDeclSpec().getNoreturnSpecLoc(),
9330 AttributeCommonInfo::AS_Keyword));
9331
9332 // Functions returning a variably modified type violate C99 6.7.5.2p2
9333 // because all functions have linkage.
9334 if (!NewFD->isInvalidDecl() &&
9335 NewFD->getReturnType()->isVariablyModifiedType()) {
9336 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9337 NewFD->setInvalidDecl();
9338 }
9339
9340 // Apply an implicit SectionAttr if '#pragma clang section text' is active
9341 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9342 !NewFD->hasAttr<SectionAttr>())
9343 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9344 Context, PragmaClangTextSection.SectionName,
9345 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9346
9347 // Apply an implicit SectionAttr if #pragma code_seg is active.
9348 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9349 !NewFD->hasAttr<SectionAttr>()) {
9350 NewFD->addAttr(SectionAttr::CreateImplicit(
9351 Context, CodeSegStack.CurrentValue->getString(),
9352 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9353 SectionAttr::Declspec_allocate));
9354 if (UnifySection(CodeSegStack.CurrentValue->getString(),
9355 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9356 ASTContext::PSF_Read,
9357 NewFD))
9358 NewFD->dropAttr<SectionAttr>();
9359 }
9360
9361 // Apply an implicit CodeSegAttr from class declspec or
9362 // apply an implicit SectionAttr from #pragma code_seg if active.
9363 if (!NewFD->hasAttr<CodeSegAttr>()) {
9364 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9365 D.isFunctionDefinition())) {
9366 NewFD->addAttr(SAttr);
9367 }
9368 }
9369
9370 // Handle attributes.
9371 ProcessDeclAttributes(S, NewFD, D);
9372
9373 if (getLangOpts().OpenCL) {
9374 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9375 // type declaration will generate a compilation error.
9376 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9377 if (AddressSpace != LangAS::Default) {
9378 Diag(NewFD->getLocation(),
9379 diag::err_opencl_return_value_with_address_space);
9380 NewFD->setInvalidDecl();
9381 }
9382 }
9383
9384 if (!getLangOpts().CPlusPlus) {
9385 // Perform semantic checking on the function declaration.
9386 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9387 CheckMain(NewFD, D.getDeclSpec());
9388
9389 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9390 CheckMSVCRTEntryPoint(NewFD);
9391
9392 if (!NewFD->isInvalidDecl())
9393 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9394 isMemberSpecialization));
9395 else if (!Previous.empty())
9396 // Recover gracefully from an invalid redeclaration.
9397 D.setRedeclaration(true);
9398 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 9400, __PRETTY_FUNCTION__))
9399 Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 9400, __PRETTY_FUNCTION__))
9400 "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 9400, __PRETTY_FUNCTION__))
;
9401
9402 // Diagnose no-prototype function declarations with calling conventions that
9403 // don't support variadic calls. Only do this in C and do it after merging
9404 // possibly prototyped redeclarations.
9405 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9406 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9407 CallingConv CC = FT->getExtInfo().getCC();
9408 if (!supportsVariadicCall(CC)) {
9409 // Windows system headers sometimes accidentally use stdcall without
9410 // (void) parameters, so we relax this to a warning.
9411 int DiagID =
9412 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9413 Diag(NewFD->getLocation(), DiagID)
9414 << FunctionType::getNameForCallConv(CC);
9415 }
9416 }
9417
9418 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9419 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9420 checkNonTrivialCUnion(NewFD->getReturnType(),
9421 NewFD->getReturnTypeSourceRange().getBegin(),
9422 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9423 } else {
9424 // C++11 [replacement.functions]p3:
9425 // The program's definitions shall not be specified as inline.
9426 //
9427 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9428 //
9429 // Suppress the diagnostic if the function is __attribute__((used)), since
9430 // that forces an external definition to be emitted.
9431 if (D.getDeclSpec().isInlineSpecified() &&
9432 NewFD->isReplaceableGlobalAllocationFunction() &&
9433 !NewFD->hasAttr<UsedAttr>())
9434 Diag(D.getDeclSpec().getInlineSpecLoc(),
9435 diag::ext_operator_new_delete_declared_inline)
9436 << NewFD->getDeclName();
9437
9438 // If the declarator is a template-id, translate the parser's template
9439 // argument list into our AST format.
9440 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9441 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9442 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9443 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9444 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9445 TemplateId->NumArgs);
9446 translateTemplateArguments(TemplateArgsPtr,
9447 TemplateArgs);
9448
9449 HasExplicitTemplateArgs = true;
9450
9451 if (NewFD->isInvalidDecl()) {
9452 HasExplicitTemplateArgs = false;
9453 } else if (FunctionTemplate) {
9454 // Function template with explicit template arguments.
9455 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9456 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9457
9458 HasExplicitTemplateArgs = false;
9459 } else {
9460 assert((isFunctionTemplateSpecialization ||(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified
()) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 9462, __PRETTY_FUNCTION__))
9461 D.getDeclSpec().isFriendSpecified()) &&(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified
()) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 9462, __PRETTY_FUNCTION__))
9462 "should have a 'template<>' for this decl")(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified
()) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 9462, __PRETTY_FUNCTION__))
;
9463 // "friend void foo<>(int);" is an implicit specialization decl.
9464 isFunctionTemplateSpecialization = true;
9465 }
9466 } else if (isFriend && isFunctionTemplateSpecialization) {
9467 // This combination is only possible in a recovery case; the user
9468 // wrote something like:
9469 // template <> friend void foo(int);
9470 // which we're recovering from as if the user had written:
9471 // friend void foo<>(int);
9472 // Go ahead and fake up a template id.
9473 HasExplicitTemplateArgs = true;
9474 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9475 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9476 }
9477
9478 // We do not add HD attributes to specializations here because
9479 // they may have different constexpr-ness compared to their
9480 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9481 // may end up with different effective targets. Instead, a
9482 // specialization inherits its target attributes from its template
9483 // in the CheckFunctionTemplateSpecialization() call below.
9484 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9485 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9486
9487 // If it's a friend (and only if it's a friend), it's possible
9488 // that either the specialized function type or the specialized
9489 // template is dependent, and therefore matching will fail. In
9490 // this case, don't check the specialization yet.
9491 bool InstantiationDependent = false;
9492 if (isFunctionTemplateSpecialization && isFriend &&
9493 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9494 TemplateSpecializationType::anyDependentTemplateArguments(
9495 TemplateArgs,
9496 InstantiationDependent))) {
9497 assert(HasExplicitTemplateArgs &&((HasExplicitTemplateArgs && "friend function specialization without template args"
) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 9498, __PRETTY_FUNCTION__))
9498 "friend function specialization without template args")((HasExplicitTemplateArgs && "friend function specialization without template args"
) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 9498, __PRETTY_FUNCTION__))
;
9499 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9500 Previous))
9501 NewFD->setInvalidDecl();
9502 } else if (isFunctionTemplateSpecialization) {
9503 if (CurContext->isDependentContext() && CurContext->isRecord()
9504 && !isFriend) {
9505 isDependentClassScopeExplicitSpecialization = true;
9506 } else if (!NewFD->isInvalidDecl() &&
9507 CheckFunctionTemplateSpecialization(
9508 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9509 Previous))
9510 NewFD->setInvalidDecl();
9511
9512 // C++ [dcl.stc]p1:
9513 // A storage-class-specifier shall not be specified in an explicit
9514 // specialization (14.7.3)
9515 FunctionTemplateSpecializationInfo *Info =
9516 NewFD->getTemplateSpecializationInfo();
9517 if (Info && SC != SC_None) {
9518 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9519 Diag(NewFD->getLocation(),
9520 diag::err_explicit_specialization_inconsistent_storage_class)
9521 << SC
9522 << FixItHint::CreateRemoval(
9523 D.getDeclSpec().getStorageClassSpecLoc());
9524
9525 else
9526 Diag(NewFD->getLocation(),
9527 diag::ext_explicit_specialization_storage_class)
9528 << FixItHint::CreateRemoval(
9529 D.getDeclSpec().getStorageClassSpecLoc());
9530 }
9531 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9532 if (CheckMemberSpecialization(NewFD, Previous))
9533 NewFD->setInvalidDecl();
9534 }
9535
9536 // Perform semantic checking on the function declaration.
9537 if (!isDependentClassScopeExplicitSpecialization) {
9538 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9539 CheckMain(NewFD, D.getDeclSpec());
9540
9541 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9542 CheckMSVCRTEntryPoint(NewFD);
9543
9544 if (!NewFD->isInvalidDecl())
9545 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9546 isMemberSpecialization));
9547 else if (!Previous.empty())
9548 // Recover gracefully from an invalid redeclaration.
9549 D.setRedeclaration(true);
9550 }
9551
9552 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 9554, __PRETTY_FUNCTION__))
9553 Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 9554, __PRETTY_FUNCTION__))
9554 "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 9554, __PRETTY_FUNCTION__))
;
9555
9556 NamedDecl *PrincipalDecl = (FunctionTemplate
9557 ? cast<NamedDecl>(FunctionTemplate)
9558 : NewFD);
9559
9560 if (isFriend && NewFD->getPreviousDecl()) {
9561 AccessSpecifier Access = AS_public;
9562 if (!NewFD->isInvalidDecl())
9563 Access = NewFD->getPreviousDecl()->getAccess();
9564
9565 NewFD->setAccess(Access);
9566 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9567 }
9568
9569 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9570 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9571 PrincipalDecl->setNonMemberOperator();
9572
9573 // If we have a function template, check the template parameter
9574 // list. This will check and merge default template arguments.
9575 if (FunctionTemplate) {
9576 FunctionTemplateDecl *PrevTemplate =
9577 FunctionTemplate->getPreviousDecl();
9578 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9579 PrevTemplate ? PrevTemplate->getTemplateParameters()
9580 : nullptr,
9581 D.getDeclSpec().isFriendSpecified()
9582 ? (D.isFunctionDefinition()
9583 ? TPC_FriendFunctionTemplateDefinition
9584 : TPC_FriendFunctionTemplate)
9585 : (D.getCXXScopeSpec().isSet() &&
9586 DC && DC->isRecord() &&
9587 DC->isDependentContext())
9588 ? TPC_ClassTemplateMember
9589 : TPC_FunctionTemplate);
9590 }
9591
9592 if (NewFD->isInvalidDecl()) {
9593 // Ignore all the rest of this.
9594 } else if (!D.isRedeclaration()) {
9595 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9596 AddToScope };
9597 // Fake up an access specifier if it's supposed to be a class member.
9598 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9599 NewFD->setAccess(AS_public);
9600
9601 // Qualified decls generally require a previous declaration.
9602 if (D.getCXXScopeSpec().isSet()) {
9603 // ...with the major exception of templated-scope or
9604 // dependent-scope friend declarations.
9605
9606 // TODO: we currently also suppress this check in dependent
9607 // contexts because (1) the parameter depth will be off when
9608 // matching friend templates and (2) we might actually be
9609 // selecting a friend based on a dependent factor. But there
9610 // are situations where these conditions don't apply and we
9611 // can actually do this check immediately.
9612 //
9613 // Unless the scope is dependent, it's always an error if qualified
9614 // redeclaration lookup found nothing at all. Diagnose that now;
9615 // nothing will diagnose that error later.
9616 if (isFriend &&
9617 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9618 (!Previous.empty() && CurContext->isDependentContext()))) {
9619 // ignore these
9620 } else {
9621 // The user tried to provide an out-of-line definition for a
9622 // function that is a member of a class or namespace, but there
9623 // was no such member function declared (C++ [class.mfct]p2,
9624 // C++ [namespace.memdef]p2). For example:
9625 //
9626 // class X {
9627 // void f() const;
9628 // };
9629 //
9630 // void X::f() { } // ill-formed
9631 //
9632 // Complain about this problem, and attempt to suggest close
9633 // matches (e.g., those that differ only in cv-qualifiers and
9634 // whether the parameter types are references).
9635
9636 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9637 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9638 AddToScope = ExtraArgs.AddToScope;
9639 return Result;
9640 }
9641 }
9642
9643 // Unqualified local friend declarations are required to resolve
9644 // to something.
9645 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9646 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9647 *this, Previous, NewFD, ExtraArgs, true, S)) {
9648 AddToScope = ExtraArgs.AddToScope;
9649 return Result;
9650 }
9651 }
9652 } else if (!D.isFunctionDefinition() &&
9653 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9654 !isFriend && !isFunctionTemplateSpecialization &&
9655 !isMemberSpecialization) {
9656 // An out-of-line member function declaration must also be a
9657 // definition (C++ [class.mfct]p2).
9658 // Note that this is not the case for explicit specializations of
9659 // function templates or member functions of class templates, per
9660 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9661 // extension for compatibility with old SWIG code which likes to
9662 // generate them.
9663 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9664 << D.getCXXScopeSpec().getRange();
9665 }
9666 }
9667
9668 // If this is the first declaration of a library builtin function, add
9669 // attributes as appropriate.
9670 if (!D.isRedeclaration() &&
9671 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9672 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9673 if (unsigned BuiltinID = II->getBuiltinID()) {
9674 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9675 // Validate the type matches unless this builtin is specified as
9676 // matching regardless of its declared type.
9677 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9678 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9679 } else {
9680 ASTContext::GetBuiltinTypeError Error;
9681 LookupNecessaryTypesForBuiltin(S, BuiltinID);
9682 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9683
9684 if (!Error && !BuiltinType.isNull() &&
9685 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9686 NewFD->getType(), BuiltinType))
9687 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9688 }
9689 } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9690 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9691 // FIXME: We should consider this a builtin only in the std namespace.
9692 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9693 }
9694 }
9695 }
9696 }
9697
9698 ProcessPragmaWeak(S, NewFD);
9699 checkAttributesAfterMerging(*this, *NewFD);
9700
9701 AddKnownFunctionAttributes(NewFD);
9702
9703 if (NewFD->hasAttr<OverloadableAttr>() &&
9704 !NewFD->getType()->getAs<FunctionProtoType>()) {
9705 Diag(NewFD->getLocation(),
9706 diag::err_attribute_overloadable_no_prototype)
9707 << NewFD;
9708
9709 // Turn this into a variadic function with no parameters.
9710 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9711 FunctionProtoType::ExtProtoInfo EPI(
9712 Context.getDefaultCallingConvention(true, false));
9713 EPI.Variadic = true;
9714 EPI.ExtInfo = FT->getExtInfo();
9715
9716 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9717 NewFD->setType(R);
9718 }
9719
9720 // If there's a #pragma GCC visibility in scope, and this isn't a class
9721 // member, set the visibility of this function.
9722 if (!DC->isRecord() && NewFD->isExternallyVisible())
9723 AddPushedVisibilityAttribute(NewFD);
9724
9725 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9726 // marking the function.
9727 AddCFAuditedAttribute(NewFD);
9728
9729 // If this is a function definition, check if we have to apply optnone due to
9730 // a pragma.
9731 if(D.isFunctionDefinition())
9732 AddRangeBasedOptnone(NewFD);
9733
9734 // If this is the first declaration of an extern C variable, update
9735 // the map of such variables.
9736 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9737 isIncompleteDeclExternC(*this, NewFD))
9738 RegisterLocallyScopedExternCDecl(NewFD, S);
9739
9740 // Set this FunctionDecl's range up to the right paren.
9741 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9742
9743 if (D.isRedeclaration() && !Previous.empty()) {
9744 NamedDecl *Prev = Previous.getRepresentativeDecl();
9745 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9746 isMemberSpecialization ||
9747 isFunctionTemplateSpecialization,
9748 D.isFunctionDefinition());
9749 }
9750
9751 if (getLangOpts().CUDA) {
9752 IdentifierInfo *II = NewFD->getIdentifier();
9753 if (II && II->isStr(getCudaConfigureFuncName()) &&
9754 !NewFD->isInvalidDecl() &&
9755 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9756 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9757 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9758 << getCudaConfigureFuncName();
9759 Context.setcudaConfigureCallDecl(NewFD);
9760 }
9761
9762 // Variadic functions, other than a *declaration* of printf, are not allowed
9763 // in device-side CUDA code, unless someone passed
9764 // -fcuda-allow-variadic-functions.
9765 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9766 (NewFD->hasAttr<CUDADeviceAttr>() ||
9767 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9768 !(II && II->isStr("printf") && NewFD->isExternC() &&
9769 !D.isFunctionDefinition())) {
9770 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9771 }
9772 }
9773
9774 MarkUnusedFileScopedDecl(NewFD);
9775
9776
9777
9778 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9779 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9780 if ((getLangOpts().OpenCLVersion >= 120)
9781 && (SC == SC_Static)) {
9782 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9783 D.setInvalidType();
9784 }
9785
9786 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9787 if (!NewFD->getReturnType()->isVoidType()) {
9788 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9789 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9790 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9791 : FixItHint());
9792 D.setInvalidType();
9793 }
9794
9795 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9796 for (auto Param : NewFD->parameters())
9797 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9798
9799 if (getLangOpts().OpenCLCPlusPlus) {
9800 if (DC->isRecord()) {
9801 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9802 D.setInvalidType();
9803 }
9804 if (FunctionTemplate) {
9805 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9806 D.setInvalidType();
9807 }
9808 }
9809 }
9810
9811 if (getLangOpts().CPlusPlus) {
9812 if (FunctionTemplate) {
9813 if (NewFD->isInvalidDecl())
9814 FunctionTemplate->setInvalidDecl();
9815 return FunctionTemplate;
9816 }
9817
9818 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9819 CompleteMemberSpecialization(NewFD, Previous);
9820 }
9821
9822 for (const ParmVarDecl *Param : NewFD->parameters()) {
9823 QualType PT = Param->getType();
9824
9825 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9826 // types.
9827 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9828 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9829 QualType ElemTy = PipeTy->getElementType();
9830 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9831 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9832 D.setInvalidType();
9833 }
9834 }
9835 }
9836 }
9837
9838 // Here we have an function template explicit specialization at class scope.
9839 // The actual specialization will be postponed to template instatiation
9840 // time via the ClassScopeFunctionSpecializationDecl node.
9841 if (isDependentClassScopeExplicitSpecialization) {
9842 ClassScopeFunctionSpecializationDecl *NewSpec =
9843 ClassScopeFunctionSpecializationDecl::Create(
9844 Context, CurContext, NewFD->getLocation(),
9845 cast<CXXMethodDecl>(NewFD),
9846 HasExplicitTemplateArgs, TemplateArgs);
9847 CurContext->addDecl(NewSpec);
9848 AddToScope = false;
9849 }
9850
9851 // Diagnose availability attributes. Availability cannot be used on functions
9852 // that are run during load/unload.
9853 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9854 if (NewFD->hasAttr<ConstructorAttr>()) {
9855 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9856 << 1;
9857 NewFD->dropAttr<AvailabilityAttr>();
9858 }
9859 if (NewFD->hasAttr<DestructorAttr>()) {
9860 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9861 << 2;
9862 NewFD->dropAttr<AvailabilityAttr>();
9863 }
9864 }
9865
9866 // Diagnose no_builtin attribute on function declaration that are not a
9867 // definition.
9868 // FIXME: We should really be doing this in
9869 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9870 // the FunctionDecl and at this point of the code
9871 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9872 // because Sema::ActOnStartOfFunctionDef has not been called yet.
9873 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9874 switch (D.getFunctionDefinitionKind()) {
9875 case FunctionDefinitionKind::Defaulted:
9876 case FunctionDefinitionKind::Deleted:
9877 Diag(NBA->getLocation(),
9878 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9879 << NBA->getSpelling();
9880 break;
9881 case FunctionDefinitionKind::Declaration:
9882 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9883 << NBA->getSpelling();
9884 break;
9885 case FunctionDefinitionKind::Definition:
9886 break;
9887 }
9888
9889 return NewFD;
9890}
9891
9892/// Return a CodeSegAttr from a containing class. The Microsoft docs say
9893/// when __declspec(code_seg) "is applied to a class, all member functions of
9894/// the class and nested classes -- this includes compiler-generated special
9895/// member functions -- are put in the specified segment."
9896/// The actual behavior is a little more complicated. The Microsoft compiler
9897/// won't check outer classes if there is an active value from #pragma code_seg.
9898/// The CodeSeg is always applied from the direct parent but only from outer
9899/// classes when the #pragma code_seg stack is empty. See:
9900/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9901/// available since MS has removed the page.
9902static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9903 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9904 if (!Method)
9905 return nullptr;
9906 const CXXRecordDecl *Parent = Method->getParent();
9907 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9908 Attr *NewAttr = SAttr->clone(S.getASTContext());
9909 NewAttr->setImplicit(true);
9910 return NewAttr;
9911 }
9912
9913 // The Microsoft compiler won't check outer classes for the CodeSeg
9914 // when the #pragma code_seg stack is active.
9915 if (S.CodeSegStack.CurrentValue)
9916 return nullptr;
9917
9918 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9919 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9920 Attr *NewAttr = SAttr->clone(S.getASTContext());
9921 NewAttr->setImplicit(true);
9922 return NewAttr;
9923 }
9924 }
9925 return nullptr;
9926}
9927
9928/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9929/// containing class. Otherwise it will return implicit SectionAttr if the
9930/// function is a definition and there is an active value on CodeSegStack
9931/// (from the current #pragma code-seg value).
9932///
9933/// \param FD Function being declared.
9934/// \param IsDefinition Whether it is a definition or just a declarartion.
9935/// \returns A CodeSegAttr or SectionAttr to apply to the function or
9936/// nullptr if no attribute should be added.
9937Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9938 bool IsDefinition) {
9939 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9940 return A;
9941 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9942 CodeSegStack.CurrentValue)
9943 return SectionAttr::CreateImplicit(
9944 getASTContext(), CodeSegStack.CurrentValue->getString(),
9945 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9946 SectionAttr::Declspec_allocate);
9947 return nullptr;
9948}
9949
9950/// Determines if we can perform a correct type check for \p D as a
9951/// redeclaration of \p PrevDecl. If not, we can generally still perform a
9952/// best-effort check.
9953///
9954/// \param NewD The new declaration.
9955/// \param OldD The old declaration.
9956/// \param NewT The portion of the type of the new declaration to check.
9957/// \param OldT The portion of the type of the old declaration to check.
9958bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9959 QualType NewT, QualType OldT) {
9960 if (!NewD->getLexicalDeclContext()->isDependentContext())
9961 return true;
9962
9963 // For dependently-typed local extern declarations and friends, we can't
9964 // perform a correct type check in general until instantiation:
9965 //
9966 // int f();
9967 // template<typename T> void g() { T f(); }
9968 //
9969 // (valid if g() is only instantiated with T = int).
9970 if (NewT->isDependentType() &&
9971 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9972 return false;
9973
9974 // Similarly, if the previous declaration was a dependent local extern
9975 // declaration, we don't really know its type yet.
9976 if (OldT->isDependentType() && OldD->isLocalExternDecl())
9977 return false;
9978
9979 return true;
9980}
9981
9982/// Checks if the new declaration declared in dependent context must be
9983/// put in the same redeclaration chain as the specified declaration.
9984///
9985/// \param D Declaration that is checked.
9986/// \param PrevDecl Previous declaration found with proper lookup method for the
9987/// same declaration name.
9988/// \returns True if D must be added to the redeclaration chain which PrevDecl
9989/// belongs to.
9990///
9991bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9992 if (!D->getLexicalDeclContext()->isDependentContext())
9993 return true;
9994
9995 // Don't chain dependent friend function definitions until instantiation, to
9996 // permit cases like
9997 //
9998 // void func();
9999 // template<typename T> class C1 { friend void func() {} };
10000 // template<typename T> class C2 { friend void func() {} };
10001 //
10002 // ... which is valid if only one of C1 and C2 is ever instantiated.
10003 //
10004 // FIXME: This need only apply to function definitions. For now, we proxy
10005 // this by checking for a file-scope function. We do not want this to apply
10006 // to friend declarations nominating member functions, because that gets in
10007 // the way of access checks.
10008 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10009 return false;
10010
10011 auto *VD = dyn_cast<ValueDecl>(D);
10012 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10013 return !VD || !PrevVD ||
10014 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10015 PrevVD->getType());
10016}
10017
10018/// Check the target attribute of the function for MultiVersion
10019/// validity.
10020///
10021/// Returns true if there was an error, false otherwise.
10022static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10023 const auto *TA = FD->getAttr<TargetAttr>();
10024 assert(TA && "MultiVersion Candidate requires a target attribute")((TA && "MultiVersion Candidate requires a target attribute"
) ? static_cast<void> (0) : __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 10024, __PRETTY_FUNCTION__))
;
10025 ParsedTargetAttr ParseInfo = TA->parse();
10026 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10027 enum ErrType { Feature = 0, Architecture = 1 };
10028
10029 if (!ParseInfo.Architecture.empty() &&
10030 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10031 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10032 << Architecture << ParseInfo.Architecture;
10033 return true;
10034 }
10035
10036 for (const auto &Feat : ParseInfo.Features) {
10037 auto BareFeat = StringRef{Feat}.substr(1);
10038 if (Feat[0] == '-') {
10039 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10040 << Feature << ("no-" + BareFeat).str();
10041 return true;
10042 }
10043
10044 if (!TargetInfo.validateCpuSupports(BareFeat) ||
10045 !TargetInfo.isValidFeatureName(BareFeat)) {
10046 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10047 << Feature << BareFeat;
10048 return true;
10049 }
10050 }
10051 return false;
10052}
10053
10054// Provide a white-list of attributes that are allowed to be combined with
10055// multiversion functions.
10056static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10057 MultiVersionKind MVType) {
10058 // Note: this list/diagnosis must match the list in
10059 // checkMultiversionAttributesAllSame.
10060 switch (Kind) {
10061 default:
10062 return false;
10063 case attr::Used:
10064 return MVType == MultiVersionKind::Target;
10065 case attr::NonNull:
10066 case attr::NoThrow:
10067 return true;
10068 }
10069}
10070
10071static bool checkNonMultiVersionCompatAttributes(Sema &S,
10072 const FunctionDecl *FD,
10073 const FunctionDecl *CausedFD,
10074 MultiVersionKind MVType) {
10075 bool IsCPUSpecificCPUDispatchMVType =
10076 MVType == MultiVersionKind::CPUDispatch ||
10077 MVType == MultiVersionKind::CPUSpecific;
10078 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10079 Sema &S, const Attr *A) {
10080 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10081 << IsCPUSpecificCPUDispatchMVType << A;
10082 if (CausedFD)
10083 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10084 return true;
10085 };
10086
10087 for (const Attr *A : FD->attrs()) {
10088 switch (A->getKind()) {
10089 case attr::CPUDispatch:
10090 case attr::CPUSpecific:
10091 if (MVType != MultiVersionKind::CPUDispatch &&
10092 MVType != MultiVersionKind::CPUSpecific)
10093 return Diagnose(S, A);
10094 break;
10095 case attr::Target:
10096 if (MVType != MultiVersionKind::Target)
10097 return Diagnose(S, A);
10098 break;
10099 default:
10100 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10101 return Diagnose(S, A);
10102 break;
10103 }
10104 }
10105 return false;
10106}
10107
10108bool Sema::areMultiversionVariantFunctionsCompatible(
10109 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10110 const PartialDiagnostic &NoProtoDiagID,
10111 const PartialDiagnosticAt &NoteCausedDiagIDAt,
10112 const PartialDiagnosticAt &NoSupportDiagIDAt,
10113 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10114 bool ConstexprSupported, bool CLinkageMayDiffer) {
10115 enum DoesntSupport {
10116 FuncTemplates = 0,
10117 VirtFuncs = 1,
10118 DeducedReturn = 2,
10119 Constructors = 3,
10120 Destructors = 4,
10121 DeletedFuncs = 5,
10122 DefaultedFuncs = 6,
10123 ConstexprFuncs = 7,
10124 ConstevalFuncs = 8,
10125 };
10126 enum Different {
10127 CallingConv = 0,
10128 ReturnType = 1,
10129 ConstexprSpec = 2,
10130 InlineSpec = 3,
10131 StorageClass = 4,
10132 Linkage = 5,
10133 };
10134
10135 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10136 !OldFD->getType()->getAs<FunctionProtoType>()) {
10137 Diag(OldFD->getLocation(), NoProtoDiagID);
10138 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10139 return true;
10140 }
10141
10142 if (NoProtoDiagID.getDiagID() != 0 &&
10143 !NewFD->getType()->getAs<FunctionProtoType>())
10144 return Diag(NewFD->getLocation(), NoProtoDiagID);
10145
10146 if (!TemplatesSupported &&
10147 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10148 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10149 << FuncTemplates;
10150
10151 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10152 if (NewCXXFD->isVirtual())
10153 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10154 << VirtFuncs;
10155
10156 if (isa<CXXConstructorDecl>(NewCXXFD))
10157 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10158 << Constructors;
10159
10160 if (isa<CXXDestructorDecl>(NewCXXFD))
10161 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10162 << Destructors;
10163 }
10164
10165 if (NewFD->isDeleted())
10166 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10167 << DeletedFuncs;
10168
10169 if (NewFD->isDefaulted())
10170 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10171 << DefaultedFuncs;
10172
10173 if (!ConstexprSupported && NewFD->isConstexpr())
10174 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10175 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10176
10177 QualType NewQType = Context.getCanonicalType(NewFD->getType());
10178 const auto *NewType = cast<FunctionType>(NewQType);
10179 QualType NewReturnType = NewType->getReturnType();
10180
10181 if (NewReturnType->isUndeducedType())
10182 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10183 << DeducedReturn;
10184
10185 // Ensure the return type is identical.
10186 if (OldFD) {
10187 QualType OldQType = Context.getCanonicalType(OldFD->getType());
10188 const auto *OldType = cast<FunctionType>(OldQType);
10189 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10190 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10191
10192 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10193 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10194
10195 QualType OldReturnType = OldType->getReturnType();
10196
10197 if (OldReturnType != NewReturnType)
10198 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10199
10200 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10201 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10202
10203 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10204 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10205
10206 if (OldFD->getStorageClass() != NewFD->getStorageClass())
10207 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10208
10209 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10210 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10211
10212 if (CheckEquivalentExceptionSpec(
10213 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10214 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10215 return true;
10216 }
10217 return false;
10218}
10219
10220static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10221 const FunctionDecl *NewFD,
10222 bool CausesMV,
10223 MultiVersionKind MVType) {
10224 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10225 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10226 if (OldFD)
10227 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10228 return true;
10229 }
10230
10231 bool IsCPUSpecificCPUDispatchMVType =
10232 MVType == MultiVersionKind::CPUDispatch ||
10233 MVType == MultiVersionKind::CPUSpecific;
10234
10235 if (CausesMV && OldFD &&
10236 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10237 return true;
10238
10239 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10240 return true;
10241
10242 // Only allow transition to MultiVersion if it hasn't been used.
10243 if (OldFD && CausesMV && OldFD->isUsed(false))
10244 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10245
10246 return S.areMultiversionVariantFunctionsCompatible(
10247 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10248 PartialDiagnosticAt(NewFD->getLocation(),
10249 S.PDiag(diag::note_multiversioning_caused_here)),
10250 PartialDiagnosticAt(NewFD->getLocation(),
10251 S.PDiag(diag::err_multiversion_doesnt_support)
10252 << IsCPUSpecificCPUDispatchMVType),
10253 PartialDiagnosticAt(NewFD->getLocation(),
10254 S.PDiag(diag::err_multiversion_diff)),
10255 /*TemplatesSupported=*/false,
10256 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10257 /*CLinkageMayDiffer=*/false);
10258}
10259
10260/// Check the validity of a multiversion function declaration that is the
10261/// first of its kind. Also sets the multiversion'ness' of the function itself.
10262///
10263/// This sets NewFD->isInvalidDecl() to true if there was an error.
10264///
10265/// Returns true if there was an error, false otherwise.
10266static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10267 MultiVersionKind MVType,
10268 const TargetAttr *TA) {
10269 assert(MVType != MultiVersionKind::None &&((MVType != MultiVersionKind::None && "Function lacks multiversion attribute"
) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 10270, __PRETTY_FUNCTION__))
10270 "Function lacks multiversion attribute")((MVType != MultiVersionKind::None && "Function lacks multiversion attribute"
) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 10270, __PRETTY_FUNCTION__))
;
10271
10272 // Target only causes MV if it is default, otherwise this is a normal
10273 // function.
10274 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10275 return false;
10276
10277 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10278 FD->setInvalidDecl();
10279 return true;
10280 }
10281
10282 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10283 FD->setInvalidDecl();
10284 return true;
10285 }
10286
10287 FD->setIsMultiVersion();
10288 return false;
10289}
10290
10291static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10292 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10293 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10294 return true;
10295 }
10296
10297 return false;
10298}
10299
10300static bool CheckTargetCausesMultiVersioning(
10301 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10302 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10303 LookupResult &Previous) {
10304 const auto *OldTA = OldFD->getAttr<TargetAttr>();
10305 ParsedTargetAttr NewParsed = NewTA->parse();
10306 // Sort order doesn't matter, it just needs to be consistent.
10307 llvm::sort(NewParsed.Features);
10308
10309 // If the old decl is NOT MultiVersioned yet, and we don't cause that
10310 // to change, this is a simple redeclaration.
10311 if (!NewTA->isDefaultVersion() &&
10312 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10313 return false;
10314
10315 // Otherwise, this decl causes MultiVersioning.
10316 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10317 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10318 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10319 NewFD->setInvalidDecl();
10320 return true;
10321 }
10322
10323 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10324 MultiVersionKind::Target)) {
10325 NewFD->setInvalidDecl();
10326 return true;
10327 }
10328
10329 if (CheckMultiVersionValue(S, NewFD)) {
10330 NewFD->setInvalidDecl();
10331 return true;
10332 }
10333
10334 // If this is 'default', permit the forward declaration.
10335 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10336 Redeclaration = true;
10337 OldDecl = OldFD;
10338 OldFD->setIsMultiVersion();
10339 NewFD->setIsMultiVersion();
10340 return false;
10341 }
10342
10343 if (CheckMultiVersionValue(S, OldFD)) {
10344 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10345 NewFD->setInvalidDecl();
10346 return true;
10347 }
10348
10349 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10350
10351 if (OldParsed == NewParsed) {
10352 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10353 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10354 NewFD->setInvalidDecl();
10355 return true;
10356 }
10357
10358 for (const auto *FD : OldFD->redecls()) {
10359 const auto *CurTA = FD->getAttr<TargetAttr>();
10360 // We allow forward declarations before ANY multiversioning attributes, but
10361 // nothing after the fact.
10362 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10363 (!CurTA || CurTA->isInherited())) {
10364 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10365 << 0;
10366 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10367 NewFD->setInvalidDecl();
10368 return true;
10369 }
10370 }
10371
10372 OldFD->setIsMultiVersion();
10373 NewFD->setIsMultiVersion();
10374 Redeclaration = false;
10375 MergeTypeWithPrevious = false;
10376 OldDecl = nullptr;
10377 Previous.clear();
10378 return false;
10379}
10380
10381/// Check the validity of a new function declaration being added to an existing
10382/// multiversioned declaration collection.
10383static bool CheckMultiVersionAdditionalDecl(
10384 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10385 MultiVersionKind NewMVType, const TargetAttr *NewTA,
10386 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10387 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10388 LookupResult &Previous) {
10389
10390 MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10391 // Disallow mixing of multiversioning types.
10392 if ((OldMVType == MultiVersionKind::Target &&
10393 NewMVType != MultiVersionKind::Target) ||
10394 (NewMVType == MultiVersionKind::Target &&
10395 OldMVType != MultiVersionKind::Target)) {
10396 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10397 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10398 NewFD->setInvalidDecl();
10399 return true;
10400 }
10401
10402 ParsedTargetAttr NewParsed;
10403 if (NewTA) {
10404 NewParsed = NewTA->parse();
10405 llvm::sort(NewParsed.Features);
10406 }
10407
10408 bool UseMemberUsingDeclRules =
10409 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10410
10411 // Next, check ALL non-overloads to see if this is a redeclaration of a
10412 // previous member of the MultiVersion set.
10413 for (NamedDecl *ND : Previous) {
10414 FunctionDecl *CurFD = ND->getAsFunction();
10415 if (!CurFD)
10416 continue;
10417 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10418 continue;
10419
10420 if (NewMVType == MultiVersionKind::Target) {
10421 const auto *CurTA = CurFD->getAttr<TargetAttr>();
10422 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10423 NewFD->setIsMultiVersion();
10424 Redeclaration = true;
10425 OldDecl = ND;
10426 return false;
10427 }
10428
10429 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10430 if (CurParsed == NewParsed) {
10431 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10432 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10433 NewFD->setInvalidDecl();
10434 return true;
10435 }
10436 } else {
10437 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10438 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10439 // Handle CPUDispatch/CPUSpecific versions.
10440 // Only 1 CPUDispatch function is allowed, this will make it go through
10441 // the redeclaration errors.
10442 if (NewMVType == MultiVersionKind::CPUDispatch &&
10443 CurFD->hasAttr<CPUDispatchAttr>()) {
10444 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10445 std::equal(
10446 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10447 NewCPUDisp->cpus_begin(),
10448 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10449 return Cur->getName() == New->getName();
10450 })) {
10451 NewFD->setIsMultiVersion();
10452 Redeclaration = true;
10453 OldDecl = ND;
10454 return false;
10455 }
10456
10457 // If the declarations don't match, this is an error condition.
10458 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10459 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10460 NewFD->setInvalidDecl();
10461 return true;
10462 }
10463 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10464
10465 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10466 std::equal(
10467 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10468 NewCPUSpec->cpus_begin(),
10469 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10470 return Cur->getName() == New->getName();
10471 })) {
10472 NewFD->setIsMultiVersion();
10473 Redeclaration = true;
10474 OldDecl = ND;
10475 return false;
10476 }
10477
10478 // Only 1 version of CPUSpecific is allowed for each CPU.
10479 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10480 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10481 if (CurII == NewII) {
10482 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10483 << NewII;
10484 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10485 NewFD->setInvalidDecl();
10486 return true;
10487 }
10488 }
10489 }
10490 }
10491 // If the two decls aren't the same MVType, there is no possible error
10492 // condition.
10493 }
10494 }
10495
10496 // Else, this is simply a non-redecl case. Checking the 'value' is only
10497 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10498 // handled in the attribute adding step.
10499 if (NewMVType == MultiVersionKind::Target &&
10500 CheckMultiVersionValue(S, NewFD)) {
10501 NewFD->setInvalidDecl();
10502 return true;
10503 }
10504
10505 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10506 !OldFD->isMultiVersion(), NewMVType)) {
10507 NewFD->setInvalidDecl();
10508 return true;
10509 }
10510
10511 // Permit forward declarations in the case where these two are compatible.
10512 if (!OldFD->isMultiVersion()) {
10513 OldFD->setIsMultiVersion();
10514 NewFD->setIsMultiVersion();
10515 Redeclaration = true;
10516 OldDecl = OldFD;
10517 return false;
10518 }
10519
10520 NewFD->setIsMultiVersion();
10521 Redeclaration = false;
10522 MergeTypeWithPrevious = false;
10523 OldDecl = nullptr;
10524 Previous.clear();
10525 return false;
10526}
10527
10528
10529/// Check the validity of a mulitversion function declaration.
10530/// Also sets the multiversion'ness' of the function itself.
10531///
10532/// This sets NewFD->isInvalidDecl() to true if there was an error.
10533///
10534/// Returns true if there was an error, false otherwise.
10535static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10536 bool &Redeclaration, NamedDecl *&OldDecl,
10537 bool &MergeTypeWithPrevious,
10538 LookupResult &Previous) {
10539 const auto *NewTA = NewFD->getAttr<TargetAttr>();
10540 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10541 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10542
10543 // Mixing Multiversioning types is prohibited.
10544 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10545 (NewCPUDisp && NewCPUSpec)) {
10546 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10547 NewFD->setInvalidDecl();
10548 return true;
10549 }
10550
10551 MultiVersionKind MVType = NewFD->getMultiVersionKind();
10552
10553 // Main isn't allowed to become a multiversion function, however it IS
10554 // permitted to have 'main' be marked with the 'target' optimization hint.
10555 if (NewFD->isMain()) {
10556 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10557 MVType == MultiVersionKind::CPUDispatch ||
10558 MVType == MultiVersionKind::CPUSpecific) {
10559 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10560 NewFD->setInvalidDecl();
10561 return true;
10562 }
10563 return false;
10564 }
10565
10566 if (!OldDecl || !OldDecl->getAsFunction() ||
10567 OldDecl->getDeclContext()->getRedeclContext() !=
10568 NewFD->getDeclContext()->getRedeclContext()) {
10569 // If there's no previous declaration, AND this isn't attempting to cause
10570 // multiversioning, this isn't an error condition.
10571 if (MVType == MultiVersionKind::None)
10572 return false;
10573 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10574 }
10575
10576 FunctionDecl *OldFD = OldDecl->getAsFunction();
10577
10578 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10579 return false;
10580
10581 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10582 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10583 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10584 NewFD->setInvalidDecl();
10585 return true;
10586 }
10587
10588 // Handle the target potentially causes multiversioning case.
10589 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10590 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10591 Redeclaration, OldDecl,
10592 MergeTypeWithPrevious, Previous);
10593
10594 // At this point, we have a multiversion function decl (in OldFD) AND an
10595 // appropriate attribute in the current function decl. Resolve that these are
10596 // still compatible with previous declarations.
10597 return CheckMultiVersionAdditionalDecl(
10598 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10599 OldDecl, MergeTypeWithPrevious, Previous);
10600}
10601
10602/// Perform semantic checking of a new function declaration.
10603///
10604/// Performs semantic analysis of the new function declaration
10605/// NewFD. This routine performs all semantic checking that does not
10606/// require the actual declarator involved in the declaration, and is
10607/// used both for the declaration of functions as they are parsed
10608/// (called via ActOnDeclarator) and for the declaration of functions
10609/// that have been instantiated via C++ template instantiation (called
10610/// via InstantiateDecl).
10611///
10612/// \param IsMemberSpecialization whether this new function declaration is
10613/// a member specialization (that replaces any definition provided by the
10614/// previous declaration).
10615///
10616/// This sets NewFD->isInvalidDecl() to true if there was an error.
10617///
10618/// \returns true if the function declaration is a redeclaration.
10619bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10620 LookupResult &Previous,
10621 bool IsMemberSpecialization) {
10622 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&((!NewFD->getReturnType()->isVariablyModifiedType() &&
"Variably modified return types are not handled here") ? static_cast
<void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 10623, __PRETTY_FUNCTION__))
10623 "Variably modified return types are not handled here")((!NewFD->getReturnType()->isVariablyModifiedType() &&
"Variably modified return types are not handled here") ? static_cast
<void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 10623, __PRETTY_FUNCTION__))
;
10624
10625 // Determine whether the type of this function should be merged with
10626 // a previous visible declaration. This never happens for functions in C++,
10627 // and always happens in C if the previous declaration was visible.
10628 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10629 !Previous.isShadowed();
10630
10631 bool Redeclaration = false;
10632 NamedDecl *OldDecl = nullptr;
10633 bool MayNeedOverloadableChecks = false;
10634
10635 // Merge or overload the declaration with an existing declaration of
10636 // the same name, if appropriate.
10637 if (!Previous.empty()) {
10638 // Determine whether NewFD is an overload of PrevDecl or
10639 // a declaration that requires merging. If it's an overload,
10640 // there's no more work to do here; we'll just add the new
10641 // function to the scope.
10642 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10643 NamedDecl *Candidate = Previous.getRepresentativeDecl();
10644 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10645 Redeclaration = true;
10646 OldDecl = Candidate;
10647 }
10648 } else {
10649 MayNeedOverloadableChecks = true;
10650 switch (CheckOverload(S, NewFD, Previous, OldDecl,
10651 /*NewIsUsingDecl*/ false)) {
10652 case Ovl_Match:
10653 Redeclaration = true;
10654 break;
10655
10656 case Ovl_NonFunction:
10657 Redeclaration = true;
10658 break;
10659
10660 case Ovl_Overload:
10661 Redeclaration = false;
10662 break;
10663 }
10664 }
10665 }
10666
10667 // Check for a previous extern "C" declaration with this name.
10668 if (!Redeclaration &&
10669 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10670 if (!Previous.empty()) {
10671 // This is an extern "C" declaration with the same name as a previous
10672 // declaration, and thus redeclares that entity...
10673 Redeclaration = true;
10674 OldDecl = Previous.getFoundDecl();
10675 MergeTypeWithPrevious = false;
10676
10677 // ... except in the presence of __attribute__((overloadable)).
10678 if (OldDecl->hasAttr<OverloadableAttr>() ||
10679 NewFD->hasAttr<OverloadableAttr>()) {
10680 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10681 MayNeedOverloadableChecks = true;
10682 Redeclaration = false;
10683 OldDecl = nullptr;
10684 }
10685 }
10686 }
10687 }
10688
10689 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10690 MergeTypeWithPrevious, Previous))
10691 return Redeclaration;
10692
10693 // PPC MMA non-pointer types are not allowed as function return types.
10694 if (Context.getTargetInfo().getTriple().isPPC64() &&
10695 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10696 NewFD->setInvalidDecl();
10697 }
10698
10699 // C++11 [dcl.constexpr]p8:
10700 // A constexpr specifier for a non-static member function that is not
10701 // a constructor declares that member function to be const.
10702 //
10703 // This needs to be delayed until we know whether this is an out-of-line
10704 // definition of a static member function.
10705 //
10706 // This rule is not present in C++1y, so we produce a backwards
10707 // compatibility warning whenever it happens in C++11.
10708 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10709 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10710 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10711 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10712 CXXMethodDecl *OldMD = nullptr;
10713 if (OldDecl)
10714 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10715 if (!OldMD || !OldMD->isStatic()) {
10716 const FunctionProtoType *FPT =
10717 MD->getType()->castAs<FunctionProtoType>();
10718 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10719 EPI.TypeQuals.addConst();
10720 MD->setType(Context.getFunctionType(FPT->getReturnType(),
10721 FPT->getParamTypes(), EPI));
10722
10723 // Warn that we did this, if we're not performing template instantiation.
10724 // In that case, we'll have warned already when the template was defined.
10725 if (!inTemplateInstantiation()) {
10726 SourceLocation AddConstLoc;
10727 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10728 .IgnoreParens().getAs<FunctionTypeLoc>())
10729 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10730
10731 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10732 << FixItHint::CreateInsertion(AddConstLoc, " const");
10733 }
10734 }
10735 }
10736
10737 if (Redeclaration) {
10738 // NewFD and OldDecl represent declarations that need to be
10739 // merged.
10740 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10741 NewFD->setInvalidDecl();
10742 return Redeclaration;
10743 }
10744
10745 Previous.clear();
10746 Previous.addDecl(OldDecl);
10747
10748 if (FunctionTemplateDecl *OldTemplateDecl =
10749 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10750 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10751 FunctionTemplateDecl *NewTemplateDecl
10752 = NewFD->getDescribedFunctionTemplate();
10753 assert(NewTemplateDecl && "Template/non-template mismatch")((NewTemplateDecl && "Template/non-template mismatch"
) ? static_cast<void> (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 10753, __PRETTY_FUNCTION__))
;
10754
10755 // The call to MergeFunctionDecl above may have created some state in
10756 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10757 // can add it as a redeclaration.
10758 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10759
10760 NewFD->setPreviousDeclaration(OldFD);
10761 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10762 if (NewFD->isCXXClassMember()) {
10763 NewFD->setAccess(OldTemplateDecl->getAccess());
10764 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10765 }
10766
10767 // If this is an explicit specialization of a member that is a function
10768 // template, mark it as a member specialization.
10769 if (IsMemberSpecialization &&
10770 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10771 NewTemplateDecl->setMemberSpecialization();
10772 assert(OldTemplateDecl->isMemberSpecialization())((OldTemplateDecl->isMemberSpecialization()) ? static_cast
<void> (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 10772, __PRETTY_FUNCTION__))
;
10773 // Explicit specializations of a member template do not inherit deleted
10774 // status from the parent member template that they are specializing.
10775 if (OldFD->isDeleted()) {
10776 // FIXME: This assert will not hold in the presence of modules.
10777 assert(OldFD->getCanonicalDecl() == OldFD)((OldFD->getCanonicalDecl() == OldFD) ? static_cast<void
> (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 10777, __PRETTY_FUNCTION__))
;
10778 // FIXME: We need an update record for this AST mutation.
10779 OldFD->setDeletedAsWritten(false);
10780 }
10781 }
10782
10783 } else {
10784 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10785 auto *OldFD = cast<FunctionDecl>(OldDecl);
10786 // This needs to happen first so that 'inline' propagates.
10787 NewFD->setPreviousDeclaration(OldFD);
10788 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10789 if (NewFD->isCXXClassMember())
10790 NewFD->setAccess(OldFD->getAccess());
10791 }
10792 }
10793 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10794 !NewFD->getAttr<OverloadableAttr>()) {
10795 assert((Previous.empty() ||(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 10800, __PRETTY_FUNCTION__))
10796 llvm::any_of(Previous,(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 10800, __PRETTY_FUNCTION__))
10797 [](const NamedDecl *ND) {(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 10800, __PRETTY_FUNCTION__))
10798 return ND->hasAttr<OverloadableAttr>();(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 10800, __PRETTY_FUNCTION__))
10799 })) &&(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 10800, __PRETTY_FUNCTION__))
10800 "Non-redecls shouldn't happen without overloadable present")(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 10800, __PRETTY_FUNCTION__))
;
10801
10802 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10803 const auto *FD = dyn_cast<FunctionDecl>(ND);
10804 return FD && !FD->hasAttr<OverloadableAttr>();
10805 });
10806
10807 if (OtherUnmarkedIter != Previous.end()) {
10808 Diag(NewFD->getLocation(),
10809 diag::err_attribute_overloadable_multiple_unmarked_overloads);
10810 Diag((*OtherUnmarkedIter)->getLocation(),
10811 diag::note_attribute_overloadable_prev_overload)
10812 << false;
10813
10814 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10815 }
10816 }
10817
10818 // Semantic checking for this function declaration (in isolation).
10819
10820 if (getLangOpts().CPlusPlus) {
10821 // C++-specific checks.
10822 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10823 CheckConstructor(Constructor);
10824 } else if (CXXDestructorDecl *Destructor =
10825 dyn_cast<CXXDestructorDecl>(NewFD)) {
10826 CXXRecordDecl *Record = Destructor->getParent();
10827 QualType ClassType = Context.getTypeDeclType(Record);
10828
10829 // FIXME: Shouldn't we be able to perform this check even when the class
10830 // type is dependent? Both gcc and edg can handle that.
10831 if (!ClassType->isDependentType()) {
10832 DeclarationName Name
10833 = Context.DeclarationNames.getCXXDestructorName(
10834 Context.getCanonicalType(ClassType));
10835 if (NewFD->getDeclName() != Name) {
10836 Diag(NewFD->getLocation(), diag::err_destructor_name);
10837 NewFD->setInvalidDecl();
10838 return Redeclaration;
10839 }
10840 }
10841 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10842 if (auto *TD = Guide->getDescribedFunctionTemplate())
10843 CheckDeductionGuideTemplate(TD);
10844
10845 // A deduction guide is not on the list of entities that can be
10846 // explicitly specialized.
10847 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10848 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10849 << /*explicit specialization*/ 1;
10850 }
10851
10852 // Find any virtual functions that this function overrides.
10853 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10854 if (!Method->isFunctionTemplateSpecialization() &&
10855 !Method->getDescribedFunctionTemplate() &&
10856 Method->isCanonicalDecl()) {
10857 AddOverriddenMethods(Method->getParent(), Method);
10858 }
10859 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10860 // C++2a [class.virtual]p6
10861 // A virtual method shall not have a requires-clause.
10862 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10863 diag::err_constrained_virtual_method);
10864
10865 if (Method->isStatic())
10866 checkThisInStaticMemberFunctionType(Method);
10867 }
10868
10869 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10870 ActOnConversionDeclarator(Conversion);
10871
10872 // Extra checking for C++ overloaded operators (C++ [over.oper]).
10873 if (NewFD->isOverloadedOperator() &&
10874 CheckOverloadedOperatorDeclaration(NewFD)) {
10875 NewFD->setInvalidDecl();
10876 return Redeclaration;
10877 }
10878
10879 // Extra checking for C++0x literal operators (C++0x [over.literal]).
10880 if (NewFD->getLiteralIdentifier() &&
10881 CheckLiteralOperatorDeclaration(NewFD)) {
10882 NewFD->setInvalidDecl();
10883 return Redeclaration;
10884 }
10885
10886 // In C++, check default arguments now that we have merged decls. Unless
10887 // the lexical context is the class, because in this case this is done
10888 // during delayed parsing anyway.
10889 if (!CurContext->isRecord())
10890 CheckCXXDefaultArguments(NewFD);
10891
10892 // If this function declares a builtin function, check the type of this
10893 // declaration against the expected type for the builtin.
10894 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10895 ASTContext::GetBuiltinTypeError Error;
10896 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10897 QualType T = Context.GetBuiltinType(BuiltinID, Error);
10898 // If the type of the builtin differs only in its exception
10899 // specification, that's OK.
10900 // FIXME: If the types do differ in this way, it would be better to
10901 // retain the 'noexcept' form of the type.
10902 if (!T.isNull() &&
10903 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10904 NewFD->getType()))
10905 // The type of this function differs from the type of the builtin,
10906 // so forget about the builtin entirely.
10907 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10908 }
10909
10910 // If this function is declared as being extern "C", then check to see if
10911 // the function returns a UDT (class, struct, or union type) that is not C
10912 // compatible, and if it does, warn the user.
10913 // But, issue any diagnostic on the first declaration only.
10914 if (Previous.empty() && NewFD->isExternC()) {
10915 QualType R = NewFD->getReturnType();
10916 if (R->isIncompleteType() && !R->isVoidType())
10917 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10918 << NewFD << R;
10919 else if (!R.isPODType(Context) && !R->isVoidType() &&
10920 !R->isObjCObjectPointerType())
10921 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10922 }
10923
10924 // C++1z [dcl.fct]p6:
10925 // [...] whether the function has a non-throwing exception-specification
10926 // [is] part of the function type
10927 //
10928 // This results in an ABI break between C++14 and C++17 for functions whose
10929 // declared type includes an exception-specification in a parameter or
10930 // return type. (Exception specifications on the function itself are OK in
10931 // most cases, and exception specifications are not permitted in most other
10932 // contexts where they could make it into a mangling.)
10933 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10934 auto HasNoexcept = [&](QualType T) -> bool {
10935 // Strip off declarator chunks that could be between us and a function
10936 // type. We don't need to look far, exception specifications are very
10937 // restricted prior to C++17.
10938 if (auto *RT = T->getAs<ReferenceType>())
10939 T = RT->getPointeeType();
10940 else if (T->isAnyPointerType())
10941 T = T->getPointeeType();
10942 else if (auto *MPT = T->getAs<MemberPointerType>())
10943 T = MPT->getPointeeType();
10944 if (auto *FPT = T->getAs<FunctionProtoType>())
10945 if (FPT->isNothrow())
10946 return true;
10947 return false;
10948 };
10949
10950 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10951 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10952 for (QualType T : FPT->param_types())
10953 AnyNoexcept |= HasNoexcept(T);
10954 if (AnyNoexcept)
10955 Diag(NewFD->getLocation(),
10956 diag::warn_cxx17_compat_exception_spec_in_signature)
10957 << NewFD;
10958 }
10959
10960 if (!Redeclaration && LangOpts.CUDA)
10961 checkCUDATargetOverload(NewFD, Previous);
10962 }
10963 return Redeclaration;
10964}
10965
10966void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10967 // C++11 [basic.start.main]p3:
10968 // A program that [...] declares main to be inline, static or
10969 // constexpr is ill-formed.
10970 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
10971 // appear in a declaration of main.
10972 // static main is not an error under C99, but we should warn about it.
10973 // We accept _Noreturn main as an extension.
10974 if (FD->getStorageClass() == SC_Static)
10975 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10976 ? diag::err_static_main : diag::warn_static_main)
10977 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10978 if (FD->isInlineSpecified())
10979 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10980 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10981 if (DS.isNoreturnSpecified()) {
10982 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10983 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10984 Diag(NoreturnLoc, diag::ext_noreturn_main);
10985 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10986 << FixItHint::CreateRemoval(NoreturnRange);
10987 }
10988 if (FD->isConstexpr()) {
10989 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10990 << FD->isConsteval()
10991 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10992 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
10993 }
10994
10995 if (getLangOpts().OpenCL) {
10996 Diag(FD->getLocation(), diag::err_opencl_no_main)
10997 << FD->hasAttr<OpenCLKernelAttr>();
10998 FD->setInvalidDecl();
10999 return;
11000 }
11001
11002 QualType T = FD->getType();
11003 assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11003, __PRETTY_FUNCTION__))
;
11004 const FunctionType* FT = T->castAs<FunctionType>();
11005
11006 // Set default calling convention for main()
11007 if (FT->getCallConv() != CC_C) {
11008 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11009 FD->setType(QualType(FT, 0));
11010 T = Context.getCanonicalType(FD->getType());
11011 }
11012
11013 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11014 // In C with GNU extensions we allow main() to have non-integer return
11015 // type, but we should warn about the extension, and we disable the
11016 // implicit-return-zero rule.
11017
11018 // GCC in C mode accepts qualified 'int'.
11019 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11020 FD->setHasImplicitReturnZero(true);
11021 else {
11022 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11023 SourceRange RTRange = FD->getReturnTypeSourceRange();
11024 if (RTRange.isValid())
11025 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11026 << FixItHint::CreateReplacement(RTRange, "int");
11027 }
11028 } else {
11029 // In C and C++, main magically returns 0 if you fall off the end;
11030 // set the flag which tells us that.
11031 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11032
11033 // All the standards say that main() should return 'int'.
11034 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11035 FD->setHasImplicitReturnZero(true);
11036 else {
11037 // Otherwise, this is just a flat-out error.
11038 SourceRange RTRange = FD->getReturnTypeSourceRange();
11039 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11040 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11041 : FixItHint());
11042 FD->setInvalidDecl(true);
11043 }
11044 }
11045
11046 // Treat protoless main() as nullary.
11047 if (isa<FunctionNoProtoType>(FT)) return;
11048
11049 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11050 unsigned nparams = FTP->getNumParams();
11051 assert(FD->getNumParams() == nparams)((FD->getNumParams() == nparams) ? static_cast<void>
(0) : __assert_fail ("FD->getNumParams() == nparams", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11051, __PRETTY_FUNCTION__))
;
11052
11053 bool HasExtraParameters = (nparams > 3);
11054
11055 if (FTP->isVariadic()) {
11056 Diag(FD->getLocation(), diag::ext_variadic_main);
11057 // FIXME: if we had information about the location of the ellipsis, we
11058 // could add a FixIt hint to remove it as a parameter.
11059 }
11060
11061 // Darwin passes an undocumented fourth argument of type char**. If
11062 // other platforms start sprouting these, the logic below will start
11063 // getting shifty.
11064 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11065 HasExtraParameters = false;
11066
11067 if (HasExtraParameters) {
11068 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11069 FD->setInvalidDecl(true);
11070 nparams = 3;
11071 }
11072
11073 // FIXME: a lot of the following diagnostics would be improved
11074 // if we had some location information about types.
11075
11076 QualType CharPP =
11077 Context.getPointerType(Context.getPointerType(Context.CharTy));
11078 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11079
11080 for (unsigned i = 0; i < nparams; ++i) {
11081 QualType AT = FTP->getParamType(i);
11082
11083 bool mismatch = true;
11084
11085 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11086 mismatch = false;
11087 else if (Expected[i] == CharPP) {
11088 // As an extension, the following forms are okay:
11089 // char const **
11090 // char const * const *
11091 // char * const *
11092
11093 QualifierCollector qs;
11094 const PointerType* PT;
11095 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11096 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11097 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11098 Context.CharTy)) {
11099 qs.removeConst();
11100 mismatch = !qs.empty();
11101 }
11102 }
11103
11104 if (mismatch) {
11105 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11106 // TODO: suggest replacing given type with expected type
11107 FD->setInvalidDecl(true);
11108 }
11109 }
11110
11111 if (nparams == 1 && !FD->isInvalidDecl()) {
11112 Diag(FD->getLocation(), diag::warn_main_one_arg);
11113 }
11114
11115 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11116 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11117 FD->setInvalidDecl();
11118 }
11119}
11120
11121void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11122 QualType T = FD->getType();
11123 assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11123, __PRETTY_FUNCTION__))
;
11124 const FunctionType *FT = T->castAs<FunctionType>();
11125
11126 // Set an implicit return of 'zero' if the function can return some integral,
11127 // enumeration, pointer or nullptr type.
11128 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11129 FT->getReturnType()->isAnyPointerType() ||
11130 FT->getReturnType()->isNullPtrType())
11131 // DllMain is exempt because a return value of zero means it failed.
11132 if (FD->getName() != "DllMain")
11133 FD->setHasImplicitReturnZero(true);
11134
11135 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11136 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11137 FD->setInvalidDecl();
11138 }
11139}
11140
11141bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11142 // FIXME: Need strict checking. In C89, we need to check for
11143 // any assignment, increment, decrement, function-calls, or
11144 // commas outside of a sizeof. In C99, it's the same list,
11145 // except that the aforementioned are allowed in unevaluated
11146 // expressions. Everything else falls under the
11147 // "may accept other forms of constant expressions" exception.
11148 //
11149 // Regular C++ code will not end up here (exceptions: language extensions,
11150 // OpenCL C++ etc), so the constant expression rules there don't matter.
11151 if (Init->isValueDependent()) {
11152 assert(Init->containsErrors() &&((Init->containsErrors() && "Dependent code should only occur in error-recovery path."
) ? static_cast<void> (0) : __assert_fail ("Init->containsErrors() && \"Dependent code should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11153, __PRETTY_FUNCTION__))
11153 "Dependent code should only occur in error-recovery path.")((Init->containsErrors() && "Dependent code should only occur in error-recovery path."
) ? static_cast<void> (0) : __assert_fail ("Init->containsErrors() && \"Dependent code should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11153, __PRETTY_FUNCTION__))
;
11154 return true;
11155 }
11156 const Expr *Culprit;
11157 if (Init->isConstantInitializer(Context, false, &Culprit))
11158 return false;
11159 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11160 << Culprit->getSourceRange();
11161 return true;
11162}
11163
11164namespace {
11165 // Visits an initialization expression to see if OrigDecl is evaluated in
11166 // its own initialization and throws a warning if it does.
11167 class SelfReferenceChecker
11168 : public EvaluatedExprVisitor<SelfReferenceChecker> {
11169 Sema &S;
11170 Decl *OrigDecl;
11171 bool isRecordType;
11172 bool isPODType;
11173 bool isReferenceType;
11174
11175 bool isInitList;
11176 llvm::SmallVector<unsigned, 4> InitFieldIndex;
11177
11178 public:
11179 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11180
11181 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11182 S(S), OrigDecl(OrigDecl) {
11183 isPODType = false;
11184 isRecordType = false;
11185 isReferenceType = false;
11186 isInitList = false;
11187 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11188 isPODType = VD->getType().isPODType(S.Context);
11189 isRecordType = VD->getType()->isRecordType();
11190 isReferenceType = VD->getType()->isReferenceType();
11191 }
11192 }
11193
11194 // For most expressions, just call the visitor. For initializer lists,
11195 // track the index of the field being initialized since fields are
11196 // initialized in order allowing use of previously initialized fields.
11197 void CheckExpr(Expr *E) {
11198 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11199 if (!InitList) {
11200 Visit(E);
11201 return;
11202 }
11203
11204 // Track and increment the index here.
11205 isInitList = true;
11206 InitFieldIndex.push_back(0);
11207 for (auto Child : InitList->children()) {
11208 CheckExpr(cast<Expr>(Child));
11209 ++InitFieldIndex.back();
11210 }
11211 InitFieldIndex.pop_back();
11212 }
11213
11214 // Returns true if MemberExpr is checked and no further checking is needed.
11215 // Returns false if additional checking is required.
11216 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11217 llvm::SmallVector<FieldDecl*, 4> Fields;
11218 Expr *Base = E;
11219 bool ReferenceField = false;
11220
11221 // Get the field members used.
11222 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11223 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11224 if (!FD)
11225 return false;
11226 Fields.push_back(FD);
11227 if (FD->getType()->isReferenceType())
11228 ReferenceField = true;
11229 Base = ME->getBase()->IgnoreParenImpCasts();
11230 }
11231
11232 // Keep checking only if the base Decl is the same.
11233 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11234 if (!DRE || DRE->getDecl() != OrigDecl)
11235 return false;
11236
11237 // A reference field can be bound to an unininitialized field.
11238 if (CheckReference && !ReferenceField)
11239 return true;
11240
11241 // Convert FieldDecls to their index number.
11242 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11243 for (const FieldDecl *I : llvm::reverse(Fields))
11244 UsedFieldIndex.push_back(I->getFieldIndex());
11245
11246 // See if a warning is needed by checking the first difference in index
11247 // numbers. If field being used has index less than the field being
11248 // initialized, then the use is safe.
11249 for (auto UsedIter = UsedFieldIndex.begin(),
11250 UsedEnd = UsedFieldIndex.end(),
11251 OrigIter = InitFieldIndex.begin(),
11252 OrigEnd = InitFieldIndex.end();
11253 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11254 if (*UsedIter < *OrigIter)
11255 return true;
11256 if (*UsedIter > *OrigIter)
11257 break;
11258 }
11259
11260 // TODO: Add a different warning which will print the field names.
11261 HandleDeclRefExpr(DRE);
11262 return true;
11263 }
11264
11265 // For most expressions, the cast is directly above the DeclRefExpr.
11266 // For conditional operators, the cast can be outside the conditional
11267 // operator if both expressions are DeclRefExpr's.
11268 void HandleValue(Expr *E) {
11269 E = E->IgnoreParens();
11270 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11271 HandleDeclRefExpr(DRE);
11272 return;
11273 }
11274
11275 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11276 Visit(CO->getCond());
11277 HandleValue(CO->getTrueExpr());
11278 HandleValue(CO->getFalseExpr());
11279 return;
11280 }
11281
11282 if (BinaryConditionalOperator *BCO =
11283 dyn_cast<BinaryConditionalOperator>(E)) {
11284 Visit(BCO->getCond());
11285 HandleValue(BCO->getFalseExpr());
11286 return;
11287 }
11288
11289 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11290 HandleValue(OVE->getSourceExpr());
11291 return;
11292 }
11293
11294 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11295 if (BO->getOpcode() == BO_Comma) {
11296 Visit(BO->getLHS());
11297 HandleValue(BO->getRHS());
11298 return;
11299 }
11300 }
11301
11302 if (isa<MemberExpr>(E)) {
11303 if (isInitList) {
11304 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11305 false /*CheckReference*/))
11306 return;
11307 }
11308
11309 Expr *Base = E->IgnoreParenImpCasts();
11310 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11311 // Check for static member variables and don't warn on them.
11312 if (!isa<FieldDecl>(ME->getMemberDecl()))
11313 return;
11314 Base = ME->getBase()->IgnoreParenImpCasts();
11315 }
11316 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11317 HandleDeclRefExpr(DRE);
11318 return;
11319 }
11320
11321 Visit(E);
11322 }
11323
11324 // Reference types not handled in HandleValue are handled here since all
11325 // uses of references are bad, not just r-value uses.
11326 void VisitDeclRefExpr(DeclRefExpr *E) {
11327 if (isReferenceType)
11328 HandleDeclRefExpr(E);
11329 }
11330
11331 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11332 if (E->getCastKind() == CK_LValueToRValue) {
11333 HandleValue(E->getSubExpr());
11334 return;
11335 }
11336
11337 Inherited::VisitImplicitCastExpr(E);
11338 }
11339
11340 void VisitMemberExpr(MemberExpr *E) {
11341 if (isInitList) {
11342 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11343 return;
11344 }
11345
11346 // Don't warn on arrays since they can be treated as pointers.
11347 if (E->getType()->canDecayToPointerType()) return;
11348
11349 // Warn when a non-static method call is followed by non-static member
11350 // field accesses, which is followed by a DeclRefExpr.
11351 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11352 bool Warn = (MD && !MD->isStatic());
11353 Expr *Base = E->getBase()->IgnoreParenImpCasts();
11354 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11355 if (!isa<FieldDecl>(ME->getMemberDecl()))
11356 Warn = false;
11357 Base = ME->getBase()->IgnoreParenImpCasts();
11358 }
11359
11360 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11361 if (Warn)
11362 HandleDeclRefExpr(DRE);
11363 return;
11364 }
11365
11366 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11367 // Visit that expression.
11368 Visit(Base);
11369 }
11370
11371 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11372 Expr *Callee = E->getCallee();
11373
11374 if (isa<UnresolvedLookupExpr>(Callee))
11375 return Inherited::VisitCXXOperatorCallExpr(E);
11376
11377 Visit(Callee);
11378 for (auto Arg: E->arguments())
11379 HandleValue(Arg->IgnoreParenImpCasts());
11380 }
11381
11382 void VisitUnaryOperator(UnaryOperator *E) {
11383 // For POD record types, addresses of its own members are well-defined.
11384 if (E->getOpcode() == UO_AddrOf && isRecordType &&
11385 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11386 if (!isPODType)
11387 HandleValue(E->getSubExpr());
11388 return;
11389 }
11390
11391 if (E->isIncrementDecrementOp()) {
11392 HandleValue(E->getSubExpr());
11393 return;
11394 }
11395
11396 Inherited::VisitUnaryOperator(E);
11397 }
11398
11399 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11400
11401 void VisitCXXConstructExpr(CXXConstructExpr *E) {
11402 if (E->getConstructor()->isCopyConstructor()) {
11403 Expr *ArgExpr = E->getArg(0);
11404 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11405 if (ILE->getNumInits() == 1)
11406 ArgExpr = ILE->getInit(0);
11407 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11408 if (ICE->getCastKind() == CK_NoOp)
11409 ArgExpr = ICE->getSubExpr();
11410 HandleValue(ArgExpr);
11411 return;
11412 }
11413 Inherited::VisitCXXConstructExpr(E);
11414 }
11415
11416 void VisitCallExpr(CallExpr *E) {
11417 // Treat std::move as a use.
11418 if (E->isCallToStdMove()) {
11419 HandleValue(E->getArg(0));
11420 return;
11421 }
11422
11423 Inherited::VisitCallExpr(E);
11424 }
11425
11426 void VisitBinaryOperator(BinaryOperator *E) {
11427 if (E->isCompoundAssignmentOp()) {
11428 HandleValue(E->getLHS());
11429 Visit(E->getRHS());
11430 return;
11431 }
11432
11433 Inherited::VisitBinaryOperator(E);
11434 }
11435
11436 // A custom visitor for BinaryConditionalOperator is needed because the
11437 // regular visitor would check the condition and true expression separately
11438 // but both point to the same place giving duplicate diagnostics.
11439 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11440 Visit(E->getCond());
11441 Visit(E->getFalseExpr());
11442 }
11443
11444 void HandleDeclRefExpr(DeclRefExpr *DRE) {
11445 Decl* ReferenceDecl = DRE->getDecl();
11446 if (OrigDecl != ReferenceDecl) return;
11447 unsigned diag;
11448 if (isReferenceType) {
11449 diag = diag::warn_uninit_self_reference_in_reference_init;
11450 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11451 diag = diag::warn_static_self_reference_in_init;
11452 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11453 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11454 DRE->getDecl()->getType()->isRecordType()) {
11455 diag = diag::warn_uninit_self_reference_in_init;
11456 } else {
11457 // Local variables will be handled by the CFG analysis.
11458 return;
11459 }
11460
11461 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11462 S.PDiag(diag)
11463 << DRE->getDecl() << OrigDecl->getLocation()
11464 << DRE->getSourceRange());
11465 }
11466 };
11467
11468 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11469 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11470 bool DirectInit) {
11471 // Parameters arguments are occassionially constructed with itself,
11472 // for instance, in recursive functions. Skip them.
11473 if (isa<ParmVarDecl>(OrigDecl))
11474 return;
11475
11476 E = E->IgnoreParens();
11477
11478 // Skip checking T a = a where T is not a record or reference type.
11479 // Doing so is a way to silence uninitialized warnings.
11480 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11481 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11482 if (ICE->getCastKind() == CK_LValueToRValue)
11483 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11484 if (DRE->getDecl() == OrigDecl)
11485 return;
11486
11487 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11488 }
11489} // end anonymous namespace
11490
11491namespace {
11492 // Simple wrapper to add the name of a variable or (if no variable is
11493 // available) a DeclarationName into a diagnostic.
11494 struct VarDeclOrName {
11495 VarDecl *VDecl;
11496 DeclarationName Name;
11497
11498 friend const Sema::SemaDiagnosticBuilder &
11499 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11500 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11501 }
11502 };
11503} // end anonymous namespace
11504
11505QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11506 DeclarationName Name, QualType Type,
11507 TypeSourceInfo *TSI,
11508 SourceRange Range, bool DirectInit,
11509 Expr *Init) {
11510 bool IsInitCapture = !VDecl;
11511 assert((!VDecl || !VDecl->isInitCapture()) &&(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization"
) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11512, __PRETTY_FUNCTION__))
11512 "init captures are expected to be deduced prior to initialization")(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization"
) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11512, __PRETTY_FUNCTION__))
;
11513
11514 VarDeclOrName VN{VDecl, Name};
11515
11516 DeducedType *Deduced = Type->getContainedDeducedType();
11517 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")((Deduced && "deduceVarTypeFromInitializer for non-deduced type"
) ? static_cast<void> (0) : __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11517, __PRETTY_FUNCTION__))
;
11518
11519 // C++11 [dcl.spec.auto]p3
11520 if (!Init) {
11521 assert(VDecl && "no init for init capture deduction?")((VDecl && "no init for init capture deduction?") ? static_cast
<void> (0) : __assert_fail ("VDecl && \"no init for init capture deduction?\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11521, __PRETTY_FUNCTION__))
;
11522
11523 // Except for class argument deduction, and then for an initializing
11524 // declaration only, i.e. no static at class scope or extern.
11525 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11526 VDecl->hasExternalStorage() ||
11527 VDecl->isStaticDataMember()) {
11528 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11529 << VDecl->getDeclName() << Type;
11530 return QualType();
11531 }
11532 }
11533
11534 ArrayRef<Expr*> DeduceInits;
11535 if (Init)
11536 DeduceInits = Init;
11537
11538 if (DirectInit) {
11539 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11540 DeduceInits = PL->exprs();
11541 }
11542
11543 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11544 assert(VDecl && "non-auto type for init capture deduction?")((VDecl && "non-auto type for init capture deduction?"
) ? static_cast<void> (0) : __assert_fail ("VDecl && \"non-auto type for init capture deduction?\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11544, __PRETTY_FUNCTION__))
;
11545 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11546 InitializationKind Kind = InitializationKind::CreateForInit(
11547 VDecl->getLocation(), DirectInit, Init);
11548 // FIXME: Initialization should not be taking a mutable list of inits.
11549 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11550 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11551 InitsCopy);
11552 }
11553
11554 if (DirectInit) {
11555 if (auto *IL = dyn_cast<InitListExpr>(Init))
11556 DeduceInits = IL->inits();
11557 }
11558
11559 // Deduction only works if we have exactly one source expression.
11560 if (DeduceInits.empty()) {
11561 // It isn't possible to write this directly, but it is possible to
11562 // end up in this situation with "auto x(some_pack...);"
11563 Diag(Init->getBeginLoc(), IsInitCapture
11564 ? diag::err_init_capture_no_expression
11565 : diag::err_auto_var_init_no_expression)
11566 << VN << Type << Range;
11567 return QualType();
11568 }
11569
11570 if (DeduceInits.size() > 1) {
11571 Diag(DeduceInits[1]->getBeginLoc(),
11572 IsInitCapture ? diag::err_init_capture_multiple_expressions
11573 : diag::err_auto_var_init_multiple_expressions)
11574 << VN << Type << Range;
11575 return QualType();
11576 }
11577
11578 Expr *DeduceInit = DeduceInits[0];
11579 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11580 Diag(Init->getBeginLoc(), IsInitCapture
11581 ? diag::err_init_capture_paren_braces
11582 : diag::err_auto_var_init_paren_braces)
11583 << isa<InitListExpr>(Init) << VN << Type << Range;
11584 return QualType();
11585 }
11586
11587 // Expressions default to 'id' when we're in a debugger.
11588 bool DefaultedAnyToId = false;
11589 if (getLangOpts().DebuggerCastResultToId &&
11590 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11591 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11592 if (Result.isInvalid()) {
11593 return QualType();
11594 }
11595 Init = Result.get();
11596 DefaultedAnyToId = true;
11597 }
11598
11599 // C++ [dcl.decomp]p1:
11600 // If the assignment-expression [...] has array type A and no ref-qualifier
11601 // is present, e has type cv A
11602 if (VDecl && isa<DecompositionDecl>(VDecl) &&
11603 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11604 DeduceInit->getType()->isConstantArrayType())
11605 return Context.getQualifiedType(DeduceInit->getType(),
11606 Type.getQualifiers());
11607
11608 QualType DeducedType;
11609 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11610 if (!IsInitCapture)
11611 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11612 else if (isa<InitListExpr>(Init))
11613 Diag(Range.getBegin(),
11614 diag::err_init_capture_deduction_failure_from_init_list)
11615 << VN
11616 << (DeduceInit->getType().isNull() ? TSI->getType()
11617 : DeduceInit->getType())
11618 << DeduceInit->getSourceRange();
11619 else
11620 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11621 << VN << TSI->getType()
11622 << (DeduceInit->getType().isNull() ? TSI->getType()
11623 : DeduceInit->getType())
11624 << DeduceInit->getSourceRange();
11625 }
11626
11627 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11628 // 'id' instead of a specific object type prevents most of our usual
11629 // checks.
11630 // We only want to warn outside of template instantiations, though:
11631 // inside a template, the 'id' could have come from a parameter.
11632 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11633 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11634 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11635 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11636 }
11637
11638 return DeducedType;
11639}
11640
11641bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11642 Expr *Init) {
11643 assert(!Init || !Init->containsErrors())((!Init || !Init->containsErrors()) ? static_cast<void>
(0) : __assert_fail ("!Init || !Init->containsErrors()", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11643, __PRETTY_FUNCTION__))
;
11644 QualType DeducedType = deduceVarTypeFromInitializer(
11645 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11646 VDecl->getSourceRange(), DirectInit, Init);
11647 if (DeducedType.isNull()) {
11648 VDecl->setInvalidDecl();
11649 return true;
11650 }
11651
11652 VDecl->setType(DeducedType);
11653 assert(VDecl->isLinkageValid())((VDecl->isLinkageValid()) ? static_cast<void> (0) :
__assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11653, __PRETTY_FUNCTION__))
;
11654
11655 // In ARC, infer lifetime.
11656 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11657 VDecl->setInvalidDecl();
11658
11659 if (getLangOpts().OpenCL)
11660 deduceOpenCLAddressSpace(VDecl);
11661
11662 // If this is a redeclaration, check that the type we just deduced matches
11663 // the previously declared type.
11664 if (VarDecl *Old = VDecl->getPreviousDecl()) {
11665 // We never need to merge the type, because we cannot form an incomplete
11666 // array of auto, nor deduce such a type.
11667 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11668 }
11669
11670 // Check the deduced type is valid for a variable declaration.
11671 CheckVariableDeclarationType(VDecl);
11672 return VDecl->isInvalidDecl();
11673}
11674
11675void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11676 SourceLocation Loc) {
11677 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11678 Init = EWC->getSubExpr();
11679
11680 if (auto *CE = dyn_cast<ConstantExpr>(Init))
11681 Init = CE->getSubExpr();
11682
11683 QualType InitType = Init->getType();
11684 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()
|| InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11686, __PRETTY_FUNCTION__))
11685 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()
|| InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11686, __PRETTY_FUNCTION__))
11686 "shouldn't be called if type doesn't have a non-trivial C struct")(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()
|| InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11686, __PRETTY_FUNCTION__))
;
11687 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11688 for (auto I : ILE->inits()) {
11689 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11690 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11691 continue;
11692 SourceLocation SL = I->getExprLoc();
11693 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11694 }
11695 return;
11696 }
11697
11698 if (isa<ImplicitValueInitExpr>(Init)) {
11699 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11700 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11701 NTCUK_Init);
11702 } else {
11703 // Assume all other explicit initializers involving copying some existing
11704 // object.
11705 // TODO: ignore any explicit initializers where we can guarantee
11706 // copy-elision.
11707 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11708 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11709 }
11710}
11711
11712namespace {
11713
11714bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11715 // Ignore unavailable fields. A field can be marked as unavailable explicitly
11716 // in the source code or implicitly by the compiler if it is in a union
11717 // defined in a system header and has non-trivial ObjC ownership
11718 // qualifications. We don't want those fields to participate in determining
11719 // whether the containing union is non-trivial.
11720 return FD->hasAttr<UnavailableAttr>();
11721}
11722
11723struct DiagNonTrivalCUnionDefaultInitializeVisitor
11724 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11725 void> {
11726 using Super =
11727 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11728 void>;
11729
11730 DiagNonTrivalCUnionDefaultInitializeVisitor(
11731 QualType OrigTy, SourceLocation OrigLoc,
11732 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11733 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11734
11735 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11736 const FieldDecl *FD, bool InNonTrivialUnion) {
11737 if (const auto *AT = S.Context.getAsArrayType(QT))
11738 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11739 InNonTrivialUnion);
11740 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11741 }
11742
11743 void visitARCStrong(QualType QT, const FieldDecl *FD,
11744 bool InNonTrivialUnion) {
11745 if (InNonTrivialUnion)
11746 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11747 << 1 << 0 << QT << FD->getName();
11748 }
11749
11750 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11751 if (InNonTrivialUnion)
11752 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11753 << 1 << 0 << QT << FD->getName();
11754 }
11755
11756 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11757 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11758 if (RD->isUnion()) {
11759 if (OrigLoc.isValid()) {
11760 bool IsUnion = false;
11761 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11762 IsUnion = OrigRD->isUnion();
11763 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11764 << 0 << OrigTy << IsUnion << UseContext;
11765 // Reset OrigLoc so that this diagnostic is emitted only once.
11766 OrigLoc = SourceLocation();
11767 }
11768 InNonTrivialUnion = true;
11769 }
11770
11771 if (InNonTrivialUnion)
11772 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11773 << 0 << 0 << QT.getUnqualifiedType() << "";
11774
11775 for (const FieldDecl *FD : RD->fields())
11776 if (!shouldIgnoreForRecordTriviality(FD))
11777 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11778 }
11779
11780 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11781
11782 // The non-trivial C union type or the struct/union type that contains a
11783 // non-trivial C union.
11784 QualType OrigTy;
11785 SourceLocation OrigLoc;
11786 Sema::NonTrivialCUnionContext UseContext;
11787 Sema &S;
11788};
11789
11790struct DiagNonTrivalCUnionDestructedTypeVisitor
11791 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11792 using Super =
11793 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11794
11795 DiagNonTrivalCUnionDestructedTypeVisitor(
11796 QualType OrigTy, SourceLocation OrigLoc,
11797 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11798 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11799
11800 void visitWithKind(QualType::DestructionKind DK, QualType QT,
11801 const FieldDecl *FD, bool InNonTrivialUnion) {
11802 if (const auto *AT = S.Context.getAsArrayType(QT))
11803 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11804 InNonTrivialUnion);
11805 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11806 }
11807
11808 void visitARCStrong(QualType QT, const FieldDecl *FD,
11809 bool InNonTrivialUnion) {
11810 if (InNonTrivialUnion)
11811 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11812 << 1 << 1 << QT << FD->getName();
11813 }
11814
11815 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11816 if (InNonTrivialUnion)
11817 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11818 << 1 << 1 << QT << FD->getName();
11819 }
11820
11821 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11822 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11823 if (RD->isUnion()) {
11824 if (OrigLoc.isValid()) {
11825 bool IsUnion = false;
11826 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11827 IsUnion = OrigRD->isUnion();
11828 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11829 << 1 << OrigTy << IsUnion << UseContext;
11830 // Reset OrigLoc so that this diagnostic is emitted only once.
11831 OrigLoc = SourceLocation();
11832 }
11833 InNonTrivialUnion = true;
11834 }
11835
11836 if (InNonTrivialUnion)
11837 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11838 << 0 << 1 << QT.getUnqualifiedType() << "";
11839
11840 for (const FieldDecl *FD : RD->fields())
11841 if (!shouldIgnoreForRecordTriviality(FD))
11842 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11843 }
11844
11845 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11846 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11847 bool InNonTrivialUnion) {}
11848
11849 // The non-trivial C union type or the struct/union type that contains a
11850 // non-trivial C union.
11851 QualType OrigTy;
11852 SourceLocation OrigLoc;
11853 Sema::NonTrivialCUnionContext UseContext;
11854 Sema &S;
11855};
11856
11857struct DiagNonTrivalCUnionCopyVisitor
11858 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11859 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11860
11861 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11862 Sema::NonTrivialCUnionContext UseContext,
11863 Sema &S)
11864 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11865
11866 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11867 const FieldDecl *FD, bool InNonTrivialUnion) {
11868 if (const auto *AT = S.Context.getAsArrayType(QT))
11869 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11870 InNonTrivialUnion);
11871 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11872 }
11873
11874 void visitARCStrong(QualType QT, const FieldDecl *FD,
11875 bool InNonTrivialUnion) {
11876 if (InNonTrivialUnion)
11877 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11878 << 1 << 2 << QT << FD->getName();
11879 }
11880
11881 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11882 if (InNonTrivialUnion)
11883 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11884 << 1 << 2 << QT << FD->getName();
11885 }
11886
11887 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11888 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11889 if (RD->isUnion()) {
11890 if (OrigLoc.isValid()) {
11891 bool IsUnion = false;
11892 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11893 IsUnion = OrigRD->isUnion();
11894 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11895 << 2 << OrigTy << IsUnion << UseContext;
11896 // Reset OrigLoc so that this diagnostic is emitted only once.
11897 OrigLoc = SourceLocation();
11898 }
11899 InNonTrivialUnion = true;
11900 }
11901
11902 if (InNonTrivialUnion)
11903 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11904 << 0 << 2 << QT.getUnqualifiedType() << "";
11905
11906 for (const FieldDecl *FD : RD->fields())
11907 if (!shouldIgnoreForRecordTriviality(FD))
11908 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11909 }
11910
11911 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11912 const FieldDecl *FD, bool InNonTrivialUnion) {}
11913 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11914 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11915 bool InNonTrivialUnion) {}
11916
11917 // The non-trivial C union type or the struct/union type that contains a
11918 // non-trivial C union.
11919 QualType OrigTy;
11920 SourceLocation OrigLoc;
11921 Sema::NonTrivialCUnionContext UseContext;
11922 Sema &S;
11923};
11924
11925} // namespace
11926
11927void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11928 NonTrivialCUnionContext UseContext,
11929 unsigned NonTrivialKind) {
11930 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11933, __PRETTY_FUNCTION__))
11931 QT.hasNonTrivialToPrimitiveDestructCUnion() ||(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11933, __PRETTY_FUNCTION__))
11932 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11933, __PRETTY_FUNCTION__))
11933 "shouldn't be called if type doesn't have a non-trivial C union")(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11933, __PRETTY_FUNCTION__))
;
11934
11935 if ((NonTrivialKind & NTCUK_Init) &&
11936 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11937 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11938 .visit(QT, nullptr, false);
11939 if ((NonTrivialKind & NTCUK_Destruct) &&
11940 QT.hasNonTrivialToPrimitiveDestructCUnion())
11941 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11942 .visit(QT, nullptr, false);
11943 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11944 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11945 .visit(QT, nullptr, false);
11946}
11947
11948/// AddInitializerToDecl - Adds the initializer Init to the
11949/// declaration dcl. If DirectInit is true, this is C++ direct
11950/// initialization rather than copy initialization.
11951void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11952 // If there is no declaration, there was an error parsing it. Just ignore
11953 // the initializer.
11954 if (!RealDecl || RealDecl->isInvalidDecl()) {
11955 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11956 return;
11957 }
11958
11959 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11960 // Pure-specifiers are handled in ActOnPureSpecifier.
11961 Diag(Method->getLocation(), diag::err_member_function_initialization)
11962 << Method->getDeclName() << Init->getSourceRange();
11963 Method->setInvalidDecl();
11964 return;
11965 }
11966
11967 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11968 if (!VDecl) {
11969 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")((!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"
) ? static_cast<void> (0) : __assert_fail ("!isa<FieldDecl>(RealDecl) && \"field init shouldn't get here\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 11969, __PRETTY_FUNCTION__))
;
11970 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11971 RealDecl->setInvalidDecl();
11972 return;
11973 }
11974
11975 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11976 if (VDecl->getType()->isUndeducedType()) {
11977 // Attempt typo correction early so that the type of the init expression can
11978 // be deduced based on the chosen correction if the original init contains a
11979 // TypoExpr.
11980 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11981 if (!Res.isUsable()) {
11982 // There are unresolved typos in Init, just drop them.
11983 // FIXME: improve the recovery strategy to preserve the Init.
11984 RealDecl->setInvalidDecl();
11985 return;
11986 }
11987 if (Res.get()->containsErrors()) {
11988 // Invalidate the decl as we don't know the type for recovery-expr yet.
11989 RealDecl->setInvalidDecl();
11990 VDecl->setInit(Res.get());
11991 return;
11992 }
11993 Init = Res.get();
11994
11995 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11996 return;
11997 }
11998
11999 // dllimport cannot be used on variable definitions.
12000 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12001 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12002 VDecl->setInvalidDecl();
12003 return;
12004 }
12005
12006 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12007 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12008 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12009 VDecl->setInvalidDecl();
12010 return;
12011 }
12012
12013 if (!VDecl->getType()->isDependentType()) {
12014 // A definition must end up with a complete type, which means it must be
12015 // complete with the restriction that an array type might be completed by
12016 // the initializer; note that later code assumes this restriction.
12017 QualType BaseDeclType = VDecl->getType();
12018 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12019 BaseDeclType = Array->getElementType();
12020 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12021 diag::err_typecheck_decl_incomplete_type)) {
12022 RealDecl->setInvalidDecl();
12023 return;
12024 }
12025
12026 // The variable can not have an abstract class type.
12027 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12028 diag::err_abstract_type_in_decl,
12029 AbstractVariableType))
12030 VDecl->setInvalidDecl();
12031 }
12032
12033 // If adding the initializer will turn this declaration into a definition,
12034 // and we already have a definition for this variable, diagnose or otherwise
12035 // handle the situation.
12036 VarDecl *Def;
12037 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12038 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12039 !VDecl->isThisDeclarationADemotedDefinition() &&
12040 checkVarDeclRedefinition(Def, VDecl))
12041 return;
12042
12043 if (getLangOpts().CPlusPlus) {
12044 // C++ [class.static.data]p4
12045 // If a static data member is of const integral or const
12046 // enumeration type, its declaration in the class definition can
12047 // specify a constant-initializer which shall be an integral
12048 // constant expression (5.19). In that case, the member can appear
12049 // in integral constant expressions. The member shall still be
12050 // defined in a namespace scope if it is used in the program and the
12051 // namespace scope definition shall not contain an initializer.
12052 //
12053 // We already performed a redefinition check above, but for static
12054 // data members we also need to check whether there was an in-class
12055 // declaration with an initializer.
12056 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12057 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12058 << VDecl->getDeclName();
12059 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12060 diag::note_previous_initializer)
12061 << 0;
12062 return;
12063 }
12064
12065 if (VDecl->hasLocalStorage())
12066 setFunctionHasBranchProtectedScope();
12067
12068 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12069 VDecl->setInvalidDecl();
12070 return;
12071 }
12072 }
12073
12074 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12075 // a kernel function cannot be initialized."
12076 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12077 Diag(VDecl->getLocation(), diag::err_local_cant_init);
12078 VDecl->setInvalidDecl();
12079 return;
12080 }
12081
12082 // The LoaderUninitialized attribute acts as a definition (of undef).
12083 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12084 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12085 VDecl->setInvalidDecl();
12086 return;
12087 }
12088
12089 // Get the decls type and save a reference for later, since
12090 // CheckInitializerTypes may change it.
12091 QualType DclT = VDecl->getType(), SavT = DclT;
12092
12093 // Expressions default to 'id' when we're in a debugger
12094 // and we are assigning it to a variable of Objective-C pointer type.
12095 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12096 Init->getType() == Context.UnknownAnyTy) {
12097 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12098 if (Result.isInvalid()) {
12099 VDecl->setInvalidDecl();
12100 return;
12101 }
12102 Init = Result.get();
12103 }
12104
12105 // Perform the initialization.
12106 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12107 if (!VDecl->isInvalidDecl()) {
12108 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12109 InitializationKind Kind = InitializationKind::CreateForInit(
12110 VDecl->getLocation(), DirectInit, Init);
12111
12112 MultiExprArg Args = Init;
12113 if (CXXDirectInit)
12114 Args = MultiExprArg(CXXDirectInit->getExprs(),
12115 CXXDirectInit->getNumExprs());
12116
12117 // Try to correct any TypoExprs in the initialization arguments.
12118 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12119 ExprResult Res = CorrectDelayedTyposInExpr(
12120 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12121 [this, Entity, Kind](Expr *E) {
12122 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12123 return Init.Failed() ? ExprError() : E;
12124 });
12125 if (Res.isInvalid()) {
12126 VDecl->setInvalidDecl();
12127 } else if (Res.get() != Args[Idx]) {
12128 Args[Idx] = Res.get();
12129 }
12130 }
12131 if (VDecl->isInvalidDecl())
12132 return;
12133
12134 InitializationSequence InitSeq(*this, Entity, Kind, Args,
12135 /*TopLevelOfInitList=*/false,
12136 /*TreatUnavailableAsInvalid=*/false);
12137 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12138 if (Result.isInvalid()) {
12139 // If the provied initializer fails to initialize the var decl,
12140 // we attach a recovery expr for better recovery.
12141 auto RecoveryExpr =
12142 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12143 if (RecoveryExpr.get())
12144 VDecl->setInit(RecoveryExpr.get());
12145 return;
12146 }
12147
12148 Init = Result.getAs<Expr>();
12149 }
12150
12151 // Check for self-references within variable initializers.
12152 // Variables declared within a function/method body (except for references)
12153 // are handled by a dataflow analysis.
12154 // This is undefined behavior in C++, but valid in C.
12155 if (getLangOpts().CPlusPlus) {
12156 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12157 VDecl->getType()->isReferenceType()) {
12158 CheckSelfReference(*this, RealDecl, Init, DirectInit);
12159 }
12160 }
12161
12162 // If the type changed, it means we had an incomplete type that was
12163 // completed by the initializer. For example:
12164 // int ary[] = { 1, 3, 5 };
12165 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12166 if (!VDecl->isInvalidDecl() && (DclT != SavT))
12167 VDecl->setType(DclT);
12168
12169 if (!VDecl->isInvalidDecl()) {
12170 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12171
12172 if (VDecl->hasAttr<BlocksAttr>())
12173 checkRetainCycles(VDecl, Init);
12174
12175 // It is safe to assign a weak reference into a strong variable.
12176 // Although this code can still have problems:
12177 // id x = self.weakProp;
12178 // id y = self.weakProp;
12179 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12180 // paths through the function. This should be revisited if
12181 // -Wrepeated-use-of-weak is made flow-sensitive.
12182 if (FunctionScopeInfo *FSI = getCurFunction())
12183 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12184 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12185 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12186 Init->getBeginLoc()))
12187 FSI->markSafeWeakUse(Init);
12188 }
12189
12190 // The initialization is usually a full-expression.
12191 //
12192 // FIXME: If this is a braced initialization of an aggregate, it is not
12193 // an expression, and each individual field initializer is a separate
12194 // full-expression. For instance, in:
12195 //
12196 // struct Temp { ~Temp(); };
12197 // struct S { S(Temp); };
12198 // struct T { S a, b; } t = { Temp(), Temp() }
12199 //
12200 // we should destroy the first Temp before constructing the second.
12201 ExprResult Result =
12202 ActOnFinishFullExpr(Init, VDecl->getLocation(),
12203 /*DiscardedValue*/ false, VDecl->isConstexpr());
12204 if (Result.isInvalid()) {
12205 VDecl->setInvalidDecl();
12206 return;
12207 }
12208 Init = Result.get();
12209
12210 // Attach the initializer to the decl.
12211 VDecl->setInit(Init);
12212
12213 if (VDecl->isLocalVarDecl()) {
12214 // Don't check the initializer if the declaration is malformed.
12215 if (VDecl->isInvalidDecl()) {
12216 // do nothing
12217
12218 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12219 // This is true even in C++ for OpenCL.
12220 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12221 CheckForConstantInitializer(Init, DclT);
12222
12223 // Otherwise, C++ does not restrict the initializer.
12224 } else if (getLangOpts().CPlusPlus) {
12225 // do nothing
12226
12227 // C99 6.7.8p4: All the expressions in an initializer for an object that has
12228 // static storage duration shall be constant expressions or string literals.
12229 } else if (VDecl->getStorageClass() == SC_Static) {
12230 CheckForConstantInitializer(Init, DclT);
12231
12232 // C89 is stricter than C99 for aggregate initializers.
12233 // C89 6.5.7p3: All the expressions [...] in an initializer list
12234 // for an object that has aggregate or union type shall be
12235 // constant expressions.
12236 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12237 isa<InitListExpr>(Init)) {
12238 const Expr *Culprit;
12239 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12240 Diag(Culprit->getExprLoc(),
12241 diag::ext_aggregate_init_not_constant)
12242 << Culprit->getSourceRange();
12243 }
12244 }
12245
12246 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12247 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12248 if (VDecl->hasLocalStorage())
12249 BE->getBlockDecl()->setCanAvoidCopyToHeap();
12250 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12251 VDecl->getLexicalDeclContext()->isRecord()) {
12252 // This is an in-class initialization for a static data member, e.g.,
12253 //
12254 // struct S {
12255 // static const int value = 17;
12256 // };
12257
12258 // C++ [class.mem]p4:
12259 // A member-declarator can contain a constant-initializer only
12260 // if it declares a static member (9.4) of const integral or
12261 // const enumeration type, see 9.4.2.
12262 //
12263 // C++11 [class.static.data]p3:
12264 // If a non-volatile non-inline const static data member is of integral
12265 // or enumeration type, its declaration in the class definition can
12266 // specify a brace-or-equal-initializer in which every initializer-clause
12267 // that is an assignment-expression is a constant expression. A static
12268 // data member of literal type can be declared in the class definition
12269 // with the constexpr specifier; if so, its declaration shall specify a
12270 // brace-or-equal-initializer in which every initializer-clause that is
12271 // an assignment-expression is a constant expression.
12272
12273 // Do nothing on dependent types.
12274 if (DclT->isDependentType()) {
12275
12276 // Allow any 'static constexpr' members, whether or not they are of literal
12277 // type. We separately check that every constexpr variable is of literal
12278 // type.
12279 } else if (VDecl->isConstexpr()) {
12280
12281 // Require constness.
12282 } else if (!DclT.isConstQualified()) {
12283 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12284 << Init->getSourceRange();
12285 VDecl->setInvalidDecl();
12286
12287 // We allow integer constant expressions in all cases.
12288 } else if (DclT->isIntegralOrEnumerationType()) {
12289 // Check whether the expression is a constant expression.
12290 SourceLocation Loc;
12291 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12292 // In C++11, a non-constexpr const static data member with an
12293 // in-class initializer cannot be volatile.
12294 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12295 else if (Init->isValueDependent())
12296 ; // Nothing to check.
12297 else if (Init->isIntegerConstantExpr(Context, &Loc))
12298 ; // Ok, it's an ICE!
12299 else if (Init->getType()->isScopedEnumeralType() &&
12300 Init->isCXX11ConstantExpr(Context))
12301 ; // Ok, it is a scoped-enum constant expression.
12302 else if (Init->isEvaluatable(Context)) {
12303 // If we can constant fold the initializer through heroics, accept it,
12304 // but report this as a use of an extension for -pedantic.
12305 Diag(Loc, diag::ext_in_class_initializer_non_constant)
12306 << Init->getSourceRange();
12307 } else {
12308 // Otherwise, this is some crazy unknown case. Report the issue at the
12309 // location provided by the isIntegerConstantExpr failed check.
12310 Diag(Loc, diag::err_in_class_initializer_non_constant)
12311 << Init->getSourceRange();
12312 VDecl->setInvalidDecl();
12313 }
12314
12315 // We allow foldable floating-point constants as an extension.
12316 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12317 // In C++98, this is a GNU extension. In C++11, it is not, but we support
12318 // it anyway and provide a fixit to add the 'constexpr'.
12319 if (getLangOpts().CPlusPlus11) {
12320 Diag(VDecl->getLocation(),
12321 diag::ext_in_class_initializer_float_type_cxx11)
12322 << DclT << Init->getSourceRange();
12323 Diag(VDecl->getBeginLoc(),
12324 diag::note_in_class_initializer_float_type_cxx11)
12325 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12326 } else {
12327 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12328 << DclT << Init->getSourceRange();
12329
12330 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12331 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12332 << Init->getSourceRange();
12333 VDecl->setInvalidDecl();
12334 }
12335 }
12336
12337 // Suggest adding 'constexpr' in C++11 for literal types.
12338 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12339 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12340 << DclT << Init->getSourceRange()
12341 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12342 VDecl->setConstexpr(true);
12343
12344 } else {
12345 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12346 << DclT << Init->getSourceRange();
12347 VDecl->setInvalidDecl();
12348 }
12349 } else if (VDecl->isFileVarDecl()) {
12350 // In C, extern is typically used to avoid tentative definitions when
12351 // declaring variables in headers, but adding an intializer makes it a
12352 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12353 // In C++, extern is often used to give implictly static const variables
12354 // external linkage, so don't warn in that case. If selectany is present,
12355 // this might be header code intended for C and C++ inclusion, so apply the
12356 // C++ rules.
12357 if (VDecl->getStorageClass() == SC_Extern &&
12358 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12359 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12360 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12361 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12362 Diag(VDecl->getLocation(), diag::warn_extern_init);
12363
12364 // In Microsoft C++ mode, a const variable defined in namespace scope has
12365 // external linkage by default if the variable is declared with
12366 // __declspec(dllexport).
12367 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12368 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12369 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12370 VDecl->setStorageClass(SC_Extern);
12371
12372 // C99 6.7.8p4. All file scoped initializers need to be constant.
12373 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12374 CheckForConstantInitializer(Init, DclT);
12375 }
12376
12377 QualType InitType = Init->getType();
12378 if (!InitType.isNull() &&
12379 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12380 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12381 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12382
12383 // We will represent direct-initialization similarly to copy-initialization:
12384 // int x(1); -as-> int x = 1;
12385 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12386 //
12387 // Clients that want to distinguish between the two forms, can check for
12388 // direct initializer using VarDecl::getInitStyle().
12389 // A major benefit is that clients that don't particularly care about which
12390 // exactly form was it (like the CodeGen) can handle both cases without
12391 // special case code.
12392
12393 // C++ 8.5p11:
12394 // The form of initialization (using parentheses or '=') is generally
12395 // insignificant, but does matter when the entity being initialized has a
12396 // class type.
12397 if (CXXDirectInit) {
12398 assert(DirectInit && "Call-style initializer must be direct init.")((DirectInit && "Call-style initializer must be direct init."
) ? static_cast<void> (0) : __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 12398, __PRETTY_FUNCTION__))
;
12399 VDecl->setInitStyle(VarDecl::CallInit);
12400 } else if (DirectInit) {
12401 // This must be list-initialization. No other way is direct-initialization.
12402 VDecl->setInitStyle(VarDecl::ListInit);
12403 }
12404
12405 if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12406 DeclsToCheckForDeferredDiags.push_back(VDecl);
12407 CheckCompleteVariableDeclaration(VDecl);
12408}
12409
12410/// ActOnInitializerError - Given that there was an error parsing an
12411/// initializer for the given declaration, try to return to some form
12412/// of sanity.
12413void Sema::ActOnInitializerError(Decl *D) {
12414 // Our main concern here is re-establishing invariants like "a
12415 // variable's type is either dependent or complete".
12416 if (!D || D->isInvalidDecl()) return;
12417
12418 VarDecl *VD = dyn_cast<VarDecl>(D);
12419 if (!VD) return;
12420
12421 // Bindings are not usable if we can't make sense of the initializer.
12422 if (auto *DD = dyn_cast<DecompositionDecl>(D))
12423 for (auto *BD : DD->bindings())
12424 BD->setInvalidDecl();
12425
12426 // Auto types are meaningless if we can't make sense of the initializer.
12427 if (VD->getType()->isUndeducedType()) {
12428 D->setInvalidDecl();
12429 return;
12430 }
12431
12432 QualType Ty = VD->getType();
12433 if (Ty->isDependentType()) return;
12434
12435 // Require a complete type.
12436 if (RequireCompleteType(VD->getLocation(),
12437 Context.getBaseElementType(Ty),
12438 diag::err_typecheck_decl_incomplete_type)) {
12439 VD->setInvalidDecl();
12440 return;
12441 }
12442
12443 // Require a non-abstract type.
12444 if (RequireNonAbstractType(VD->getLocation(), Ty,
12445 diag::err_abstract_type_in_decl,
12446 AbstractVariableType)) {
12447 VD->setInvalidDecl();
12448 return;
12449 }
12450
12451 // Don't bother complaining about constructors or destructors,
12452 // though.
12453}
12454
12455void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12456 // If there is no declaration, there was an error parsing it. Just ignore it.
12457 if (!RealDecl)
12458 return;
12459
12460 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12461 QualType Type = Var->getType();
12462
12463 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12464 if (isa<DecompositionDecl>(RealDecl)) {
12465 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12466 Var->setInvalidDecl();
12467 return;
12468 }
12469
12470 if (Type->isUndeducedType() &&
12471 DeduceVariableDeclarationType(Var, false, nullptr))
12472 return;
12473
12474 // C++11 [class.static.data]p3: A static data member can be declared with
12475 // the constexpr specifier; if so, its declaration shall specify
12476 // a brace-or-equal-initializer.
12477 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12478 // the definition of a variable [...] or the declaration of a static data
12479 // member.
12480 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12481 !Var->isThisDeclarationADemotedDefinition()) {
12482 if (Var->isStaticDataMember()) {
12483 // C++1z removes the relevant rule; the in-class declaration is always
12484 // a definition there.
12485 if (!getLangOpts().CPlusPlus17 &&
12486 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12487 Diag(Var->getLocation(),
12488 diag::err_constexpr_static_mem_var_requires_init)
12489 << Var;
12490 Var->setInvalidDecl();
12491 return;
12492 }
12493 } else {
12494 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12495 Var->setInvalidDecl();
12496 return;
12497 }
12498 }
12499
12500 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12501 // be initialized.
12502 if (!Var->isInvalidDecl() &&
12503 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12504 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12505 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12506 Var->setInvalidDecl();
12507 return;
12508 }
12509
12510 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12511 if (Var->getStorageClass() == SC_Extern) {
12512 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12513 << Var;
12514 Var->setInvalidDecl();
12515 return;
12516 }
12517 if (RequireCompleteType(Var->getLocation(), Var->getType(),
12518 diag::err_typecheck_decl_incomplete_type)) {
12519 Var->setInvalidDecl();
12520 return;
12521 }
12522 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12523 if (!RD->hasTrivialDefaultConstructor()) {
12524 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12525 Var->setInvalidDecl();
12526 return;
12527 }
12528 }
12529 }
12530
12531 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12532 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12533 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12534 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12535 NTCUC_DefaultInitializedObject, NTCUK_Init);
12536
12537
12538 switch (DefKind) {
12539 case VarDecl::Definition:
12540 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12541 break;
12542
12543 // We have an out-of-line definition of a static data member
12544 // that has an in-class initializer, so we type-check this like
12545 // a declaration.
12546 //
12547 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12548
12549 case VarDecl::DeclarationOnly:
12550 // It's only a declaration.
12551
12552 // Block scope. C99 6.7p7: If an identifier for an object is
12553 // declared with no linkage (C99 6.2.2p6), the type for the
12554 // object shall be complete.
12555 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12556 !Var->hasLinkage() && !Var->isInvalidDecl() &&
12557 RequireCompleteType(Var->getLocation(), Type,
12558 diag::err_typecheck_decl_incomplete_type))
12559 Var->setInvalidDecl();
12560
12561 // Make sure that the type is not abstract.
12562 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12563 RequireNonAbstractType(Var->getLocation(), Type,
12564 diag::err_abstract_type_in_decl,
12565 AbstractVariableType))
12566 Var->setInvalidDecl();
12567 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12568 Var->getStorageClass() == SC_PrivateExtern) {
12569 Diag(Var->getLocation(), diag::warn_private_extern);
12570 Diag(Var->getLocation(), diag::note_private_extern);
12571 }
12572
12573 if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12574 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12575 ExternalDeclarations.push_back(Var);
12576
12577 return;
12578
12579 case VarDecl::TentativeDefinition:
12580 // File scope. C99 6.9.2p2: A declaration of an identifier for an
12581 // object that has file scope without an initializer, and without a
12582 // storage-class specifier or with the storage-class specifier "static",
12583 // constitutes a tentative definition. Note: A tentative definition with
12584 // external linkage is valid (C99 6.2.2p5).
12585 if (!Var->isInvalidDecl()) {
12586 if (const IncompleteArrayType *ArrayT
12587 = Context.getAsIncompleteArrayType(Type)) {
12588 if (RequireCompleteSizedType(
12589 Var->getLocation(), ArrayT->getElementType(),
12590 diag::err_array_incomplete_or_sizeless_type))
12591 Var->setInvalidDecl();
12592 } else if (Var->getStorageClass() == SC_Static) {
12593 // C99 6.9.2p3: If the declaration of an identifier for an object is
12594 // a tentative definition and has internal linkage (C99 6.2.2p3), the
12595 // declared type shall not be an incomplete type.
12596 // NOTE: code such as the following
12597 // static struct s;
12598 // struct s { int a; };
12599 // is accepted by gcc. Hence here we issue a warning instead of
12600 // an error and we do not invalidate the static declaration.
12601 // NOTE: to avoid multiple warnings, only check the first declaration.
12602 if (Var->isFirstDecl())
12603 RequireCompleteType(Var->getLocation(), Type,
12604 diag::ext_typecheck_decl_incomplete_type);
12605 }
12606 }
12607
12608 // Record the tentative definition; we're done.
12609 if (!Var->isInvalidDecl())
12610 TentativeDefinitions.push_back(Var);
12611 return;
12612 }
12613
12614 // Provide a specific diagnostic for uninitialized variable
12615 // definitions with incomplete array type.
12616 if (Type->isIncompleteArrayType()) {
12617 Diag(Var->getLocation(),
12618 diag::err_typecheck_incomplete_array_needs_initializer);
12619 Var->setInvalidDecl();
12620 return;
12621 }
12622
12623 // Provide a specific diagnostic for uninitialized variable
12624 // definitions with reference type.
12625 if (Type->isReferenceType()) {
12626 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12627 << Var << SourceRange(Var->getLocation(), Var->getLocation());
12628 Var->setInvalidDecl();
12629 return;
12630 }
12631
12632 // Do not attempt to type-check the default initializer for a
12633 // variable with dependent type.
12634 if (Type->isDependentType())
12635 return;
12636
12637 if (Var->isInvalidDecl())
12638 return;
12639
12640 if (!Var->hasAttr<AliasAttr>()) {
12641 if (RequireCompleteType(Var->getLocation(),
12642 Context.getBaseElementType(Type),
12643 diag::err_typecheck_decl_incomplete_type)) {
12644 Var->setInvalidDecl();
12645 return;
12646 }
12647 } else {
12648 return;
12649 }
12650
12651 // The variable can not have an abstract class type.
12652 if (RequireNonAbstractType(Var->getLocation(), Type,
12653 diag::err_abstract_type_in_decl,
12654 AbstractVariableType)) {
12655 Var->setInvalidDecl();
12656 return;
12657 }
12658
12659 // Check for jumps past the implicit initializer. C++0x
12660 // clarifies that this applies to a "variable with automatic
12661 // storage duration", not a "local variable".
12662 // C++11 [stmt.dcl]p3
12663 // A program that jumps from a point where a variable with automatic
12664 // storage duration is not in scope to a point where it is in scope is
12665 // ill-formed unless the variable has scalar type, class type with a
12666 // trivial default constructor and a trivial destructor, a cv-qualified
12667 // version of one of these types, or an array of one of the preceding
12668 // types and is declared without an initializer.
12669 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12670 if (const RecordType *Record
12671 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12672 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12673 // Mark the function (if we're in one) for further checking even if the
12674 // looser rules of C++11 do not require such checks, so that we can
12675 // diagnose incompatibilities with C++98.
12676 if (!CXXRecord->isPOD())
12677 setFunctionHasBranchProtectedScope();
12678 }
12679 }
12680 // In OpenCL, we can't initialize objects in the __local address space,
12681 // even implicitly, so don't synthesize an implicit initializer.
12682 if (getLangOpts().OpenCL &&
12683 Var->getType().getAddressSpace() == LangAS::opencl_local)
12684 return;
12685 // C++03 [dcl.init]p9:
12686 // If no initializer is specified for an object, and the
12687 // object is of (possibly cv-qualified) non-POD class type (or
12688 // array thereof), the object shall be default-initialized; if
12689 // the object is of const-qualified type, the underlying class
12690 // type shall have a user-declared default
12691 // constructor. Otherwise, if no initializer is specified for
12692 // a non- static object, the object and its subobjects, if
12693 // any, have an indeterminate initial value); if the object
12694 // or any of its subobjects are of const-qualified type, the
12695 // program is ill-formed.
12696 // C++0x [dcl.init]p11:
12697 // If no initializer is specified for an object, the object is
12698 // default-initialized; [...].
12699 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12700 InitializationKind Kind
12701 = InitializationKind::CreateDefault(Var->getLocation());
12702
12703 InitializationSequence InitSeq(*this, Entity, Kind, None);
12704 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12705
12706 if (Init.get()) {
12707 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12708 // This is important for template substitution.
12709 Var->setInitStyle(VarDecl::CallInit);
12710 } else if (Init.isInvalid()) {
12711 // If default-init fails, attach a recovery-expr initializer to track
12712 // that initialization was attempted and failed.
12713 auto RecoveryExpr =
12714 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12715 if (RecoveryExpr.get())
12716 Var->setInit(RecoveryExpr.get());
12717 }
12718
12719 CheckCompleteVariableDeclaration(Var);
12720 }
12721}
12722
12723void Sema::ActOnCXXForRangeDecl(Decl *D) {
12724 // If there is no declaration, there was an error parsing it. Ignore it.
12725 if (!D)
12726 return;
12727
12728 VarDecl *VD = dyn_cast<VarDecl>(D);
12729 if (!VD) {
12730 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12731 D->setInvalidDecl();
12732 return;
12733 }
12734
12735 VD->setCXXForRangeDecl(true);
12736
12737 // for-range-declaration cannot be given a storage class specifier.
12738 int Error = -1;
12739 switch (VD->getStorageClass()) {
12740 case SC_None:
12741 break;
12742 case SC_Extern:
12743 Error = 0;
12744 break;
12745 case SC_Static:
12746 Error = 1;
12747 break;
12748 case SC_PrivateExtern:
12749 Error = 2;
12750 break;
12751 case SC_Auto:
12752 Error = 3;
12753 break;
12754 case SC_Register:
12755 Error = 4;
12756 break;
12757 }
12758 if (Error != -1) {
12759 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12760 << VD << Error;
12761 D->setInvalidDecl();
12762 }
12763}
12764
12765StmtResult
12766Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12767 IdentifierInfo *Ident,
12768 ParsedAttributes &Attrs,
12769 SourceLocation AttrEnd) {
12770 // C++1y [stmt.iter]p1:
12771 // A range-based for statement of the form
12772 // for ( for-range-identifier : for-range-initializer ) statement
12773 // is equivalent to
12774 // for ( auto&& for-range-identifier : for-range-initializer ) statement
12775 DeclSpec DS(Attrs.getPool().getFactory());
12776
12777 const char *PrevSpec;
12778 unsigned DiagID;
12779 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12780 getPrintingPolicy());
12781
12782 Declarator D(DS, DeclaratorContext::ForInit);
12783 D.SetIdentifier(Ident, IdentLoc);
12784 D.takeAttributes(Attrs, AttrEnd);
12785
12786 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12787 IdentLoc);
12788 Decl *Var = ActOnDeclarator(S, D);
12789 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12790 FinalizeDeclaration(Var);
12791 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12792 AttrEnd.isValid() ? AttrEnd : IdentLoc);
12793}
12794
12795void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12796 if (var->isInvalidDecl()) return;
12797
12798 if (getLangOpts().OpenCL) {
12799 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12800 // initialiser
12801 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12802 !var->hasInit()) {
12803 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12804 << 1 /*Init*/;
12805 var->setInvalidDecl();
12806 return;
12807 }
12808 }
12809
12810 // In Objective-C, don't allow jumps past the implicit initialization of a
12811 // local retaining variable.
12812 if (getLangOpts().ObjC &&
12813 var->hasLocalStorage()) {
12814 switch (var->getType().getObjCLifetime()) {
12815 case Qualifiers::OCL_None:
12816 case Qualifiers::OCL_ExplicitNone:
12817 case Qualifiers::OCL_Autoreleasing:
12818 break;
12819
12820 case Qualifiers::OCL_Weak:
12821 case Qualifiers::OCL_Strong:
12822 setFunctionHasBranchProtectedScope();
12823 break;
12824 }
12825 }
12826
12827 if (var->hasLocalStorage() &&
12828 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12829 setFunctionHasBranchProtectedScope();
12830
12831 // Warn about externally-visible variables being defined without a
12832 // prior declaration. We only want to do this for global
12833 // declarations, but we also specifically need to avoid doing it for
12834 // class members because the linkage of an anonymous class can
12835 // change if it's later given a typedef name.
12836 if (var->isThisDeclarationADefinition() &&
12837 var->getDeclContext()->getRedeclContext()->isFileContext() &&
12838 var->isExternallyVisible() && var->hasLinkage() &&
12839 !var->isInline() && !var->getDescribedVarTemplate() &&
12840 !isa<VarTemplatePartialSpecializationDecl>(var) &&
12841 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12842 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12843 var->getLocation())) {
12844 // Find a previous declaration that's not a definition.
12845 VarDecl *prev = var->getPreviousDecl();
12846 while (prev && prev->isThisDeclarationADefinition())
12847 prev = prev->getPreviousDecl();
12848
12849 if (!prev) {
12850 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12851 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12852 << /* variable */ 0;
12853 }
12854 }
12855
12856 // Cache the result of checking for constant initialization.
12857 Optional<bool> CacheHasConstInit;
12858 const Expr *CacheCulprit = nullptr;
12859 auto checkConstInit = [&]() mutable {
12860 if (!CacheHasConstInit)
12861 CacheHasConstInit = var->getInit()->isConstantInitializer(
12862 Context, var->getType()->isReferenceType(), &CacheCulprit);
12863 return *CacheHasConstInit;
12864 };
12865
12866 if (var->getTLSKind() == VarDecl::TLS_Static) {
12867 if (var->getType().isDestructedType()) {
12868 // GNU C++98 edits for __thread, [basic.start.term]p3:
12869 // The type of an object with thread storage duration shall not
12870 // have a non-trivial destructor.
12871 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12872 if (getLangOpts().CPlusPlus11)
12873 Diag(var->getLocation(), diag::note_use_thread_local);
12874 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12875 if (!checkConstInit()) {
12876 // GNU C++98 edits for __thread, [basic.start.init]p4:
12877 // An object of thread storage duration shall not require dynamic
12878 // initialization.
12879 // FIXME: Need strict checking here.
12880 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12881 << CacheCulprit->getSourceRange();
12882 if (getLangOpts().CPlusPlus11)
12883 Diag(var->getLocation(), diag::note_use_thread_local);
12884 }
12885 }
12886 }
12887
12888 // Apply section attributes and pragmas to global variables.
12889 bool GlobalStorage = var->hasGlobalStorage();
12890 if (GlobalStorage && var->isThisDeclarationADefinition() &&
12891 !inTemplateInstantiation()) {
12892 PragmaStack<StringLiteral *> *Stack = nullptr;
12893 int SectionFlags = ASTContext::PSF_Read;
12894 if (var->getType().isConstQualified())
12895 Stack = &ConstSegStack;
12896 else if (!var->getInit()) {
12897 Stack = &BSSSegStack;
12898 SectionFlags |= ASTContext::PSF_Write;
12899 } else {
12900 Stack = &DataSegStack;
12901 SectionFlags |= ASTContext::PSF_Write;
12902 }
12903 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
12904 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
12905 SectionFlags |= ASTContext::PSF_Implicit;
12906 UnifySection(SA->getName(), SectionFlags, var);
12907 } else if (Stack->CurrentValue) {
12908 SectionFlags |= ASTContext::PSF_Implicit;
12909 auto SectionName = Stack->CurrentValue->getString();
12910 var->addAttr(SectionAttr::CreateImplicit(
12911 Context, SectionName, Stack->CurrentPragmaLocation,
12912 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
12913 if (UnifySection(SectionName, SectionFlags, var))
12914 var->dropAttr<SectionAttr>();
12915 }
12916
12917 // Apply the init_seg attribute if this has an initializer. If the
12918 // initializer turns out to not be dynamic, we'll end up ignoring this
12919 // attribute.
12920 if (CurInitSeg && var->getInit())
12921 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12922 CurInitSegLoc,
12923 AttributeCommonInfo::AS_Pragma));
12924 }
12925
12926 if (!var->getType()->isStructureType() && var->hasInit() &&
12927 isa<InitListExpr>(var->getInit())) {
12928 const auto *ILE = cast<InitListExpr>(var->getInit());
12929 unsigned NumInits = ILE->getNumInits();
12930 if (NumInits > 2)
12931 for (unsigned I = 0; I < NumInits; ++I) {
12932 const auto *Init = ILE->getInit(I);
12933 if (!Init)
12934 break;
12935 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12936 if (!SL)
12937 break;
12938
12939 unsigned NumConcat = SL->getNumConcatenated();
12940 // Diagnose missing comma in string array initialization.
12941 // Do not warn when all the elements in the initializer are concatenated
12942 // together. Do not warn for macros too.
12943 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
12944 bool OnlyOneMissingComma = true;
12945 for (unsigned J = I + 1; J < NumInits; ++J) {
12946 const auto *Init = ILE->getInit(J);
12947 if (!Init)
12948 break;
12949 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12950 if (!SLJ || SLJ->getNumConcatenated() > 1) {
12951 OnlyOneMissingComma = false;
12952 break;
12953 }
12954 }
12955
12956 if (OnlyOneMissingComma) {
12957 SmallVector<FixItHint, 1> Hints;
12958 for (unsigned i = 0; i < NumConcat - 1; ++i)
12959 Hints.push_back(FixItHint::CreateInsertion(
12960 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
12961
12962 Diag(SL->getStrTokenLoc(1),
12963 diag::warn_concatenated_literal_array_init)
12964 << Hints;
12965 Diag(SL->getBeginLoc(),
12966 diag::note_concatenated_string_literal_silence);
12967 }
12968 // In any case, stop now.
12969 break;
12970 }
12971 }
12972 }
12973
12974 // All the following checks are C++ only.
12975 if (!getLangOpts().CPlusPlus) {
12976 // If this variable must be emitted, add it as an initializer for the
12977 // current module.
12978 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12979 Context.addModuleInitializer(ModuleScopes.back().Module, var);
12980 return;
12981 }
12982
12983 QualType type = var->getType();
12984
12985 if (var->hasAttr<BlocksAttr>())
12986 getCurFunction()->addByrefBlockVar(var);
12987
12988 Expr *Init = var->getInit();
12989 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12990 QualType baseType = Context.getBaseElementType(type);
12991
12992 // Check whether the initializer is sufficiently constant.
12993 if (!type->isDependentType() && Init && !Init->isValueDependent() &&
12994 (GlobalStorage || var->isConstexpr() ||
12995 var->mightBeUsableInConstantExpressions(Context))) {
12996 // If this variable might have a constant initializer or might be usable in
12997 // constant expressions, check whether or not it actually is now. We can't
12998 // do this lazily, because the result might depend on things that change
12999 // later, such as which constexpr functions happen to be defined.
13000 SmallVector<PartialDiagnosticAt, 8> Notes;
13001 bool HasConstInit;
13002 if (!getLangOpts().CPlusPlus11) {
13003 // Prior to C++11, in contexts where a constant initializer is required,
13004 // the set of valid constant initializers is described by syntactic rules
13005 // in [expr.const]p2-6.
13006 // FIXME: Stricter checking for these rules would be useful for constinit /
13007 // -Wglobal-constructors.
13008 HasConstInit = checkConstInit();
13009
13010 // Compute and cache the constant value, and remember that we have a
13011 // constant initializer.
13012 if (HasConstInit) {
13013 (void)var->checkForConstantInitialization(Notes);
13014 Notes.clear();
13015 } else if (CacheCulprit) {
13016 Notes.emplace_back(CacheCulprit->getExprLoc(),
13017 PDiag(diag::note_invalid_subexpr_in_const_expr));
13018 Notes.back().second << CacheCulprit->getSourceRange();
13019 }
13020 } else {
13021 // Evaluate the initializer to see if it's a constant initializer.
13022 HasConstInit = var->checkForConstantInitialization(Notes);
13023 }
13024
13025 if (HasConstInit) {
13026 // FIXME: Consider replacing the initializer with a ConstantExpr.
13027 } else if (var->isConstexpr()) {
13028 SourceLocation DiagLoc = var->getLocation();
13029 // If the note doesn't add any useful information other than a source
13030 // location, fold it into the primary diagnostic.
13031 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13032 diag::note_invalid_subexpr_in_const_expr) {
13033 DiagLoc = Notes[0].first;
13034 Notes.clear();
13035 }
13036 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13037 << var << Init->getSourceRange();
13038 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13039 Diag(Notes[I].first, Notes[I].second);
13040 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13041 auto *Attr = var->getAttr<ConstInitAttr>();
13042 Diag(var->getLocation(), diag::err_require_constant_init_failed)
13043 << Init->getSourceRange();
13044 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13045 << Attr->getRange() << Attr->isConstinit();
13046 for (auto &it : Notes)
13047 Diag(it.first, it.second);
13048 } else if (IsGlobal &&
13049 !getDiagnostics().isIgnored(diag::warn_global_constructor,
13050 var->getLocation())) {
13051 // Warn about globals which don't have a constant initializer. Don't
13052 // warn about globals with a non-trivial destructor because we already
13053 // warned about them.
13054 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13055 if (!(RD && !RD->hasTrivialDestructor())) {
13056 // checkConstInit() here permits trivial default initialization even in
13057 // C++11 onwards, where such an initializer is not a constant initializer
13058 // but nonetheless doesn't require a global constructor.
13059 if (!checkConstInit())
13060 Diag(var->getLocation(), diag::warn_global_constructor)
13061 << Init->getSourceRange();
13062 }
13063 }
13064 }
13065
13066 // Require the destructor.
13067 if (!type->isDependentType())
13068 if (const RecordType *recordType = baseType->getAs<RecordType>())
13069 FinalizeVarWithDestructor(var, recordType);
13070
13071 // If this variable must be emitted, add it as an initializer for the current
13072 // module.
13073 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13074 Context.addModuleInitializer(ModuleScopes.back().Module, var);
13075
13076 // Build the bindings if this is a structured binding declaration.
13077 if (auto *DD = dyn_cast<DecompositionDecl>(var))
13078 CheckCompleteDecompositionDeclaration(DD);
13079}
13080
13081/// Determines if a variable's alignment is dependent.
13082static bool hasDependentAlignment(VarDecl *VD) {
13083 if (VD->getType()->isDependentType())
13084 return true;
13085 for (auto *I : VD->specific_attrs<AlignedAttr>())
13086 if (I->isAlignmentDependent())
13087 return true;
13088 return false;
13089}
13090
13091/// Check if VD needs to be dllexport/dllimport due to being in a
13092/// dllexport/import function.
13093void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13094 assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail
("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 13094, __PRETTY_FUNCTION__))
;
13095
13096 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13097
13098 // Find outermost function when VD is in lambda function.
13099 while (FD && !getDLLAttr(FD) &&
13100 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13101 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13102 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13103 }
13104
13105 if (!FD)
13106 return;
13107
13108 // Static locals inherit dll attributes from their function.
13109 if (Attr *A = getDLLAttr(FD)) {
13110 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13111 NewAttr->setInherited(true);
13112 VD->addAttr(NewAttr);
13113 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13114 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13115 NewAttr->setInherited(true);
13116 VD->addAttr(NewAttr);
13117
13118 // Export this function to enforce exporting this static variable even
13119 // if it is not used in this compilation unit.
13120 if (!FD->hasAttr<DLLExportAttr>())
13121 FD->addAttr(NewAttr);
13122
13123 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13124 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13125 NewAttr->setInherited(true);
13126 VD->addAttr(NewAttr);
13127 }
13128}
13129
13130/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13131/// any semantic actions necessary after any initializer has been attached.
13132void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13133 // Note that we are no longer parsing the initializer for this declaration.
13134 ParsingInitForAutoVars.erase(ThisDecl);
13135
13136 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13137 if (!VD)
13138 return;
13139
13140 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13141 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13142 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13143 if (PragmaClangBSSSection.Valid)
13144 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13145 Context, PragmaClangBSSSection.SectionName,
13146 PragmaClangBSSSection.PragmaLocation,
13147 AttributeCommonInfo::AS_Pragma));
13148 if (PragmaClangDataSection.Valid)
13149 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13150 Context, PragmaClangDataSection.SectionName,
13151 PragmaClangDataSection.PragmaLocation,
13152 AttributeCommonInfo::AS_Pragma));
13153 if (PragmaClangRodataSection.Valid)
13154 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13155 Context, PragmaClangRodataSection.SectionName,
13156 PragmaClangRodataSection.PragmaLocation,
13157 AttributeCommonInfo::AS_Pragma));
13158 if (PragmaClangRelroSection.Valid)
13159 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13160 Context, PragmaClangRelroSection.SectionName,
13161 PragmaClangRelroSection.PragmaLocation,
13162 AttributeCommonInfo::AS_Pragma));
13163 }
13164
13165 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13166 for (auto *BD : DD->bindings()) {
13167 FinalizeDeclaration(BD);
13168 }
13169 }
13170
13171 checkAttributesAfterMerging(*this, *VD);
13172
13173 // Perform TLS alignment check here after attributes attached to the variable
13174 // which may affect the alignment have been processed. Only perform the check
13175 // if the target has a maximum TLS alignment (zero means no constraints).
13176 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13177 // Protect the check so that it's not performed on dependent types and
13178 // dependent alignments (we can't determine the alignment in that case).
13179 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13180 !VD->isInvalidDecl()) {
13181 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13182 if (Context.getDeclAlign(VD) > MaxAlignChars) {
13183 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13184 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13185 << (unsigned)MaxAlignChars.getQuantity();
13186 }
13187 }
13188 }
13189
13190 if (VD->isStaticLocal())
13191 CheckStaticLocalForDllExport(VD);
13192
13193 // Perform check for initializers of device-side global variables.
13194 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13195 // 7.5). We must also apply the same checks to all __shared__
13196 // variables whether they are local or not. CUDA also allows
13197 // constant initializers for __constant__ and __device__ variables.
13198 if (getLangOpts().CUDA)
13199 checkAllowedCUDAInitializer(VD);
13200
13201 // Grab the dllimport or dllexport attribute off of the VarDecl.
13202 const InheritableAttr *DLLAttr = getDLLAttr(VD);
13203
13204 // Imported static data members cannot be defined out-of-line.
13205 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13206 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13207 VD->isThisDeclarationADefinition()) {
13208 // We allow definitions of dllimport class template static data members
13209 // with a warning.
13210 CXXRecordDecl *Context =
13211 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13212 bool IsClassTemplateMember =
13213 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13214 Context->getDescribedClassTemplate();
13215
13216 Diag(VD->getLocation(),
13217 IsClassTemplateMember
13218 ? diag::warn_attribute_dllimport_static_field_definition
13219 : diag::err_attribute_dllimport_static_field_definition);
13220 Diag(IA->getLocation(), diag::note_attribute);
13221 if (!IsClassTemplateMember)
13222 VD->setInvalidDecl();
13223 }
13224 }
13225
13226 // dllimport/dllexport variables cannot be thread local, their TLS index
13227 // isn't exported with the variable.
13228 if (DLLAttr && VD->getTLSKind()) {
13229 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13230 if (F && getDLLAttr(F)) {
13231 assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail
("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 13231, __PRETTY_FUNCTION__))
;
13232 // But if this is a static local in a dlimport/dllexport function, the
13233 // function will never be inlined, which means the var would never be
13234 // imported, so having it marked import/export is safe.
13235 } else {
13236 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13237 << DLLAttr;
13238 VD->setInvalidDecl();
13239 }
13240 }
13241
13242 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13243 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13244 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13245 VD->dropAttr<UsedAttr>();
13246 }
13247 }
13248
13249 const DeclContext *DC = VD->getDeclContext();
13250 // If there's a #pragma GCC visibility in scope, and this isn't a class
13251 // member, set the visibility of this variable.
13252 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13253 AddPushedVisibilityAttribute(VD);
13254
13255 // FIXME: Warn on unused var template partial specializations.
13256 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13257 MarkUnusedFileScopedDecl(VD);
13258
13259 // Now we have parsed the initializer and can update the table of magic
13260 // tag values.
13261 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13262 !VD->getType()->isIntegralOrEnumerationType())
13263 return;
13264
13265 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13266 const Expr *MagicValueExpr = VD->getInit();
13267 if (!MagicValueExpr) {
13268 continue;
13269 }
13270 Optional<llvm::APSInt> MagicValueInt;
13271 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13272 Diag(I->getRange().getBegin(),
13273 diag::err_type_tag_for_datatype_not_ice)
13274 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13275 continue;
13276 }
13277 if (MagicValueInt->getActiveBits() > 64) {
13278 Diag(I->getRange().getBegin(),
13279 diag::err_type_tag_for_datatype_too_large)
13280 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13281 continue;
13282 }
13283 uint64_t MagicValue = MagicValueInt->getZExtValue();
13284 RegisterTypeTagForDatatype(I->getArgumentKind(),
13285 MagicValue,
13286 I->getMatchingCType(),
13287 I->getLayoutCompatible(),
13288 I->getMustBeNull());
13289 }
13290}
13291
13292static bool hasDeducedAuto(DeclaratorDecl *DD) {
13293 auto *VD = dyn_cast<VarDecl>(DD);
13294 return VD && !VD->getType()->hasAutoForTrailingReturnType();
13295}
13296
13297Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13298 ArrayRef<Decl *> Group) {
13299 SmallVector<Decl*, 8> Decls;
13300
13301 if (DS.isTypeSpecOwned())
13302 Decls.push_back(DS.getRepAsDecl());
13303
13304 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13305 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13306 bool DiagnosedMultipleDecomps = false;
13307 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13308 bool DiagnosedNonDeducedAuto = false;
13309
13310 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13311 if (Decl *D = Group[i]) {
13312 // For declarators, there are some additional syntactic-ish checks we need
13313 // to perform.
13314 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13315 if (!FirstDeclaratorInGroup)
13316 FirstDeclaratorInGroup = DD;
13317 if (!FirstDecompDeclaratorInGroup)
13318 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13319 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13320 !hasDeducedAuto(DD))
13321 FirstNonDeducedAutoInGroup = DD;
13322
13323 if (FirstDeclaratorInGroup != DD) {
13324 // A decomposition declaration cannot be combined with any other
13325 // declaration in the same group.
13326 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13327 Diag(FirstDecompDeclaratorInGroup->getLocation(),
13328 diag::err_decomp_decl_not_alone)
13329 << FirstDeclaratorInGroup->getSourceRange()
13330 << DD->getSourceRange();
13331 DiagnosedMultipleDecomps = true;
13332 }
13333
13334 // A declarator that uses 'auto' in any way other than to declare a
13335 // variable with a deduced type cannot be combined with any other
13336 // declarator in the same group.
13337 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13338 Diag(FirstNonDeducedAutoInGroup->getLocation(),
13339 diag::err_auto_non_deduced_not_alone)
13340 << FirstNonDeducedAutoInGroup->getType()
13341 ->hasAutoForTrailingReturnType()
13342 << FirstDeclaratorInGroup->getSourceRange()
13343 << DD->getSourceRange();
13344 DiagnosedNonDeducedAuto = true;
13345 }
13346 }
13347 }
13348
13349 Decls.push_back(D);
13350 }
13351 }
13352
13353 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13354 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13355 handleTagNumbering(Tag, S);
13356 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13357 getLangOpts().CPlusPlus)
13358 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13359 }
13360 }
13361
13362 return BuildDeclaratorGroup(Decls);
13363}
13364
13365/// BuildDeclaratorGroup - convert a list of declarations into a declaration
13366/// group, performing any necessary semantic checking.
13367Sema::DeclGroupPtrTy
13368Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13369 // C++14 [dcl.spec.auto]p7: (DR1347)
13370 // If the type that replaces the placeholder type is not the same in each
13371 // deduction, the program is ill-formed.
13372 if (Group.size() > 1) {
13373 QualType Deduced;
13374 VarDecl *DeducedDecl = nullptr;
13375 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13376 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13377 if (!D || D->isInvalidDecl())
13378 break;
13379 DeducedType *DT = D->getType()->getContainedDeducedType();
13380 if (!DT || DT->getDeducedType().isNull())
13381 continue;
13382 if (Deduced.isNull()) {
13383 Deduced = DT->getDeducedType();
13384 DeducedDecl = D;
13385 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13386 auto *AT = dyn_cast<AutoType>(DT);
13387 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13388 diag::err_auto_different_deductions)
13389 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13390 << DeducedDecl->getDeclName() << DT->getDeducedType()
13391 << D->getDeclName();
13392 if (DeducedDecl->hasInit())
13393 Dia << DeducedDecl->getInit()->getSourceRange();
13394 if (D->getInit())
13395 Dia << D->getInit()->getSourceRange();
13396 D->setInvalidDecl();
13397 break;
13398 }
13399 }
13400 }
13401
13402 ActOnDocumentableDecls(Group);
13403
13404 return DeclGroupPtrTy::make(
13405 DeclGroupRef::Create(Context, Group.data(), Group.size()));
13406}
13407
13408void Sema::ActOnDocumentableDecl(Decl *D) {
13409 ActOnDocumentableDecls(D);
13410}
13411
13412void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13413 // Don't parse the comment if Doxygen diagnostics are ignored.
13414 if (Group.empty() || !Group[0])
13415 return;
13416
13417 if (Diags.isIgnored(diag::warn_doc_param_not_found,
13418 Group[0]->getLocation()) &&
13419 Diags.isIgnored(diag::warn_unknown_comment_command_name,
13420 Group[0]->getLocation()))
13421 return;
13422
13423 if (Group.size() >= 2) {
13424 // This is a decl group. Normally it will contain only declarations
13425 // produced from declarator list. But in case we have any definitions or
13426 // additional declaration references:
13427 // 'typedef struct S {} S;'
13428 // 'typedef struct S *S;'
13429 // 'struct S *pS;'
13430 // FinalizeDeclaratorGroup adds these as separate declarations.
13431 Decl *MaybeTagDecl = Group[0];
13432 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13433 Group = Group.slice(1);
13434 }
13435 }
13436
13437 // FIMXE: We assume every Decl in the group is in the same file.
13438 // This is false when preprocessor constructs the group from decls in
13439 // different files (e. g. macros or #include).
13440 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13441}
13442
13443/// Common checks for a parameter-declaration that should apply to both function
13444/// parameters and non-type template parameters.
13445void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13446 // Check that there are no default arguments inside the type of this
13447 // parameter.
13448 if (getLangOpts().CPlusPlus)
13449 CheckExtraCXXDefaultArguments(D);
13450
13451 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13452 if (D.getCXXScopeSpec().isSet()) {
13453 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13454 << D.getCXXScopeSpec().getRange();
13455 }
13456
13457 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13458 // simple identifier except [...irrelevant cases...].
13459 switch (D.getName().getKind()) {
13460 case UnqualifiedIdKind::IK_Identifier:
13461 break;
13462
13463 case UnqualifiedIdKind::IK_OperatorFunctionId:
13464 case UnqualifiedIdKind::IK_ConversionFunctionId:
13465 case UnqualifiedIdKind::IK_LiteralOperatorId:
13466 case UnqualifiedIdKind::IK_ConstructorName:
13467 case UnqualifiedIdKind::IK_DestructorName:
13468 case UnqualifiedIdKind::IK_ImplicitSelfParam:
13469 case UnqualifiedIdKind::IK_DeductionGuideName:
13470 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13471 << GetNameForDeclarator(D).getName();
13472 break;
13473
13474 case UnqualifiedIdKind::IK_TemplateId:
13475 case UnqualifiedIdKind::IK_ConstructorTemplateId:
13476 // GetNameForDeclarator would not produce a useful name in this case.
13477 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13478 break;
13479 }
13480}
13481
13482/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13483/// to introduce parameters into function prototype scope.
13484Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13485 const DeclSpec &DS = D.getDeclSpec();
13486
13487 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13488
13489 // C++03 [dcl.stc]p2 also permits 'auto'.
13490 StorageClass SC = SC_None;
13491 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13492 SC = SC_Register;
13493 // In C++11, the 'register' storage class specifier is deprecated.
13494 // In C++17, it is not allowed, but we tolerate it as an extension.
13495 if (getLangOpts().CPlusPlus11) {
13496 Diag(DS.getStorageClassSpecLoc(),
13497 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13498 : diag::warn_deprecated_register)
13499 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13500 }
13501 } else if (getLangOpts().CPlusPlus &&
13502 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13503 SC = SC_Auto;
13504 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13505 Diag(DS.getStorageClassSpecLoc(),
13506 diag::err_invalid_storage_class_in_func_decl);
13507 D.getMutableDeclSpec().ClearStorageClassSpecs();
13508 }
13509
13510 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13511 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13512 << DeclSpec::getSpecifierName(TSCS);
13513 if (DS.isInlineSpecified())
13514 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13515 << getLangOpts().CPlusPlus17;
13516 if (DS.hasConstexprSpecifier())
13517 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13518 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13519
13520 DiagnoseFunctionSpecifiers(DS);
13521
13522 CheckFunctionOrTemplateParamDeclarator(S, D);
13523
13524 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13525 QualType parmDeclType = TInfo->getType();
13526
13527 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13528 IdentifierInfo *II = D.getIdentifier();
13529 if (II) {
13530 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13531 ForVisibleRedeclaration);
13532 LookupName(R, S);
13533 if (R.isSingleResult()) {
13534 NamedDecl *PrevDecl = R.getFoundDecl();
13535 if (PrevDecl->isTemplateParameter()) {
13536 // Maybe we will complain about the shadowed template parameter.
13537 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13538 // Just pretend that we didn't see the previous declaration.
13539 PrevDecl = nullptr;
13540 } else if (S->isDeclScope(PrevDecl)) {
13541 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13542 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13543
13544 // Recover by removing the name
13545 II = nullptr;
13546 D.SetIdentifier(nullptr, D.getIdentifierLoc());
13547 D.setInvalidType(true);
13548 }
13549 }
13550 }
13551
13552 // Temporarily put parameter variables in the translation unit, not
13553 // the enclosing context. This prevents them from accidentally
13554 // looking like class members in C++.
13555 ParmVarDecl *New =
13556 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13557 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13558
13559 if (D.isInvalidType())
13560 New->setInvalidDecl();
13561
13562 assert(S->isFunctionPrototypeScope())((S->isFunctionPrototypeScope()) ? static_cast<void>
(0) : __assert_fail ("S->isFunctionPrototypeScope()", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 13562, __PRETTY_FUNCTION__))
;
13563 assert(S->getFunctionPrototypeDepth() >= 1)((S->getFunctionPrototypeDepth() >= 1) ? static_cast<
void> (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 13563, __PRETTY_FUNCTION__))
;
13564 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13565 S->getNextFunctionPrototypeIndex());
13566
13567 // Add the parameter declaration into this scope.
13568 S->AddDecl(New);
13569 if (II)
13570 IdResolver.AddDecl(New);
13571
13572 ProcessDeclAttributes(S, New, D);
13573
13574 if (D.getDeclSpec().isModulePrivateSpecified())
13575 Diag(New->getLocation(), diag::err_module_private_local)
13576 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13577 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13578
13579 if (New->hasAttr<BlocksAttr>()) {
13580 Diag(New->getLocation(), diag::err_block_on_nonlocal);
13581 }
13582
13583 if (getLangOpts().OpenCL)
13584 deduceOpenCLAddressSpace(New);
13585
13586 return New;
13587}
13588
13589/// Synthesizes a variable for a parameter arising from a
13590/// typedef.
13591ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13592 SourceLocation Loc,
13593 QualType T) {
13594 /* FIXME: setting StartLoc == Loc.
13595 Would it be worth to modify callers so as to provide proper source
13596 location for the unnamed parameters, embedding the parameter's type? */
13597 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13598 T, Context.getTrivialTypeSourceInfo(T, Loc),
13599 SC_None, nullptr);
13600 Param->setImplicit();
13601 return Param;
13602}
13603
13604void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13605 // Don't diagnose unused-parameter errors in template instantiations; we
13606 // will already have done so in the template itself.
13607 if (inTemplateInstantiation())
13608 return;
13609
13610 for (const ParmVarDecl *Parameter : Parameters) {
13611 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13612 !Parameter->hasAttr<UnusedAttr>()) {
13613 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13614 << Parameter->getDeclName();
13615 }
13616 }
13617}
13618
13619void Sema::DiagnoseSizeOfParametersAndReturnValue(
13620 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13621 if (LangOpts.NumLargeByValueCopy == 0) // No check.
13622 return;
13623
13624 // Warn if the return value is pass-by-value and larger than the specified
13625 // threshold.
13626 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13627 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13628 if (Size > LangOpts.NumLargeByValueCopy)
13629 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13630 }
13631
13632 // Warn if any parameter is pass-by-value and larger than the specified
13633 // threshold.
13634 for (const ParmVarDecl *Parameter : Parameters) {
13635 QualType T = Parameter->getType();
13636 if (T->isDependentType() || !T.isPODType(Context))
13637 continue;
13638 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13639 if (Size > LangOpts.NumLargeByValueCopy)
13640 Diag(Parameter->getLocation(), diag::warn_parameter_size)
13641 << Parameter << Size;
13642 }
13643}
13644
13645ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13646 SourceLocation NameLoc, IdentifierInfo *Name,
13647 QualType T, TypeSourceInfo *TSInfo,
13648 StorageClass SC) {
13649 // In ARC, infer a lifetime qualifier for appropriate parameter types.
13650 if (getLangOpts().ObjCAutoRefCount &&
13651 T.getObjCLifetime() == Qualifiers::OCL_None &&
13652 T->isObjCLifetimeType()) {
13653
13654 Qualifiers::ObjCLifetime lifetime;
13655
13656 // Special cases for arrays:
13657 // - if it's const, use __unsafe_unretained
13658 // - otherwise, it's an error
13659 if (T->isArrayType()) {
13660 if (!T.isConstQualified()) {
13661 if (DelayedDiagnostics.shouldDelayDiagnostics())
13662 DelayedDiagnostics.add(
13663 sema::DelayedDiagnostic::makeForbiddenType(
13664 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13665 else
13666 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13667 << TSInfo->getTypeLoc().getSourceRange();
13668 }
13669 lifetime = Qualifiers::OCL_ExplicitNone;
13670 } else {
13671 lifetime = T->getObjCARCImplicitLifetime();
13672 }
13673 T = Context.getLifetimeQualifiedType(T, lifetime);
13674 }
13675
13676 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13677 Context.getAdjustedParameterType(T),
13678 TSInfo, SC, nullptr);
13679
13680 // Make a note if we created a new pack in the scope of a lambda, so that
13681 // we know that references to that pack must also be expanded within the
13682 // lambda scope.
13683 if (New->isParameterPack())
13684 if (auto *LSI = getEnclosingLambda())
13685 LSI->LocalPacks.push_back(New);
13686
13687 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13688 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13689 checkNonTrivialCUnion(New->getType(), New->getLocation(),
13690 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13691
13692 // Parameters can not be abstract class types.
13693 // For record types, this is done by the AbstractClassUsageDiagnoser once
13694 // the class has been completely parsed.
13695 if (!CurContext->isRecord() &&
13696 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13697 AbstractParamType))
13698 New->setInvalidDecl();
13699
13700 // Parameter declarators cannot be interface types. All ObjC objects are
13701 // passed by reference.
13702 if (T->isObjCObjectType()) {
13703 SourceLocation TypeEndLoc =
13704 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13705 Diag(NameLoc,
13706 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13707 << FixItHint::CreateInsertion(TypeEndLoc, "*");
13708 T = Context.getObjCObjectPointerType(T);
13709 New->setType(T);
13710 }
13711
13712 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13713 // duration shall not be qualified by an address-space qualifier."
13714 // Since all parameters have automatic store duration, they can not have
13715 // an address space.
13716 if (T.getAddressSpace() != LangAS::Default &&
13717 // OpenCL allows function arguments declared to be an array of a type
13718 // to be qualified with an address space.
13719 !(getLangOpts().OpenCL &&
13720 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13721 Diag(NameLoc, diag::err_arg_with_address_space);
13722 New->setInvalidDecl();
13723 }
13724
13725 // PPC MMA non-pointer types are not allowed as function argument types.
13726 if (Context.getTargetInfo().getTriple().isPPC64() &&
13727 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13728 New->setInvalidDecl();
13729 }
13730
13731 return New;
13732}
13733
13734void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13735 SourceLocation LocAfterDecls) {
13736 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13737
13738 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13739 // for a K&R function.
13740 if (!FTI.hasPrototype) {
13741 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13742 --i;
13743 if (FTI.Params[i].Param == nullptr) {
13744 SmallString<256> Code;
13745 llvm::raw_svector_ostream(Code)
13746 << " int " << FTI.Params[i].Ident->getName() << ";\n";
13747 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13748 << FTI.Params[i].Ident
13749 << FixItHint::CreateInsertion(LocAfterDecls, Code);
13750
13751 // Implicitly declare the argument as type 'int' for lack of a better
13752 // type.
13753 AttributeFactory attrs;
13754 DeclSpec DS(attrs);
13755 const char* PrevSpec; // unused
13756 unsigned DiagID; // unused
13757 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13758 DiagID, Context.getPrintingPolicy());
13759 // Use the identifier location for the type source range.
13760 DS.SetRangeStart(FTI.Params[i].IdentLoc);
13761 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13762 Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
13763 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13764 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13765 }
13766 }
13767 }
13768}
13769
13770Decl *
13771Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13772 MultiTemplateParamsArg TemplateParameterLists,
13773 SkipBodyInfo *SkipBody) {
13774 assert(getCurFunctionDecl() == nullptr && "Function parsing confused")((getCurFunctionDecl() == nullptr && "Function parsing confused"
) ? static_cast<void> (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 13774, __PRETTY_FUNCTION__))
;
13775 assert(D.isFunctionDeclarator() && "Not a function declarator!")((D.isFunctionDeclarator() && "Not a function declarator!"
) ? static_cast<void> (0) : __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 13775, __PRETTY_FUNCTION__))
;
13776 Scope *ParentScope = FnBodyScope->getParent();
13777
13778 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13779 // we define a non-templated function definition, we will create a declaration
13780 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13781 // The base function declaration will have the equivalent of an `omp declare
13782 // variant` annotation which specifies the mangled definition as a
13783 // specialization function under the OpenMP context defined as part of the
13784 // `omp begin declare variant`.
13785 SmallVector<FunctionDecl *, 4> Bases;
13786 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
13787 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13788 ParentScope, D, TemplateParameterLists, Bases);
13789
13790 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
13791 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13792 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13793
13794 if (!Bases.empty())
13795 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
13796
13797 return Dcl;
13798}
13799
13800void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13801 Consumer.HandleInlineFunctionDefinition(D);
13802}
13803
13804static bool
13805ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13806 const FunctionDecl *&PossiblePrototype) {
13807 // Don't warn about invalid declarations.
13808 if (FD->isInvalidDecl())
13809 return false;
13810
13811 // Or declarations that aren't global.
13812 if (!FD->isGlobal())
13813 return false;
13814
13815 // Don't warn about C++ member functions.
13816 if (isa<CXXMethodDecl>(FD))
13817 return false;
13818
13819 // Don't warn about 'main'.
13820 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13821 if (IdentifierInfo *II = FD->getIdentifier())
13822 if (II->isStr("main"))
13823 return false;
13824
13825 // Don't warn about inline functions.
13826 if (FD->isInlined())
13827 return false;
13828
13829 // Don't warn about function templates.
13830 if (FD->getDescribedFunctionTemplate())
13831 return false;
13832
13833 // Don't warn about function template specializations.
13834 if (FD->isFunctionTemplateSpecialization())
13835 return false;
13836
13837 // Don't warn for OpenCL kernels.
13838 if (FD->hasAttr<OpenCLKernelAttr>())
13839 return false;
13840
13841 // Don't warn on explicitly deleted functions.
13842 if (FD->isDeleted())
13843 return false;
13844
13845 for (const FunctionDecl *Prev = FD->getPreviousDecl();
13846 Prev; Prev = Prev->getPreviousDecl()) {
13847 // Ignore any declarations that occur in function or method
13848 // scope, because they aren't visible from the header.
13849 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13850 continue;
13851
13852 PossiblePrototype = Prev;
13853 return Prev->getType()->isFunctionNoProtoType();
13854 }
13855
13856 return true;
13857}
13858
13859void
13860Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13861 const FunctionDecl *EffectiveDefinition,
13862 SkipBodyInfo *SkipBody) {
13863 const FunctionDecl *Definition = EffectiveDefinition;
13864 if (!Definition &&
13865 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
13866 return;
13867
13868 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
13869 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
13870 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13871 // A merged copy of the same function, instantiated as a member of
13872 // the same class, is OK.
13873 if (declaresSameEntity(OrigFD, OrigDef) &&
13874 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
13875 cast<Decl>(FD->getLexicalDeclContext())))
13876 return;
13877 }
13878 }
13879 }
13880
13881 if (canRedefineFunction(Definition, getLangOpts()))
13882 return;
13883
13884 // Don't emit an error when this is redefinition of a typo-corrected
13885 // definition.
13886 if (TypoCorrectedFunctionDefinitions.count(Definition))
13887 return;
13888
13889 // If we don't have a visible definition of the function, and it's inline or
13890 // a template, skip the new definition.
13891 if (SkipBody && !hasVisibleDefinition(Definition) &&
13892 (Definition->getFormalLinkage() == InternalLinkage ||
13893 Definition->isInlined() ||
13894 Definition->getDescribedFunctionTemplate() ||
13895 Definition->getNumTemplateParameterLists())) {
13896 SkipBody->ShouldSkip = true;
13897 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13898 if (auto *TD = Definition->getDescribedFunctionTemplate())
13899 makeMergedDefinitionVisible(TD);
13900 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13901 return;
13902 }
13903
13904 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13905 Definition->getStorageClass() == SC_Extern)
13906 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13907 << FD << getLangOpts().CPlusPlus;
13908 else
13909 Diag(FD->getLocation(), diag::err_redefinition) << FD;
13910
13911 Diag(Definition->getLocation(), diag::note_previous_definition);
13912 FD->setInvalidDecl();
13913}
13914
13915static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13916 Sema &S) {
13917 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13918
13919 LambdaScopeInfo *LSI = S.PushLambdaScope();
13920 LSI->CallOperator = CallOperator;
13921 LSI->Lambda = LambdaClass;
13922 LSI->ReturnType = CallOperator->getReturnType();
13923 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13924
13925 if (LCD == LCD_None)
13926 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13927 else if (LCD == LCD_ByCopy)
13928 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13929 else if (LCD == LCD_ByRef)
13930 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13931 DeclarationNameInfo DNI = CallOperator->getNameInfo();
13932
13933 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13934 LSI->Mutable = !CallOperator->isConst();
13935
13936 // Add the captures to the LSI so they can be noted as already
13937 // captured within tryCaptureVar.
13938 auto I = LambdaClass->field_begin();
13939 for (const auto &C : LambdaClass->captures()) {
13940 if (C.capturesVariable()) {
13941 VarDecl *VD = C.getCapturedVar();
13942 if (VD->isInitCapture())
13943 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13944 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13945 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13946 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13947 /*EllipsisLoc*/C.isPackExpansion()
13948 ? C.getEllipsisLoc() : SourceLocation(),
13949 I->getType(), /*Invalid*/false);
13950
13951 } else if (C.capturesThis()) {
13952 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13953 C.getCaptureKind() == LCK_StarThis);
13954 } else {
13955 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13956 I->getType());
13957 }
13958 ++I;
13959 }
13960}
13961
13962Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13963 SkipBodyInfo *SkipBody) {
13964 if (!D) {
13965 // Parsing the function declaration failed in some way. Push on a fake scope
13966 // anyway so we can try to parse the function body.
13967 PushFunctionScope();
13968 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13969 return D;
13970 }
13971
13972 FunctionDecl *FD = nullptr;
13973
13974 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13975 FD = FunTmpl->getTemplatedDecl();
13976 else
13977 FD = cast<FunctionDecl>(D);
13978
13979 // Do not push if it is a lambda because one is already pushed when building
13980 // the lambda in ActOnStartOfLambdaDefinition().
13981 if (!isLambdaCallOperator(FD))
13982 PushExpressionEvaluationContext(
13983 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
13984 : ExprEvalContexts.back().Context);
13985
13986 // Check for defining attributes before the check for redefinition.
13987 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13988 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13989 FD->dropAttr<AliasAttr>();
13990 FD->setInvalidDecl();
13991 }
13992 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13993 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13994 FD->dropAttr<IFuncAttr>();
13995 FD->setInvalidDecl();
13996 }
13997
13998 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
13999 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14000 Ctor->isDefaultConstructor() &&
14001 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14002 // If this is an MS ABI dllexport default constructor, instantiate any
14003 // default arguments.
14004 InstantiateDefaultCtorDefaultArgs(Ctor);
14005 }
14006 }
14007
14008 // See if this is a redefinition. If 'will have body' (or similar) is already
14009 // set, then these checks were already performed when it was set.
14010 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14011 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14012 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14013
14014 // If we're skipping the body, we're done. Don't enter the scope.
14015 if (SkipBody && SkipBody->ShouldSkip)
14016 return D;
14017 }
14018
14019 // Mark this function as "will have a body eventually". This lets users to
14020 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14021 // this function.
14022 FD->setWillHaveBody();
14023
14024 // If we are instantiating a generic lambda call operator, push
14025 // a LambdaScopeInfo onto the function stack. But use the information
14026 // that's already been calculated (ActOnLambdaExpr) to prime the current
14027 // LambdaScopeInfo.
14028 // When the template operator is being specialized, the LambdaScopeInfo,
14029 // has to be properly restored so that tryCaptureVariable doesn't try
14030 // and capture any new variables. In addition when calculating potential
14031 // captures during transformation of nested lambdas, it is necessary to
14032 // have the LSI properly restored.
14033 if (isGenericLambdaCallOperatorSpecialization(FD)) {
14034 assert(inTemplateInstantiation() &&((inTemplateInstantiation() && "There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? static_cast<void
> (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14036, __PRETTY_FUNCTION__))
14035 "There should be an active template instantiation on the stack "((inTemplateInstantiation() && "There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? static_cast<void
> (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14036, __PRETTY_FUNCTION__))
14036 "when instantiating a generic lambda!")((inTemplateInstantiation() && "There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? static_cast<void
> (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14036, __PRETTY_FUNCTION__))
;
14037 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14038 } else {
14039 // Enter a new function scope
14040 PushFunctionScope();
14041 }
14042
14043 // Builtin functions cannot be defined.
14044 if (unsigned BuiltinID = FD->getBuiltinID()) {
14045 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14046 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14047 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14048 FD->setInvalidDecl();
14049 }
14050 }
14051
14052 // The return type of a function definition must be complete
14053 // (C99 6.9.1p3, C++ [dcl.fct]p6).
14054 QualType ResultType = FD->getReturnType();
14055 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14056 !FD->isInvalidDecl() &&
14057 RequireCompleteType(FD->getLocation(), ResultType,
14058 diag::err_func_def_incomplete_result))
14059 FD->setInvalidDecl();
14060
14061 if (FnBodyScope)
14062 PushDeclContext(FnBodyScope, FD);
14063
14064 // Check the validity of our function parameters
14065 CheckParmsForFunctionDef(FD->parameters(),
14066 /*CheckParameterNames=*/true);
14067
14068 // Add non-parameter declarations already in the function to the current
14069 // scope.
14070 if (FnBodyScope) {
14071 for (Decl *NPD : FD->decls()) {
14072 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14073 if (!NonParmDecl)
14074 continue;
14075 assert(!isa<ParmVarDecl>(NonParmDecl) &&((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14076, __PRETTY_FUNCTION__))
14076 "parameters should not be in newly created FD yet")((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14076, __PRETTY_FUNCTION__))
;
14077
14078 // If the decl has a name, make it accessible in the current scope.
14079 if (NonParmDecl->getDeclName())
14080 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14081
14082 // Similarly, dive into enums and fish their constants out, making them
14083 // accessible in this scope.
14084 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14085 for (auto *EI : ED->enumerators())
14086 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14087 }
14088 }
14089 }
14090
14091 // Introduce our parameters into the function scope
14092 for (auto Param : FD->parameters()) {
14093 Param->setOwningFunction(FD);
14094
14095 // If this has an identifier, add it to the scope stack.
14096 if (Param->getIdentifier() && FnBodyScope) {
14097 CheckShadow(FnBodyScope, Param);
14098
14099 PushOnScopeChains(Param, FnBodyScope);
14100 }
14101 }
14102
14103 // Ensure that the function's exception specification is instantiated.
14104 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14105 ResolveExceptionSpec(D->getLocation(), FPT);
14106
14107 // dllimport cannot be applied to non-inline function definitions.
14108 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14109 !FD->isTemplateInstantiation()) {
14110 assert(!FD->hasAttr<DLLExportAttr>())((!FD->hasAttr<DLLExportAttr>()) ? static_cast<void
> (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14110, __PRETTY_FUNCTION__))
;
14111 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14112 FD->setInvalidDecl();
14113 return D;
14114 }
14115 // We want to attach documentation to original Decl (which might be
14116 // a function template).
14117 ActOnDocumentableDecl(D);
14118 if (getCurLexicalContext()->isObjCContainer() &&
14119 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14120 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14121 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14122
14123 return D;
14124}
14125
14126/// Given the set of return statements within a function body,
14127/// compute the variables that are subject to the named return value
14128/// optimization.
14129///
14130/// Each of the variables that is subject to the named return value
14131/// optimization will be marked as NRVO variables in the AST, and any
14132/// return statement that has a marked NRVO variable as its NRVO candidate can
14133/// use the named return value optimization.
14134///
14135/// This function applies a very simplistic algorithm for NRVO: if every return
14136/// statement in the scope of a variable has the same NRVO candidate, that
14137/// candidate is an NRVO variable.
14138void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14139 ReturnStmt **Returns = Scope->Returns.data();
14140
14141 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14142 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14143 if (!NRVOCandidate->isNRVOVariable())
14144 Returns[I]->setNRVOCandidate(nullptr);
14145 }
14146 }
14147}
14148
14149bool Sema::canDelayFunctionBody(const Declarator &D) {
14150 // We can't delay parsing the body of a constexpr function template (yet).
14151 if (D.getDeclSpec().hasConstexprSpecifier())
14152 return false;
14153
14154 // We can't delay parsing the body of a function template with a deduced
14155 // return type (yet).
14156 if (D.getDeclSpec().hasAutoTypeSpec()) {
14157 // If the placeholder introduces a non-deduced trailing return type,
14158 // we can still delay parsing it.
14159 if (D.getNumTypeObjects()) {
14160 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14161 if (Outer.Kind == DeclaratorChunk::Function &&
14162 Outer.Fun.hasTrailingReturnType()) {
14163 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14164 return Ty.isNull() || !Ty->isUndeducedType();
14165 }
14166 }
14167 return false;
14168 }
14169
14170 return true;
14171}
14172
14173bool Sema::canSkipFunctionBody(Decl *D) {
14174 // We cannot skip the body of a function (or function template) which is
14175 // constexpr, since we may need to evaluate its body in order to parse the
14176 // rest of the file.
14177 // We cannot skip the body of a function with an undeduced return type,
14178 // because any callers of that function need to know the type.
14179 if (const FunctionDecl *FD = D->getAsFunction()) {
14180 if (FD->isConstexpr())
14181 return false;
14182 // We can't simply call Type::isUndeducedType here, because inside template
14183 // auto can be deduced to a dependent type, which is not considered
14184 // "undeduced".
14185 if (FD->getReturnType()->getContainedDeducedType())
14186 return false;
14187 }
14188 return Consumer.shouldSkipFunctionBody(D);
14189}
14190
14191Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14192 if (!Decl)
14193 return nullptr;
14194 if (FunctionDecl *FD = Decl->getAsFunction())
14195 FD->setHasSkippedBody();
14196 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14197 MD->setHasSkippedBody();
14198 return Decl;
14199}
14200
14201Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14202 return ActOnFinishFunctionBody(D, BodyArg, false);
14203}
14204
14205/// RAII object that pops an ExpressionEvaluationContext when exiting a function
14206/// body.
14207class ExitFunctionBodyRAII {
14208public:
14209 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14210 ~ExitFunctionBodyRAII() {
14211 if (!IsLambda)
14212 S.PopExpressionEvaluationContext();
14213 }
14214
14215private:
14216 Sema &S;
14217 bool IsLambda = false;
14218};
14219
14220static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14221 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14222
14223 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14224 if (EscapeInfo.count(BD))
14225 return EscapeInfo[BD];
14226
14227 bool R = false;
14228 const BlockDecl *CurBD = BD;
14229
14230 do {
14231 R = !CurBD->doesNotEscape();
14232 if (R)
14233 break;
14234 CurBD = CurBD->getParent()->getInnermostBlockDecl();
14235 } while (CurBD);
14236
14237 return EscapeInfo[BD] = R;
14238 };
14239
14240 // If the location where 'self' is implicitly retained is inside a escaping
14241 // block, emit a diagnostic.
14242 for (const std::pair<SourceLocation, const BlockDecl *> &P :
14243 S.ImplicitlyRetainedSelfLocs)
14244 if (IsOrNestedInEscapingBlock(P.second))
14245 S.Diag(P.first, diag::warn_implicitly_retains_self)
14246 << FixItHint::CreateInsertion(P.first, "self->");
14247}
14248
14249Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14250 bool IsInstantiation) {
14251 FunctionScopeInfo *FSI = getCurFunction();
14252 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14253
14254 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>())
14255 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14256
14257 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14258 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14259
14260 if (getLangOpts().Coroutines && FSI->isCoroutine())
14261 CheckCompletedCoroutineBody(FD, Body);
14262
14263 // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14264 // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14265 // meant to pop the context added in ActOnStartOfFunctionDef().
14266 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14267
14268 if (FD) {
14269 FD->setBody(Body);
14270 FD->setWillHaveBody(false);
14271
14272 if (getLangOpts().CPlusPlus14) {
14273 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14274 FD->getReturnType()->isUndeducedType()) {
14275 // If the function has a deduced result type but contains no 'return'
14276 // statements, the result type as written must be exactly 'auto', and
14277 // the deduced result type is 'void'.
14278 if (!FD->getReturnType()->getAs<AutoType>()) {
14279 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14280 << FD->getReturnType();
14281 FD->setInvalidDecl();
14282 } else {
14283 // Substitute 'void' for the 'auto' in the type.
14284 TypeLoc ResultType = getReturnTypeLoc(FD);
14285 Context.adjustDeducedFunctionResultType(
14286 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14287 }
14288 }
14289 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14290 // In C++11, we don't use 'auto' deduction rules for lambda call
14291 // operators because we don't support return type deduction.
14292 auto *LSI = getCurLambda();
14293 if (LSI->HasImplicitReturnType) {
14294 deduceClosureReturnType(*LSI);
14295
14296 // C++11 [expr.prim.lambda]p4:
14297 // [...] if there are no return statements in the compound-statement
14298 // [the deduced type is] the type void
14299 QualType RetType =
14300 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14301
14302 // Update the return type to the deduced type.
14303 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14304 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14305 Proto->getExtProtoInfo()));
14306 }
14307 }
14308
14309 // If the function implicitly returns zero (like 'main') or is naked,
14310 // don't complain about missing return statements.
14311 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14312 WP.disableCheckFallThrough();
14313
14314 // MSVC permits the use of pure specifier (=0) on function definition,
14315 // defined at class scope, warn about this non-standard construct.
14316 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14317 Diag(FD->getLocation(), diag::ext_pure_function_definition);
14318
14319 if (!FD->isInvalidDecl()) {
14320 // Don't diagnose unused parameters of defaulted or deleted functions.
14321 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14322 DiagnoseUnusedParameters(FD->parameters());
14323 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14324 FD->getReturnType(), FD);
14325
14326 // If this is a structor, we need a vtable.
14327 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14328 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14329 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14330 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14331
14332 // Try to apply the named return value optimization. We have to check
14333 // if we can do this here because lambdas keep return statements around
14334 // to deduce an implicit return type.
14335 if (FD->getReturnType()->isRecordType() &&
14336 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14337 computeNRVO(Body, FSI);
14338 }
14339
14340 // GNU warning -Wmissing-prototypes:
14341 // Warn if a global function is defined without a previous
14342 // prototype declaration. This warning is issued even if the
14343 // definition itself provides a prototype. The aim is to detect
14344 // global functions that fail to be declared in header files.
14345 const FunctionDecl *PossiblePrototype = nullptr;
14346 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14347 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14348
14349 if (PossiblePrototype) {
14350 // We found a declaration that is not a prototype,
14351 // but that could be a zero-parameter prototype
14352 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14353 TypeLoc TL = TI->getTypeLoc();
14354 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14355 Diag(PossiblePrototype->getLocation(),
14356 diag::note_declaration_not_a_prototype)
14357 << (FD->getNumParams() != 0)
14358 << (FD->getNumParams() == 0
14359 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14360 : FixItHint{});
14361 }
14362 } else {
14363 // Returns true if the token beginning at this Loc is `const`.
14364 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14365 const LangOptions &LangOpts) {
14366 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14367 if (LocInfo.first.isInvalid())
14368 return false;
14369
14370 bool Invalid = false;
14371 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14372 if (Invalid)
14373 return false;
14374
14375 if (LocInfo.second > Buffer.size())
14376 return false;
14377
14378 const char *LexStart = Buffer.data() + LocInfo.second;
14379 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14380
14381 return StartTok.consume_front("const") &&
14382 (StartTok.empty() || isWhitespace(StartTok[0]) ||
14383 StartTok.startswith("/*") || StartTok.startswith("//"));
14384 };
14385
14386 auto findBeginLoc = [&]() {
14387 // If the return type has `const` qualifier, we want to insert
14388 // `static` before `const` (and not before the typename).
14389 if ((FD->getReturnType()->isAnyPointerType() &&
14390 FD->getReturnType()->getPointeeType().isConstQualified()) ||
14391 FD->getReturnType().isConstQualified()) {
14392 // But only do this if we can determine where the `const` is.
14393
14394 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14395 getLangOpts()))
14396
14397 return FD->getBeginLoc();
14398 }
14399 return FD->getTypeSpecStartLoc();
14400 };
14401 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14402 << /* function */ 1
14403 << (FD->getStorageClass() == SC_None
14404 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14405 : FixItHint{});
14406 }
14407
14408 // GNU warning -Wstrict-prototypes
14409 // Warn if K&R function is defined without a previous declaration.
14410 // This warning is issued only if the definition itself does not provide
14411 // a prototype. Only K&R definitions do not provide a prototype.
14412 if (!FD->hasWrittenPrototype()) {
14413 TypeSourceInfo *TI = FD->getTypeSourceInfo();
14414 TypeLoc TL = TI->getTypeLoc();
14415 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14416 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14417 }
14418 }
14419
14420 // Warn on CPUDispatch with an actual body.
14421 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14422 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14423 if (!CmpndBody->body_empty())
14424 Diag(CmpndBody->body_front()->getBeginLoc(),
14425 diag::warn_dispatch_body_ignored);
14426
14427 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14428 const CXXMethodDecl *KeyFunction;
14429 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14430 MD->isVirtual() &&
14431 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14432 MD == KeyFunction->getCanonicalDecl()) {
14433 // Update the key-function state if necessary for this ABI.
14434 if (FD->isInlined() &&
14435 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14436 Context.setNonKeyFunction(MD);
14437
14438 // If the newly-chosen key function is already defined, then we
14439 // need to mark the vtable as used retroactively.
14440 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14441 const FunctionDecl *Definition;
14442 if (KeyFunction && KeyFunction->isDefined(Definition))
14443 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14444 } else {
14445 // We just defined they key function; mark the vtable as used.
14446 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14447 }
14448 }
14449 }
14450
14451 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator
== FD) && "Function parsing confused") ? static_cast
<void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14452, __PRETTY_FUNCTION__))
14452 "Function parsing confused")(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator
== FD) && "Function parsing confused") ? static_cast
<void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14452, __PRETTY_FUNCTION__))
;
14453 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14454 assert(MD == getCurMethodDecl() && "Method parsing confused")((MD == getCurMethodDecl() && "Method parsing confused"
) ? static_cast<void> (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14454, __PRETTY_FUNCTION__))
;
14455 MD->setBody(Body);
14456 if (!MD->isInvalidDecl()) {
14457 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14458 MD->getReturnType(), MD);
14459
14460 if (Body)
14461 computeNRVO(Body, FSI);
14462 }
14463 if (FSI->ObjCShouldCallSuper) {
14464 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14465 << MD->getSelector().getAsString();
14466 FSI->ObjCShouldCallSuper = false;
14467 }
14468 if (FSI->ObjCWarnForNoDesignatedInitChain) {
14469 const ObjCMethodDecl *InitMethod = nullptr;
14470 bool isDesignated =
14471 MD->isDesignatedInitializerForTheInterface(&InitMethod);
14472 assert(isDesignated && InitMethod)((isDesignated && InitMethod) ? static_cast<void>
(0) : __assert_fail ("isDesignated && InitMethod", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14472, __PRETTY_FUNCTION__))
;
14473 (void)isDesignated;
14474
14475 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14476 auto IFace = MD->getClassInterface();
14477 if (!IFace)
14478 return false;
14479 auto SuperD = IFace->getSuperClass();
14480 if (!SuperD)
14481 return false;
14482 return SuperD->getIdentifier() ==
14483 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14484 };
14485 // Don't issue this warning for unavailable inits or direct subclasses
14486 // of NSObject.
14487 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14488 Diag(MD->getLocation(),
14489 diag::warn_objc_designated_init_missing_super_call);
14490 Diag(InitMethod->getLocation(),
14491 diag::note_objc_designated_init_marked_here);
14492 }
14493 FSI->ObjCWarnForNoDesignatedInitChain = false;
14494 }
14495 if (FSI->ObjCWarnForNoInitDelegation) {
14496 // Don't issue this warning for unavaialable inits.
14497 if (!MD->isUnavailable())
14498 Diag(MD->getLocation(),
14499 diag::warn_objc_secondary_init_missing_init_call);
14500 FSI->ObjCWarnForNoInitDelegation = false;
14501 }
14502
14503 diagnoseImplicitlyRetainedSelf(*this);
14504 } else {
14505 // Parsing the function declaration failed in some way. Pop the fake scope
14506 // we pushed on.
14507 PopFunctionScopeInfo(ActivePolicy, dcl);
14508 return nullptr;
14509 }
14510
14511 if (Body && FSI->HasPotentialAvailabilityViolations)
14512 DiagnoseUnguardedAvailabilityViolations(dcl);
14513
14514 assert(!FSI->ObjCShouldCallSuper &&((!FSI->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<void> (0)
: __assert_fail ("!FSI->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14516, __PRETTY_FUNCTION__))
14515 "This should only be set for ObjC methods, which should have been "((!FSI->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<void> (0)
: __assert_fail ("!FSI->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14516, __PRETTY_FUNCTION__))
14516 "handled in the block above.")((!FSI->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<void> (0)
: __assert_fail ("!FSI->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14516, __PRETTY_FUNCTION__))
;
14517
14518 // Verify and clean out per-function state.
14519 if (Body && (!FD || !FD->isDefaulted())) {
14520 // C++ constructors that have function-try-blocks can't have return
14521 // statements in the handlers of that block. (C++ [except.handle]p14)
14522 // Verify this.
14523 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14524 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14525
14526 // Verify that gotos and switch cases don't jump into scopes illegally.
14527 if (FSI->NeedsScopeChecking() &&
14528 !PP.isCodeCompletionEnabled())
14529 DiagnoseInvalidJumps(Body);
14530
14531 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14532 if (!Destructor->getParent()->isDependentType())
14533 CheckDestructor(Destructor);
14534
14535 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14536 Destructor->getParent());
14537 }
14538
14539 // If any errors have occurred, clear out any temporaries that may have
14540 // been leftover. This ensures that these temporaries won't be picked up for
14541 // deletion in some later function.
14542 if (hasUncompilableErrorOccurred() ||
14543 getDiagnostics().getSuppressAllDiagnostics()) {
14544 DiscardCleanupsInEvaluationContext();
14545 }
14546 if (!hasUncompilableErrorOccurred() &&
14547 !isa<FunctionTemplateDecl>(dcl)) {
14548 // Since the body is valid, issue any analysis-based warnings that are
14549 // enabled.
14550 ActivePolicy = &WP;
14551 }
14552
14553 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14554 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14555 FD->setInvalidDecl();
14556
14557 if (FD && FD->hasAttr<NakedAttr>()) {
14558 for (const Stmt *S : Body->children()) {
14559 // Allow local register variables without initializer as they don't
14560 // require prologue.
14561 bool RegisterVariables = false;
14562 if (auto *DS = dyn_cast<DeclStmt>(S)) {
14563 for (const auto *Decl : DS->decls()) {
14564 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14565 RegisterVariables =
14566 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14567 if (!RegisterVariables)
14568 break;
14569 }
14570 }
14571 }
14572 if (RegisterVariables)
14573 continue;
14574 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14575 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14576 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14577 FD->setInvalidDecl();
14578 break;
14579 }
14580 }
14581 }
14582
14583 assert(ExprCleanupObjects.size() ==((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
&& "Leftover temporaries in function") ? static_cast
<void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14585, __PRETTY_FUNCTION__))
14584 ExprEvalContexts.back().NumCleanupObjects &&((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
&& "Leftover temporaries in function") ? static_cast
<void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14585, __PRETTY_FUNCTION__))
14585 "Leftover temporaries in function")((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
&& "Leftover temporaries in function") ? static_cast
<void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14585, __PRETTY_FUNCTION__))
;
14586 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function")((!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14586, __PRETTY_FUNCTION__))
;
14587 assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking"
) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14588, __PRETTY_FUNCTION__))
14588 "Leftover expressions for odr-use checking")((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking"
) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14588, __PRETTY_FUNCTION__))
;
14589 }
14590
14591 if (!IsInstantiation)
14592 PopDeclContext();
14593
14594 PopFunctionScopeInfo(ActivePolicy, dcl);
14595 // If any errors have occurred, clear out any temporaries that may have
14596 // been leftover. This ensures that these temporaries won't be picked up for
14597 // deletion in some later function.
14598 if (hasUncompilableErrorOccurred()) {
14599 DiscardCleanupsInEvaluationContext();
14600 }
14601
14602 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14603 auto ES = getEmissionStatus(FD);
14604 if (ES == Sema::FunctionEmissionStatus::Emitted ||
14605 ES == Sema::FunctionEmissionStatus::Unknown)
14606 DeclsToCheckForDeferredDiags.push_back(FD);
14607 }
14608
14609 return dcl;
14610}
14611
14612/// When we finish delayed parsing of an attribute, we must attach it to the
14613/// relevant Decl.
14614void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14615 ParsedAttributes &Attrs) {
14616 // Always attach attributes to the underlying decl.
14617 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14618 D = TD->getTemplatedDecl();
14619 ProcessDeclAttributeList(S, D, Attrs);
14620
14621 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14622 if (Method->isStatic())
14623 checkThisInStaticMemberFunctionAttributes(Method);
14624}
14625
14626/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14627/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14628NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14629 IdentifierInfo &II, Scope *S) {
14630 // Find the scope in which the identifier is injected and the corresponding
14631 // DeclContext.
14632 // FIXME: C89 does not say what happens if there is no enclosing block scope.
14633 // In that case, we inject the declaration into the translation unit scope
14634 // instead.
14635 Scope *BlockScope = S;
14636 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14637 BlockScope = BlockScope->getParent();
14638
14639 Scope *ContextScope = BlockScope;
14640 while (!ContextScope->getEntity())
14641 ContextScope = ContextScope->getParent();
14642 ContextRAII SavedContext(*this, ContextScope->getEntity());
14643
14644 // Before we produce a declaration for an implicitly defined
14645 // function, see whether there was a locally-scoped declaration of
14646 // this name as a function or variable. If so, use that
14647 // (non-visible) declaration, and complain about it.
14648 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14649 if (ExternCPrev) {
14650 // We still need to inject the function into the enclosing block scope so
14651 // that later (non-call) uses can see it.
14652 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14653
14654 // C89 footnote 38:
14655 // If in fact it is not defined as having type "function returning int",
14656 // the behavior is undefined.
14657 if (!isa<FunctionDecl>(ExternCPrev) ||
14658 !Context.typesAreCompatible(
14659 cast<FunctionDecl>(ExternCPrev)->getType(),
14660 Context.getFunctionNoProtoType(Context.IntTy))) {
14661 Diag(Loc, diag::ext_use_out_of_scope_declaration)
14662 << ExternCPrev << !getLangOpts().C99;
14663 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14664 return ExternCPrev;
14665 }
14666 }
14667
14668 // Extension in C99. Legal in C90, but warn about it.
14669 unsigned diag_id;
14670 if (II.getName().startswith("__builtin_"))
14671 diag_id = diag::warn_builtin_unknown;
14672 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14673 else if (getLangOpts().OpenCL)
14674 diag_id = diag::err_opencl_implicit_function_decl;
14675 else if (getLangOpts().C99)
14676 diag_id = diag::ext_implicit_function_decl;
14677 else
14678 diag_id = diag::warn_implicit_function_decl;
14679 Diag(Loc, diag_id) << &II;
14680
14681 // If we found a prior declaration of this function, don't bother building
14682 // another one. We've already pushed that one into scope, so there's nothing
14683 // more to do.
14684 if (ExternCPrev)
14685 return ExternCPrev;
14686
14687 // Because typo correction is expensive, only do it if the implicit
14688 // function declaration is going to be treated as an error.
14689 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14690 TypoCorrection Corrected;
14691 DeclFilterCCC<FunctionDecl> CCC{};
14692 if (S && (Corrected =
14693 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14694 S, nullptr, CCC, CTK_NonError)))
14695 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14696 /*ErrorRecovery*/false);
14697 }
14698
14699 // Set a Declarator for the implicit definition: int foo();
14700 const char *Dummy;
14701 AttributeFactory attrFactory;
14702 DeclSpec DS(attrFactory);
14703 unsigned DiagID;
14704 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14705 Context.getPrintingPolicy());
14706 (void)Error; // Silence warning.
14707 assert(!Error && "Error setting up implicit decl!")((!Error && "Error setting up implicit decl!") ? static_cast
<void> (0) : __assert_fail ("!Error && \"Error setting up implicit decl!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14707, __PRETTY_FUNCTION__))
;
14708 SourceLocation NoLoc;
14709 Declarator D(DS, DeclaratorContext::Block);
14710 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14711 /*IsAmbiguous=*/false,
14712 /*LParenLoc=*/NoLoc,
14713 /*Params=*/nullptr,
14714 /*NumParams=*/0,
14715 /*EllipsisLoc=*/NoLoc,
14716 /*RParenLoc=*/NoLoc,
14717 /*RefQualifierIsLvalueRef=*/true,
14718 /*RefQualifierLoc=*/NoLoc,
14719 /*MutableLoc=*/NoLoc, EST_None,
14720 /*ESpecRange=*/SourceRange(),
14721 /*Exceptions=*/nullptr,
14722 /*ExceptionRanges=*/nullptr,
14723 /*NumExceptions=*/0,
14724 /*NoexceptExpr=*/nullptr,
14725 /*ExceptionSpecTokens=*/nullptr,
14726 /*DeclsInPrototype=*/None, Loc,
14727 Loc, D),
14728 std::move(DS.getAttributes()), SourceLocation());
14729 D.SetIdentifier(&II, Loc);
14730
14731 // Insert this function into the enclosing block scope.
14732 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14733 FD->setImplicit();
14734
14735 AddKnownFunctionAttributes(FD);
14736
14737 return FD;
14738}
14739
14740/// If this function is a C++ replaceable global allocation function
14741/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14742/// adds any function attributes that we know a priori based on the standard.
14743///
14744/// We need to check for duplicate attributes both here and where user-written
14745/// attributes are applied to declarations.
14746void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14747 FunctionDecl *FD) {
14748 if (FD->isInvalidDecl())
14749 return;
14750
14751 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14752 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14753 return;
14754
14755 Optional<unsigned> AlignmentParam;
14756 bool IsNothrow = false;
14757 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14758 return;
14759
14760 // C++2a [basic.stc.dynamic.allocation]p4:
14761 // An allocation function that has a non-throwing exception specification
14762 // indicates failure by returning a null pointer value. Any other allocation
14763 // function never returns a null pointer value and indicates failure only by
14764 // throwing an exception [...]
14765 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14766 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14767
14768 // C++2a [basic.stc.dynamic.allocation]p2:
14769 // An allocation function attempts to allocate the requested amount of
14770 // storage. [...] If the request succeeds, the value returned by a
14771 // replaceable allocation function is a [...] pointer value p0 different
14772 // from any previously returned value p1 [...]
14773 //
14774 // However, this particular information is being added in codegen,
14775 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14776
14777 // C++2a [basic.stc.dynamic.allocation]p2:
14778 // An allocation function attempts to allocate the requested amount of
14779 // storage. If it is successful, it returns the address of the start of a
14780 // block of storage whose length in bytes is at least as large as the
14781 // requested size.
14782 if (!FD->hasAttr<AllocSizeAttr>()) {
14783 FD->addAttr(AllocSizeAttr::CreateImplicit(
14784 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14785 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14786 }
14787
14788 // C++2a [basic.stc.dynamic.allocation]p3:
14789 // For an allocation function [...], the pointer returned on a successful
14790 // call shall represent the address of storage that is aligned as follows:
14791 // (3.1) If the allocation function takes an argument of type
14792 // std​::​align_­val_­t, the storage will have the alignment
14793 // specified by the value of this argument.
14794 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14795 FD->addAttr(AllocAlignAttr::CreateImplicit(
14796 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14797 }
14798
14799 // FIXME:
14800 // C++2a [basic.stc.dynamic.allocation]p3:
14801 // For an allocation function [...], the pointer returned on a successful
14802 // call shall represent the address of storage that is aligned as follows:
14803 // (3.2) Otherwise, if the allocation function is named operator new[],
14804 // the storage is aligned for any object that does not have
14805 // new-extended alignment ([basic.align]) and is no larger than the
14806 // requested size.
14807 // (3.3) Otherwise, the storage is aligned for any object that does not
14808 // have new-extended alignment and is of the requested size.
14809}
14810
14811/// Adds any function attributes that we know a priori based on
14812/// the declaration of this function.
14813///
14814/// These attributes can apply both to implicitly-declared builtins
14815/// (like __builtin___printf_chk) or to library-declared functions
14816/// like NSLog or printf.
14817///
14818/// We need to check for duplicate attributes both here and where user-written
14819/// attributes are applied to declarations.
14820void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14821 if (FD->isInvalidDecl())
14822 return;
14823
14824 // If this is a built-in function, map its builtin attributes to
14825 // actual attributes.
14826 if (unsigned BuiltinID = FD->getBuiltinID()) {
14827 // Handle printf-formatting attributes.
14828 unsigned FormatIdx;
14829 bool HasVAListArg;
14830 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14831 if (!FD->hasAttr<FormatAttr>()) {
14832 const char *fmt = "printf";
14833 unsigned int NumParams = FD->getNumParams();
14834 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14835 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14836 fmt = "NSString";
14837 FD->addAttr(FormatAttr::CreateImplicit(Context,
14838 &Context.Idents.get(fmt),
14839 FormatIdx+1,
14840 HasVAListArg ? 0 : FormatIdx+2,
14841 FD->getLocation()));
14842 }
14843 }
14844 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14845 HasVAListArg)) {
14846 if (!FD->hasAttr<FormatAttr>())
14847 FD->addAttr(FormatAttr::CreateImplicit(Context,
14848 &Context.Idents.get("scanf"),
14849 FormatIdx+1,
14850 HasVAListArg ? 0 : FormatIdx+2,
14851 FD->getLocation()));
14852 }
14853
14854 // Handle automatically recognized callbacks.
14855 SmallVector<int, 4> Encoding;
14856 if (!FD->hasAttr<CallbackAttr>() &&
14857 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14858 FD->addAttr(CallbackAttr::CreateImplicit(
14859 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14860
14861 // Mark const if we don't care about errno and that is the only thing
14862 // preventing the function from being const. This allows IRgen to use LLVM
14863 // intrinsics for such functions.
14864 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14865 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14866 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14867
14868 // We make "fma" on some platforms const because we know it does not set
14869 // errno in those environments even though it could set errno based on the
14870 // C standard.
14871 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14872 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14873 !FD->hasAttr<ConstAttr>()) {
14874 switch (BuiltinID) {
14875 case Builtin::BI__builtin_fma:
14876 case Builtin::BI__builtin_fmaf:
14877 case Builtin::BI__builtin_fmal:
14878 case Builtin::BIfma:
14879 case Builtin::BIfmaf:
14880 case Builtin::BIfmal:
14881 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14882 break;
14883 default:
14884 break;
14885 }
14886 }
14887
14888 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14889 !FD->hasAttr<ReturnsTwiceAttr>())
14890 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14891 FD->getLocation()));
14892 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14893 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14894 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14895 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14896 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14897 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14898 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14899 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14900 // Add the appropriate attribute, depending on the CUDA compilation mode
14901 // and which target the builtin belongs to. For example, during host
14902 // compilation, aux builtins are __device__, while the rest are __host__.
14903 if (getLangOpts().CUDAIsDevice !=
14904 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14905 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14906 else
14907 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14908 }
14909 }
14910
14911 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14912
14913 // If C++ exceptions are enabled but we are told extern "C" functions cannot
14914 // throw, add an implicit nothrow attribute to any extern "C" function we come
14915 // across.
14916 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14917 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14918 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14919 if (!FPT || FPT->getExceptionSpecType() == EST_None)
14920 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14921 }
14922
14923 IdentifierInfo *Name = FD->getIdentifier();
14924 if (!Name)
14925 return;
14926 if ((!getLangOpts().CPlusPlus &&
14927 FD->getDeclContext()->isTranslationUnit()) ||
14928 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14929 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14930 LinkageSpecDecl::lang_c)) {
14931 // Okay: this could be a libc/libm/Objective-C function we know
14932 // about.
14933 } else
14934 return;
14935
14936 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14937 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14938 // target-specific builtins, perhaps?
14939 if (!FD->hasAttr<FormatAttr>())
14940 FD->addAttr(FormatAttr::CreateImplicit(Context,
14941 &Context.Idents.get("printf"), 2,
14942 Name->isStr("vasprintf") ? 0 : 3,
14943 FD->getLocation()));
14944 }
14945
14946 if (Name->isStr("__CFStringMakeConstantString")) {
14947 // We already have a __builtin___CFStringMakeConstantString,
14948 // but builds that use -fno-constant-cfstrings don't go through that.
14949 if (!FD->hasAttr<FormatArgAttr>())
14950 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14951 FD->getLocation()));
14952 }
14953}
14954
14955TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14956 TypeSourceInfo *TInfo) {
14957 assert(D.getIdentifier() && "Wrong callback for declspec without declarator")((D.getIdentifier() && "Wrong callback for declspec without declarator"
) ? static_cast<void> (0) : __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14957, __PRETTY_FUNCTION__))
;
14958 assert(!T.isNull() && "GetTypeForDeclarator() returned null type")((!T.isNull() && "GetTypeForDeclarator() returned null type"
) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14958, __PRETTY_FUNCTION__))
;
14959
14960 if (!TInfo) {
14961 assert(D.isInvalidType() && "no declarator info for valid type")((D.isInvalidType() && "no declarator info for valid type"
) ? static_cast<void> (0) : __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 14961, __PRETTY_FUNCTION__))
;
14962 TInfo = Context.getTrivialTypeSourceInfo(T);
14963 }
14964
14965 // Scope manipulation handled by caller.
14966 TypedefDecl *NewTD =
14967 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14968 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14969
14970 // Bail out immediately if we have an invalid declaration.
14971 if (D.isInvalidType()) {
14972 NewTD->setInvalidDecl();
14973 return NewTD;
14974 }
14975
14976 if (D.getDeclSpec().isModulePrivateSpecified()) {
14977 if (CurContext->isFunctionOrMethod())
14978 Diag(NewTD->getLocation(), diag::err_module_private_local)
14979 << 2 << NewTD
14980 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14981 << FixItHint::CreateRemoval(
14982 D.getDeclSpec().getModulePrivateSpecLoc());
14983 else
14984 NewTD->setModulePrivate();
14985 }
14986
14987 // C++ [dcl.typedef]p8:
14988 // If the typedef declaration defines an unnamed class (or
14989 // enum), the first typedef-name declared by the declaration
14990 // to be that class type (or enum type) is used to denote the
14991 // class type (or enum type) for linkage purposes only.
14992 // We need to check whether the type was declared in the declaration.
14993 switch (D.getDeclSpec().getTypeSpecType()) {
14994 case TST_enum:
14995 case TST_struct:
14996 case TST_interface:
14997 case TST_union:
14998 case TST_class: {
14999 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15000 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15001 break;
15002 }
15003
15004 default:
15005 break;
15006 }
15007
15008 return NewTD;
15009}
15010
15011/// Check that this is a valid underlying type for an enum declaration.
15012bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15013 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15014 QualType T = TI->getType();
15015
15016 if (T->isDependentType())
15017 return false;
15018
15019 // This doesn't use 'isIntegralType' despite the error message mentioning
15020 // integral type because isIntegralType would also allow enum types in C.
15021 if (const BuiltinType *BT = T->getAs<BuiltinType>())
15022 if (BT->isInteger())
15023 return false;
15024
15025 if (T->isExtIntType())
15026 return false;
15027
15028 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15029}
15030
15031/// Check whether this is a valid redeclaration of a previous enumeration.
15032/// \return true if the redeclaration was invalid.
15033bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15034 QualType EnumUnderlyingTy, bool IsFixed,
15035 const EnumDecl *Prev) {
15036 if (IsScoped != Prev->isScoped()) {
15037 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15038 << Prev->isScoped();
15039 Diag(Prev->getLocation(), diag::note_previous_declaration);
15040 return true;
15041 }
15042
15043 if (IsFixed && Prev->isFixed()) {
15044 if (!EnumUnderlyingTy->isDependentType() &&
15045 !Prev->getIntegerType()->isDependentType() &&
15046 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15047 Prev->getIntegerType())) {
15048 // TODO: Highlight the underlying type of the redeclaration.
15049 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15050 << EnumUnderlyingTy << Prev->getIntegerType();
15051 Diag(Prev->getLocation(), diag::note_previous_declaration)
15052 << Prev->getIntegerTypeRange();
15053 return true;
15054 }
15055 } else if (IsFixed != Prev->isFixed()) {
15056 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15057 << Prev->isFixed();
15058 Diag(Prev->getLocation(), diag::note_previous_declaration);
15059 return true;
15060 }
15061
15062 return false;
15063}
15064
15065/// Get diagnostic %select index for tag kind for
15066/// redeclaration diagnostic message.
15067/// WARNING: Indexes apply to particular diagnostics only!
15068///
15069/// \returns diagnostic %select index.
15070static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15071 switch (Tag) {
15072 case TTK_Struct: return 0;
15073 case TTK_Interface: return 1;
15074 case TTK_Class: return 2;
15075 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 15075)
;
15076 }
15077}
15078
15079/// Determine if tag kind is a class-key compatible with
15080/// class for redeclaration (class, struct, or __interface).
15081///
15082/// \returns true iff the tag kind is compatible.
15083static bool isClassCompatTagKind(TagTypeKind Tag)
15084{
15085 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15086}
15087
15088Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15089 TagTypeKind TTK) {
15090 if (isa<TypedefDecl>(PrevDecl))
15091 return NTK_Typedef;
15092 else if (isa<TypeAliasDecl>(PrevDecl))
15093 return NTK_TypeAlias;
15094 else if (isa<ClassTemplateDecl>(PrevDecl))
15095 return NTK_Template;
15096 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15097 return NTK_TypeAliasTemplate;
15098 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15099 return NTK_TemplateTemplateArgument;
15100 switch (TTK) {
15101 case TTK_Struct:
15102 case TTK_Interface:
15103 case TTK_Class:
15104 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15105 case TTK_Union:
15106 return NTK_NonUnion;
15107 case TTK_Enum:
15108 return NTK_NonEnum;
15109 }
15110 llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 15110)
;
15111}
15112
15113/// Determine whether a tag with a given kind is acceptable
15114/// as a redeclaration of the given tag declaration.
15115///
15116/// \returns true if the new tag kind is acceptable, false otherwise.
15117bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15118 TagTypeKind NewTag, bool isDefinition,
15119 SourceLocation NewTagLoc,
15120 const IdentifierInfo *Name) {
15121 // C++ [dcl.type.elab]p3:
15122 // The class-key or enum keyword present in the
15123 // elaborated-type-specifier shall agree in kind with the
15124 // declaration to which the name in the elaborated-type-specifier
15125 // refers. This rule also applies to the form of
15126 // elaborated-type-specifier that declares a class-name or
15127 // friend class since it can be construed as referring to the
15128 // definition of the class. Thus, in any
15129 // elaborated-type-specifier, the enum keyword shall be used to
15130 // refer to an enumeration (7.2), the union class-key shall be
15131 // used to refer to a union (clause 9), and either the class or
15132 // struct class-key shall be used to refer to a class (clause 9)
15133 // declared using the class or struct class-key.
15134 TagTypeKind OldTag = Previous->getTagKind();
15135 if (OldTag != NewTag &&
15136 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15137 return false;
15138
15139 // Tags are compatible, but we might still want to warn on mismatched tags.
15140 // Non-class tags can't be mismatched at this point.
15141 if (!isClassCompatTagKind(NewTag))
15142 return true;
15143
15144 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15145 // by our warning analysis. We don't want to warn about mismatches with (eg)
15146 // declarations in system headers that are designed to be specialized, but if
15147 // a user asks us to warn, we should warn if their code contains mismatched
15148 // declarations.
15149 auto IsIgnoredLoc = [&](SourceLocation Loc) {
15150 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15151 Loc);
15152 };
15153 if (IsIgnoredLoc(NewTagLoc))
15154 return true;
15155
15156 auto IsIgnored = [&](const TagDecl *Tag) {
15157 return IsIgnoredLoc(Tag->getLocation());
15158 };
15159 while (IsIgnored(Previous)) {
15160 Previous = Previous->getPreviousDecl();
15161 if (!Previous)
15162 return true;
15163 OldTag = Previous->getTagKind();
15164 }
15165
15166 bool isTemplate = false;
15167 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15168 isTemplate = Record->getDescribedClassTemplate();
15169
15170 if (inTemplateInstantiation()) {
15171 if (OldTag != NewTag) {
15172 // In a template instantiation, do not offer fix-its for tag mismatches
15173 // since they usually mess up the template instead of fixing the problem.
15174 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15175 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15176 << getRedeclDiagFromTagKind(OldTag);
15177 // FIXME: Note previous location?
15178 }
15179 return true;
15180 }
15181
15182 if (isDefinition) {
15183 // On definitions, check all previous tags and issue a fix-it for each
15184 // one that doesn't match the current tag.
15185 if (Previous->getDefinition()) {
15186 // Don't suggest fix-its for redefinitions.
15187 return true;
15188 }
15189
15190 bool previousMismatch = false;
15191 for (const TagDecl *I : Previous->redecls()) {
15192 if (I->getTagKind() != NewTag) {
15193 // Ignore previous declarations for which the warning was disabled.
15194 if (IsIgnored(I))
15195 continue;
15196
15197 if (!previousMismatch) {
15198 previousMismatch = true;
15199 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15200 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15201 << getRedeclDiagFromTagKind(I->getTagKind());
15202 }
15203 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15204 << getRedeclDiagFromTagKind(NewTag)
15205 << FixItHint::CreateReplacement(I->getInnerLocStart(),
15206 TypeWithKeyword::getTagTypeKindName(NewTag));
15207 }
15208 }
15209 return true;
15210 }
15211
15212 // Identify the prevailing tag kind: this is the kind of the definition (if
15213 // there is a non-ignored definition), or otherwise the kind of the prior
15214 // (non-ignored) declaration.
15215 const TagDecl *PrevDef = Previous->getDefinition();
15216 if (PrevDef && IsIgnored(PrevDef))
15217 PrevDef = nullptr;
15218 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15219 if (Redecl->getTagKind() != NewTag) {
15220 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15221 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15222 << getRedeclDiagFromTagKind(OldTag);
15223 Diag(Redecl->getLocation(), diag::note_previous_use);
15224
15225 // If there is a previous definition, suggest a fix-it.
15226 if (PrevDef) {
15227 Diag(NewTagLoc, diag::note_struct_class_suggestion)
15228 << getRedeclDiagFromTagKind(Redecl->getTagKind())
15229 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15230 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15231 }
15232 }
15233
15234 return true;
15235}
15236
15237/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15238/// from an outer enclosing namespace or file scope inside a friend declaration.
15239/// This should provide the commented out code in the following snippet:
15240/// namespace N {
15241/// struct X;
15242/// namespace M {
15243/// struct Y { friend struct /*N::*/ X; };
15244/// }
15245/// }
15246static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15247 SourceLocation NameLoc) {
15248 // While the decl is in a namespace, do repeated lookup of that name and see
15249 // if we get the same namespace back. If we do not, continue until
15250 // translation unit scope, at which point we have a fully qualified NNS.
15251 SmallVector<IdentifierInfo *, 4> Namespaces;
15252 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15253 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15254 // This tag should be declared in a namespace, which can only be enclosed by
15255 // other namespaces. Bail if there's an anonymous namespace in the chain.
15256 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15257 if (!Namespace || Namespace->isAnonymousNamespace())
15258 return FixItHint();
15259 IdentifierInfo *II = Namespace->getIdentifier();
15260 Namespaces.push_back(II);
15261 NamedDecl *Lookup = SemaRef.LookupSingleName(
15262 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15263 if (Lookup == Namespace)
15264 break;
15265 }
15266
15267 // Once we have all the namespaces, reverse them to go outermost first, and
15268 // build an NNS.
15269 SmallString<64> Insertion;
15270 llvm::raw_svector_ostream OS(Insertion);
15271 if (DC->isTranslationUnit())
15272 OS << "::";
15273 std::reverse(Namespaces.begin(), Namespaces.end());
15274 for (auto *II : Namespaces)
15275 OS << II->getName() << "::";
15276 return FixItHint::CreateInsertion(NameLoc, Insertion);
15277}
15278
15279/// Determine whether a tag originally declared in context \p OldDC can
15280/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15281/// found a declaration in \p OldDC as a previous decl, perhaps through a
15282/// using-declaration).
15283static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15284 DeclContext *NewDC) {
15285 OldDC = OldDC->getRedeclContext();
15286 NewDC = NewDC->getRedeclContext();
15287
15288 if (OldDC->Equals(NewDC))
15289 return true;
15290
15291 // In MSVC mode, we allow a redeclaration if the contexts are related (either
15292 // encloses the other).
15293 if (S.getLangOpts().MSVCCompat &&
15294 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15295 return true;
15296
15297 return false;
15298}
15299
15300/// This is invoked when we see 'struct foo' or 'struct {'. In the
15301/// former case, Name will be non-null. In the later case, Name will be null.
15302/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15303/// reference/declaration/definition of a tag.
15304///
15305/// \param IsTypeSpecifier \c true if this is a type-specifier (or
15306/// trailing-type-specifier) other than one in an alias-declaration.
15307///
15308/// \param SkipBody If non-null, will be set to indicate if the caller should
15309/// skip the definition of this tag and treat it as if it were a declaration.
15310Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15311 SourceLocation KWLoc, CXXScopeSpec &SS,
15312 IdentifierInfo *Name, SourceLocation NameLoc,
15313 const ParsedAttributesView &Attrs, AccessSpecifier AS,
15314 SourceLocation ModulePrivateLoc,
15315 MultiTemplateParamsArg TemplateParameterLists,
15316 bool &OwnedDecl, bool &IsDependent,
15317 SourceLocation ScopedEnumKWLoc,
15318 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15319 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15320 SkipBodyInfo *SkipBody) {
15321 // If this is not a definition, it must have a name.
15322 IdentifierInfo *OrigName = Name;
15323 assert((Name != nullptr || TUK == TUK_Definition) &&(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!"
) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 15324, __PRETTY_FUNCTION__))
15324 "Nameless record must be a definition!")(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!"
) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 15324, __PRETTY_FUNCTION__))
;
15325 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)((TemplateParameterLists.size() == 0 || TUK != TUK_Reference)
? static_cast<void> (0) : __assert_fail ("TemplateParameterLists.size() == 0 || TUK != TUK_Reference"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 15325, __PRETTY_FUNCTION__))
;
15326
15327 OwnedDecl = false;
15328 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15329 bool ScopedEnum = ScopedEnumKWLoc.isValid();
15330
15331 // FIXME: Check member specializations more carefully.
15332 bool isMemberSpecialization = false;
15333 bool Invalid = false;
15334
15335 // We only need to do this matching if we have template parameters
15336 // or a scope specifier, which also conveniently avoids this work
15337 // for non-C++ cases.
15338 if (TemplateParameterLists.size() > 0 ||
15339 (SS.isNotEmpty() && TUK != TUK_Reference)) {
15340 if (TemplateParameterList *TemplateParams =
15341 MatchTemplateParametersToScopeSpecifier(
15342 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15343 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15344 if (Kind == TTK_Enum) {
15345 Diag(KWLoc, diag::err_enum_template);
15346 return nullptr;
15347 }
15348
15349 if (TemplateParams->size() > 0) {
15350 // This is a declaration or definition of a class template (which may
15351 // be a member of another template).
15352
15353 if (Invalid)
15354 return nullptr;
15355
15356 OwnedDecl = false;
15357 DeclResult Result = CheckClassTemplate(
15358 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15359 AS, ModulePrivateLoc,
15360 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15361 TemplateParameterLists.data(), SkipBody);
15362 return Result.get();
15363 } else {
15364 // The "template<>" header is extraneous.
15365 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15366 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15367 isMemberSpecialization = true;
15368 }
15369 }
15370
15371 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15372 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15373 return nullptr;
15374 }
15375
15376 // Figure out the underlying type if this a enum declaration. We need to do
15377 // this early, because it's needed to detect if this is an incompatible
15378 // redeclaration.
15379 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15380 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15381
15382 if (Kind == TTK_Enum) {
15383 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15384 // No underlying type explicitly specified, or we failed to parse the
15385 // type, default to int.
15386 EnumUnderlying = Context.IntTy.getTypePtr();
15387 } else if (UnderlyingType.get()) {
15388 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15389 // integral type; any cv-qualification is ignored.
15390 TypeSourceInfo *TI = nullptr;
15391 GetTypeFromParser(UnderlyingType.get(), &TI);
15392 EnumUnderlying = TI;
15393
15394 if (CheckEnumUnderlyingType(TI))
15395 // Recover by falling back to int.
15396 EnumUnderlying = Context.IntTy.getTypePtr();
15397
15398 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15399 UPPC_FixedUnderlyingType))
15400 EnumUnderlying = Context.IntTy.getTypePtr();
15401
15402 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15403 // For MSVC ABI compatibility, unfixed enums must use an underlying type
15404 // of 'int'. However, if this is an unfixed forward declaration, don't set
15405 // the underlying type unless the user enables -fms-compatibility. This
15406 // makes unfixed forward declared enums incomplete and is more conforming.
15407 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15408 EnumUnderlying = Context.IntTy.getTypePtr();
15409 }
15410 }
15411
15412 DeclContext *SearchDC = CurContext;
15413 DeclContext *DC = CurContext;
15414 bool isStdBadAlloc = false;
15415 bool isStdAlignValT = false;
15416
15417 RedeclarationKind Redecl = forRedeclarationInCurContext();
15418 if (TUK == TUK_Friend || TUK == TUK_Reference)
15419 Redecl = NotForRedeclaration;
15420
15421 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15422 /// implemented asks for structural equivalence checking, the returned decl
15423 /// here is passed back to the parser, allowing the tag body to be parsed.
15424 auto createTagFromNewDecl = [&]() -> TagDecl * {
15425 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")((!getLangOpts().CPlusPlus && "not meant for C++ usage"
) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 15425, __PRETTY_FUNCTION__))
;
15426 // If there is an identifier, use the location of the identifier as the
15427 // location of the decl, otherwise use the location of the struct/union
15428 // keyword.
15429 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15430 TagDecl *New = nullptr;
15431
15432 if (Kind == TTK_Enum) {
15433 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15434 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15435 // If this is an undefined enum, bail.
15436 if (TUK != TUK_Definition && !Invalid)
15437 return nullptr;
15438 if (EnumUnderlying) {
15439 EnumDecl *ED = cast<EnumDecl>(New);
15440 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15441 ED->setIntegerTypeSourceInfo(TI);
15442 else
15443 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15444 ED->setPromotionType(ED->getIntegerType());
15445 }
15446 } else { // struct/union
15447 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15448 nullptr);
15449 }
15450
15451 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15452 // Add alignment attributes if necessary; these attributes are checked
15453 // when the ASTContext lays out the structure.
15454 //
15455 // It is important for implementing the correct semantics that this
15456 // happen here (in ActOnTag). The #pragma pack stack is
15457 // maintained as a result of parser callbacks which can occur at
15458 // many points during the parsing of a struct declaration (because
15459 // the #pragma tokens are effectively skipped over during the
15460 // parsing of the struct).
15461 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15462 AddAlignmentAttributesForRecord(RD);
15463 AddMsStructLayoutForRecord(RD);
15464 }
15465 }
15466 New->setLexicalDeclContext(CurContext);
15467 return New;
15468 };
15469
15470 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15471 if (Name && SS.isNotEmpty()) {
15472 // We have a nested-name tag ('struct foo::bar').
15473
15474 // Check for invalid 'foo::'.
15475 if (SS.isInvalid()) {
15476 Name = nullptr;
15477 goto CreateNewDecl;
15478 }
15479
15480 // If this is a friend or a reference to a class in a dependent
15481 // context, don't try to make a decl for it.
15482 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15483 DC = computeDeclContext(SS, false);
15484 if (!DC) {
15485 IsDependent = true;
15486 return nullptr;
15487 }
15488 } else {
15489 DC = computeDeclContext(SS, true);
15490 if (!DC) {
15491 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15492 << SS.getRange();
15493 return nullptr;
15494 }
15495 }
15496
15497 if (RequireCompleteDeclContext(SS, DC))
15498 return nullptr;
15499
15500 SearchDC = DC;
15501 // Look-up name inside 'foo::'.
15502 LookupQualifiedName(Previous, DC);
15503
15504 if (Previous.isAmbiguous())
15505 return nullptr;
15506
15507 if (Previous.empty()) {
15508 // Name lookup did not find anything. However, if the
15509 // nested-name-specifier refers to the current instantiation,
15510 // and that current instantiation has any dependent base
15511 // classes, we might find something at instantiation time: treat
15512 // this as a dependent elaborated-type-specifier.
15513 // But this only makes any sense for reference-like lookups.
15514 if (Previous.wasNotFoundInCurrentInstantiation() &&
15515 (TUK == TUK_Reference || TUK == TUK_Friend)) {
15516 IsDependent = true;
15517 return nullptr;
15518 }
15519
15520 // A tag 'foo::bar' must already exist.
15521 Diag(NameLoc, diag::err_not_tag_in_scope)
15522 << Kind << Name << DC << SS.getRange();
15523 Name = nullptr;
15524 Invalid = true;
15525 goto CreateNewDecl;
15526 }
15527 } else if (Name) {
15528 // C++14 [class.mem]p14:
15529 // If T is the name of a class, then each of the following shall have a
15530 // name different from T:
15531 // -- every member of class T that is itself a type
15532 if (TUK != TUK_Reference && TUK != TUK_Friend &&
15533 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15534 return nullptr;
15535
15536 // If this is a named struct, check to see if there was a previous forward
15537 // declaration or definition.
15538 // FIXME: We're looking into outer scopes here, even when we
15539 // shouldn't be. Doing so can result in ambiguities that we
15540 // shouldn't be diagnosing.
15541 LookupName(Previous, S);
15542
15543 // When declaring or defining a tag, ignore ambiguities introduced
15544 // by types using'ed into this scope.
15545 if (Previous.isAmbiguous() &&
15546 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15547 LookupResult::Filter F = Previous.makeFilter();
15548 while (F.hasNext()) {
15549 NamedDecl *ND = F.next();
15550 if (!ND->getDeclContext()->getRedeclContext()->Equals(
15551 SearchDC->getRedeclContext()))
15552 F.erase();
15553 }
15554 F.done();
15555 }
15556
15557 // C++11 [namespace.memdef]p3:
15558 // If the name in a friend declaration is neither qualified nor
15559 // a template-id and the declaration is a function or an
15560 // elaborated-type-specifier, the lookup to determine whether
15561 // the entity has been previously declared shall not consider
15562 // any scopes outside the innermost enclosing namespace.
15563 //
15564 // MSVC doesn't implement the above rule for types, so a friend tag
15565 // declaration may be a redeclaration of a type declared in an enclosing
15566 // scope. They do implement this rule for friend functions.
15567 //
15568 // Does it matter that this should be by scope instead of by
15569 // semantic context?
15570 if (!Previous.empty() && TUK == TUK_Friend) {
15571 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15572 LookupResult::Filter F = Previous.makeFilter();
15573 bool FriendSawTagOutsideEnclosingNamespace = false;
15574 while (F.hasNext()) {
15575 NamedDecl *ND = F.next();
15576 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15577 if (DC->isFileContext() &&
15578 !EnclosingNS->Encloses(ND->getDeclContext())) {
15579 if (getLangOpts().MSVCCompat)
15580 FriendSawTagOutsideEnclosingNamespace = true;
15581 else
15582 F.erase();
15583 }
15584 }
15585 F.done();
15586
15587 // Diagnose this MSVC extension in the easy case where lookup would have
15588 // unambiguously found something outside the enclosing namespace.
15589 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15590 NamedDecl *ND = Previous.getFoundDecl();
15591 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15592 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15593 }
15594 }
15595
15596 // Note: there used to be some attempt at recovery here.
15597 if (Previous.isAmbiguous())
15598 return nullptr;
15599
15600 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15601 // FIXME: This makes sure that we ignore the contexts associated
15602 // with C structs, unions, and enums when looking for a matching
15603 // tag declaration or definition. See the similar lookup tweak
15604 // in Sema::LookupName; is there a better way to deal with this?
15605 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15606 SearchDC = SearchDC->getParent();
15607 }
15608 }
15609
15610 if (Previous.isSingleResult() &&
15611 Previous.getFoundDecl()->isTemplateParameter()) {
15612 // Maybe we will complain about the shadowed template parameter.
15613 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15614 // Just pretend that we didn't see the previous declaration.
15615 Previous.clear();
15616 }
15617
15618 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15619 DC->Equals(getStdNamespace())) {
15620 if (Name->isStr("bad_alloc")) {
15621 // This is a declaration of or a reference to "std::bad_alloc".
15622 isStdBadAlloc = true;
15623
15624 // If std::bad_alloc has been implicitly declared (but made invisible to
15625 // name lookup), fill in this implicit declaration as the previous
15626 // declaration, so that the declarations get chained appropriately.
15627 if (Previous.empty() && StdBadAlloc)
15628 Previous.addDecl(getStdBadAlloc());
15629 } else if (Name->isStr("align_val_t")) {
15630 isStdAlignValT = true;
15631 if (Previous.empty() && StdAlignValT)
15632 Previous.addDecl(getStdAlignValT());
15633 }
15634 }
15635
15636 // If we didn't find a previous declaration, and this is a reference
15637 // (or friend reference), move to the correct scope. In C++, we
15638 // also need to do a redeclaration lookup there, just in case
15639 // there's a shadow friend decl.
15640 if (Name && Previous.empty() &&
15641 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15642 if (Invalid) goto CreateNewDecl;
15643 assert(SS.isEmpty())((SS.isEmpty()) ? static_cast<void> (0) : __assert_fail
("SS.isEmpty()", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 15643, __PRETTY_FUNCTION__))
;
15644
15645 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15646 // C++ [basic.scope.pdecl]p5:
15647 // -- for an elaborated-type-specifier of the form
15648 //
15649 // class-key identifier
15650 //
15651 // if the elaborated-type-specifier is used in the
15652 // decl-specifier-seq or parameter-declaration-clause of a
15653 // function defined in namespace scope, the identifier is
15654 // declared as a class-name in the namespace that contains
15655 // the declaration; otherwise, except as a friend
15656 // declaration, the identifier is declared in the smallest
15657 // non-class, non-function-prototype scope that contains the
15658 // declaration.
15659 //
15660 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15661 // C structs and unions.
15662 //
15663 // It is an error in C++ to declare (rather than define) an enum
15664 // type, including via an elaborated type specifier. We'll
15665 // diagnose that later; for now, declare the enum in the same
15666 // scope as we would have picked for any other tag type.
15667 //
15668 // GNU C also supports this behavior as part of its incomplete
15669 // enum types extension, while GNU C++ does not.
15670 //
15671 // Find the context where we'll be declaring the tag.
15672 // FIXME: We would like to maintain the current DeclContext as the
15673 // lexical context,
15674 SearchDC = getTagInjectionContext(SearchDC);
15675
15676 // Find the scope where we'll be declaring the tag.
15677 S = getTagInjectionScope(S, getLangOpts());
15678 } else {
15679 assert(TUK == TUK_Friend)((TUK == TUK_Friend) ? static_cast<void> (0) : __assert_fail
("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 15679, __PRETTY_FUNCTION__))
;
15680 // C++ [namespace.memdef]p3:
15681 // If a friend declaration in a non-local class first declares a
15682 // class or function, the friend class or function is a member of
15683 // the innermost enclosing namespace.
15684 SearchDC = SearchDC->getEnclosingNamespaceContext();
15685 }
15686
15687 // In C++, we need to do a redeclaration lookup to properly
15688 // diagnose some problems.
15689 // FIXME: redeclaration lookup is also used (with and without C++) to find a
15690 // hidden declaration so that we don't get ambiguity errors when using a
15691 // type declared by an elaborated-type-specifier. In C that is not correct
15692 // and we should instead merge compatible types found by lookup.
15693 if (getLangOpts().CPlusPlus) {
15694 // FIXME: This can perform qualified lookups into function contexts,
15695 // which are meaningless.
15696 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15697 LookupQualifiedName(Previous, SearchDC);
15698 } else {
15699 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15700 LookupName(Previous, S);
15701 }
15702 }
15703
15704 // If we have a known previous declaration to use, then use it.
15705 if (Previous.empty() && SkipBody && SkipBody->Previous)
15706 Previous.addDecl(SkipBody->Previous);
15707
15708 if (!Previous.empty()) {
15709 NamedDecl *PrevDecl = Previous.getFoundDecl();
15710 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15711
15712 // It's okay to have a tag decl in the same scope as a typedef
15713 // which hides a tag decl in the same scope. Finding this
15714 // insanity with a redeclaration lookup can only actually happen
15715 // in C++.
15716 //
15717 // This is also okay for elaborated-type-specifiers, which is
15718 // technically forbidden by the current standard but which is
15719 // okay according to the likely resolution of an open issue;
15720 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15721 if (getLangOpts().CPlusPlus) {
15722 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15723 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15724 TagDecl *Tag = TT->getDecl();
15725 if (Tag->getDeclName() == Name &&
15726 Tag->getDeclContext()->getRedeclContext()
15727 ->Equals(TD->getDeclContext()->getRedeclContext())) {
15728 PrevDecl = Tag;
15729 Previous.clear();
15730 Previous.addDecl(Tag);
15731 Previous.resolveKind();
15732 }
15733 }
15734 }
15735 }
15736
15737 // If this is a redeclaration of a using shadow declaration, it must
15738 // declare a tag in the same context. In MSVC mode, we allow a
15739 // redefinition if either context is within the other.
15740 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15741 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15742 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15743 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15744 !(OldTag && isAcceptableTagRedeclContext(
15745 *this, OldTag->getDeclContext(), SearchDC))) {
15746 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15747 Diag(Shadow->getTargetDecl()->getLocation(),
15748 diag::note_using_decl_target);
15749 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15750 << 0;
15751 // Recover by ignoring the old declaration.
15752 Previous.clear();
15753 goto CreateNewDecl;
15754 }
15755 }
15756
15757 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15758 // If this is a use of a previous tag, or if the tag is already declared
15759 // in the same scope (so that the definition/declaration completes or
15760 // rementions the tag), reuse the decl.
15761 if (TUK == TUK_Reference || TUK == TUK_Friend ||
15762 isDeclInScope(DirectPrevDecl, SearchDC, S,
15763 SS.isNotEmpty() || isMemberSpecialization)) {
15764 // Make sure that this wasn't declared as an enum and now used as a
15765 // struct or something similar.
15766 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15767 TUK == TUK_Definition, KWLoc,
15768 Name)) {
15769 bool SafeToContinue
15770 = (PrevTagDecl->getTagKind() != TTK_Enum &&
15771 Kind != TTK_Enum);
15772 if (SafeToContinue)
15773 Diag(KWLoc, diag::err_use_with_wrong_tag)
15774 << Name
15775 << FixItHint::CreateReplacement(SourceRange(KWLoc),
15776 PrevTagDecl->getKindName());
15777 else
15778 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15779 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15780
15781 if (SafeToContinue)
15782 Kind = PrevTagDecl->getTagKind();
15783 else {
15784 // Recover by making this an anonymous redefinition.
15785 Name = nullptr;
15786 Previous.clear();
15787 Invalid = true;
15788 }
15789 }
15790
15791 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15792 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15793 if (TUK == TUK_Reference || TUK == TUK_Friend)
15794 return PrevTagDecl;
15795
15796 QualType EnumUnderlyingTy;
15797 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15798 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15799 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15800 EnumUnderlyingTy = QualType(T, 0);
15801
15802 // All conflicts with previous declarations are recovered by
15803 // returning the previous declaration, unless this is a definition,
15804 // in which case we want the caller to bail out.
15805 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15806 ScopedEnum, EnumUnderlyingTy,
15807 IsFixed, PrevEnum))
15808 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15809 }
15810
15811 // C++11 [class.mem]p1:
15812 // A member shall not be declared twice in the member-specification,
15813 // except that a nested class or member class template can be declared
15814 // and then later defined.
15815 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15816 S->isDeclScope(PrevDecl)) {
15817 Diag(NameLoc, diag::ext_member_redeclared);
15818 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15819 }
15820
15821 if (!Invalid) {
15822 // If this is a use, just return the declaration we found, unless
15823 // we have attributes.
15824 if (TUK == TUK_Reference || TUK == TUK_Friend) {
15825 if (!Attrs.empty()) {
15826 // FIXME: Diagnose these attributes. For now, we create a new
15827 // declaration to hold them.
15828 } else if (TUK == TUK_Reference &&
15829 (PrevTagDecl->getFriendObjectKind() ==
15830 Decl::FOK_Undeclared ||
15831 PrevDecl->getOwningModule() != getCurrentModule()) &&
15832 SS.isEmpty()) {
15833 // This declaration is a reference to an existing entity, but
15834 // has different visibility from that entity: it either makes
15835 // a friend visible or it makes a type visible in a new module.
15836 // In either case, create a new declaration. We only do this if
15837 // the declaration would have meant the same thing if no prior
15838 // declaration were found, that is, if it was found in the same
15839 // scope where we would have injected a declaration.
15840 if (!getTagInjectionContext(CurContext)->getRedeclContext()
15841 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15842 return PrevTagDecl;
15843 // This is in the injected scope, create a new declaration in
15844 // that scope.
15845 S = getTagInjectionScope(S, getLangOpts());
15846 } else {
15847 return PrevTagDecl;
15848 }
15849 }
15850
15851 // Diagnose attempts to redefine a tag.
15852 if (TUK == TUK_Definition) {
15853 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15854 // If we're defining a specialization and the previous definition
15855 // is from an implicit instantiation, don't emit an error
15856 // here; we'll catch this in the general case below.
15857 bool IsExplicitSpecializationAfterInstantiation = false;
15858 if (isMemberSpecialization) {
15859 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15860 IsExplicitSpecializationAfterInstantiation =
15861 RD->getTemplateSpecializationKind() !=
15862 TSK_ExplicitSpecialization;
15863 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15864 IsExplicitSpecializationAfterInstantiation =
15865 ED->getTemplateSpecializationKind() !=
15866 TSK_ExplicitSpecialization;
15867 }
15868
15869 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15870 // not keep more that one definition around (merge them). However,
15871 // ensure the decl passes the structural compatibility check in
15872 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15873 NamedDecl *Hidden = nullptr;
15874 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15875 // There is a definition of this tag, but it is not visible. We
15876 // explicitly make use of C++'s one definition rule here, and
15877 // assume that this definition is identical to the hidden one
15878 // we already have. Make the existing definition visible and
15879 // use it in place of this one.
15880 if (!getLangOpts().CPlusPlus) {
15881 // Postpone making the old definition visible until after we
15882 // complete parsing the new one and do the structural
15883 // comparison.
15884 SkipBody->CheckSameAsPrevious = true;
15885 SkipBody->New = createTagFromNewDecl();
15886 SkipBody->Previous = Def;
15887 return Def;
15888 } else {
15889 SkipBody->ShouldSkip = true;
15890 SkipBody->Previous = Def;
15891 makeMergedDefinitionVisible(Hidden);
15892 // Carry on and handle it like a normal definition. We'll
15893 // skip starting the definitiion later.
15894 }
15895 } else if (!IsExplicitSpecializationAfterInstantiation) {
15896 // A redeclaration in function prototype scope in C isn't
15897 // visible elsewhere, so merely issue a warning.
15898 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15899 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15900 else
15901 Diag(NameLoc, diag::err_redefinition) << Name;
15902 notePreviousDefinition(Def,
15903 NameLoc.isValid() ? NameLoc : KWLoc);
15904 // If this is a redefinition, recover by making this
15905 // struct be anonymous, which will make any later
15906 // references get the previous definition.
15907 Name = nullptr;
15908 Previous.clear();
15909 Invalid = true;
15910 }
15911 } else {
15912 // If the type is currently being defined, complain
15913 // about a nested redefinition.
15914 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15915 if (TD->isBeingDefined()) {
15916 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15917 Diag(PrevTagDecl->getLocation(),
15918 diag::note_previous_definition);
15919 Name = nullptr;
15920 Previous.clear();
15921 Invalid = true;
15922 }
15923 }
15924
15925 // Okay, this is definition of a previously declared or referenced
15926 // tag. We're going to create a new Decl for it.
15927 }
15928
15929 // Okay, we're going to make a redeclaration. If this is some kind
15930 // of reference, make sure we build the redeclaration in the same DC
15931 // as the original, and ignore the current access specifier.
15932 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15933 SearchDC = PrevTagDecl->getDeclContext();
15934 AS = AS_none;
15935 }
15936 }
15937 // If we get here we have (another) forward declaration or we
15938 // have a definition. Just create a new decl.
15939
15940 } else {
15941 // If we get here, this is a definition of a new tag type in a nested
15942 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15943 // new decl/type. We set PrevDecl to NULL so that the entities
15944 // have distinct types.
15945 Previous.clear();
15946 }
15947 // If we get here, we're going to create a new Decl. If PrevDecl
15948 // is non-NULL, it's a definition of the tag declared by
15949 // PrevDecl. If it's NULL, we have a new definition.
15950
15951 // Otherwise, PrevDecl is not a tag, but was found with tag
15952 // lookup. This is only actually possible in C++, where a few
15953 // things like templates still live in the tag namespace.
15954 } else {
15955 // Use a better diagnostic if an elaborated-type-specifier
15956 // found the wrong kind of type on the first
15957 // (non-redeclaration) lookup.
15958 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15959 !Previous.isForRedeclaration()) {
15960 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15961 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15962 << Kind;
15963 Diag(PrevDecl->getLocation(), diag::note_declared_at);
15964 Invalid = true;
15965
15966 // Otherwise, only diagnose if the declaration is in scope.
15967 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15968 SS.isNotEmpty() || isMemberSpecialization)) {
15969 // do nothing
15970
15971 // Diagnose implicit declarations introduced by elaborated types.
15972 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15973 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15974 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15975 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15976 Invalid = true;
15977
15978 // Otherwise it's a declaration. Call out a particularly common
15979 // case here.
15980 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15981 unsigned Kind = 0;
15982 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15983 Diag(NameLoc, diag::err_tag_definition_of_typedef)
15984 << Name << Kind << TND->getUnderlyingType();
15985 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15986 Invalid = true;
15987
15988 // Otherwise, diagnose.
15989 } else {
15990 // The tag name clashes with something else in the target scope,
15991 // issue an error and recover by making this tag be anonymous.
15992 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15993 notePreviousDefinition(PrevDecl, NameLoc);
15994 Name = nullptr;
15995 Invalid = true;
15996 }
15997
15998 // The existing declaration isn't relevant to us; we're in a
15999 // new scope, so clear out the previous declaration.
16000 Previous.clear();
16001 }
16002 }
16003
16004CreateNewDecl:
16005
16006 TagDecl *PrevDecl = nullptr;
16007 if (Previous.isSingleResult())
16008 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16009
16010 // If there is an identifier, use the location of the identifier as the
16011 // location of the decl, otherwise use the location of the struct/union
16012 // keyword.
16013 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16014
16015 // Otherwise, create a new declaration. If there is a previous
16016 // declaration of the same entity, the two will be linked via
16017 // PrevDecl.
16018 TagDecl *New;
16019
16020 if (Kind == TTK_Enum) {
16021 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16022 // enum X { A, B, C } D; D should chain to X.
16023 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16024 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16025 ScopedEnumUsesClassTag, IsFixed);
16026
16027 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16028 StdAlignValT = cast<EnumDecl>(New);
16029
16030 // If this is an undefined enum, warn.
16031 if (TUK != TUK_Definition && !Invalid) {
16032 TagDecl *Def;
16033 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16034 // C++0x: 7.2p2: opaque-enum-declaration.
16035 // Conflicts are diagnosed above. Do nothing.
16036 }
16037 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16038 Diag(Loc, diag::ext_forward_ref_enum_def)
16039 << New;
16040 Diag(Def->getLocation(), diag::note_previous_definition);
16041 } else {
16042 unsigned DiagID = diag::ext_forward_ref_enum;
16043 if (getLangOpts().MSVCCompat)
16044 DiagID = diag::ext_ms_forward_ref_enum;
16045 else if (getLangOpts().CPlusPlus)
16046 DiagID = diag::err_forward_ref_enum;
16047 Diag(Loc, DiagID);
16048 }
16049 }
16050
16051 if (EnumUnderlying) {
16052 EnumDecl *ED = cast<EnumDecl>(New);
16053 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16054 ED->setIntegerTypeSourceInfo(TI);
16055 else
16056 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16057 ED->setPromotionType(ED->getIntegerType());
16058 assert(ED->isComplete() && "enum with type should be complete")((ED->isComplete() && "enum with type should be complete"
) ? static_cast<void> (0) : __assert_fail ("ED->isComplete() && \"enum with type should be complete\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 16058, __PRETTY_FUNCTION__))
;
16059 }
16060 } else {
16061 // struct/union/class
16062
16063 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16064 // struct X { int A; } D; D should chain to X.
16065 if (getLangOpts().CPlusPlus) {
16066 // FIXME: Look for a way to use RecordDecl for simple structs.
16067 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16068 cast_or_null<CXXRecordDecl>(PrevDecl));
16069
16070 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16071 StdBadAlloc = cast<CXXRecordDecl>(New);
16072 } else
16073 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16074 cast_or_null<RecordDecl>(PrevDecl));
16075 }
16076
16077 // C++11 [dcl.type]p3:
16078 // A type-specifier-seq shall not define a class or enumeration [...].
16079 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16080 TUK == TUK_Definition) {
16081 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16082 << Context.getTagDeclType(New);
16083 Invalid = true;
16084 }
16085
16086 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16087 DC->getDeclKind() == Decl::Enum) {
16088 Diag(New->getLocation(), diag::err_type_defined_in_enum)
16089 << Context.getTagDeclType(New);
16090 Invalid = true;
16091 }
16092
16093 // Maybe add qualifier info.
16094 if (SS.isNotEmpty()) {
16095 if (SS.isSet()) {
16096 // If this is either a declaration or a definition, check the
16097 // nested-name-specifier against the current context.
16098 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16099 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16100 isMemberSpecialization))
16101 Invalid = true;
16102
16103 New->setQualifierInfo(SS.getWithLocInContext(Context));
16104 if (TemplateParameterLists.size() > 0) {
16105 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16106 }
16107 }
16108 else
16109 Invalid = true;
16110 }
16111
16112 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16113 // Add alignment attributes if necessary; these attributes are checked when
16114 // the ASTContext lays out the structure.
16115 //
16116 // It is important for implementing the correct semantics that this
16117 // happen here (in ActOnTag). The #pragma pack stack is
16118 // maintained as a result of parser callbacks which can occur at
16119 // many points during the parsing of a struct declaration (because
16120 // the #pragma tokens are effectively skipped over during the
16121 // parsing of the struct).
16122 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16123 AddAlignmentAttributesForRecord(RD);
16124 AddMsStructLayoutForRecord(RD);
16125 }
16126 }
16127
16128 if (ModulePrivateLoc.isValid()) {
16129 if (isMemberSpecialization)
16130 Diag(New->getLocation(), diag::err_module_private_specialization)
16131 << 2
16132 << FixItHint::CreateRemoval(ModulePrivateLoc);
16133 // __module_private__ does not apply to local classes. However, we only
16134 // diagnose this as an error when the declaration specifiers are
16135 // freestanding. Here, we just ignore the __module_private__.
16136 else if (!SearchDC->isFunctionOrMethod())
16137 New->setModulePrivate();
16138 }
16139
16140 // If this is a specialization of a member class (of a class template),
16141 // check the specialization.
16142 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16143 Invalid = true;
16144
16145 // If we're declaring or defining a tag in function prototype scope in C,
16146 // note that this type can only be used within the function and add it to
16147 // the list of decls to inject into the function definition scope.
16148 if ((Name || Kind == TTK_Enum) &&
16149 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16150 if (getLangOpts().CPlusPlus) {
16151 // C++ [dcl.fct]p6:
16152 // Types shall not be defined in return or parameter types.
16153 if (TUK == TUK_Definition && !IsTypeSpecifier) {
16154 Diag(Loc, diag::err_type_defined_in_param_type)
16155 << Name;
16156 Invalid = true;
16157 }
16158 } else if (!PrevDecl) {
16159 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16160 }
16161 }
16162
16163 if (Invalid)
16164 New->setInvalidDecl();
16165
16166 // Set the lexical context. If the tag has a C++ scope specifier, the
16167 // lexical context will be different from the semantic context.
16168 New->setLexicalDeclContext(CurContext);
16169
16170 // Mark this as a friend decl if applicable.
16171 // In Microsoft mode, a friend declaration also acts as a forward
16172 // declaration so we always pass true to setObjectOfFriendDecl to make
16173 // the tag name visible.
16174 if (TUK == TUK_Friend)
16175 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16176
16177 // Set the access specifier.
16178 if (!Invalid && SearchDC->isRecord())
16179 SetMemberAccessSpecifier(New, PrevDecl, AS);
16180
16181 if (PrevDecl)
16182 CheckRedeclarationModuleOwnership(New, PrevDecl);
16183
16184 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16185 New->startDefinition();
16186
16187 ProcessDeclAttributeList(S, New, Attrs);
16188 AddPragmaAttributes(S, New);
16189
16190 // If this has an identifier, add it to the scope stack.
16191 if (TUK == TUK_Friend) {
16192 // We might be replacing an existing declaration in the lookup tables;
16193 // if so, borrow its access specifier.
16194 if (PrevDecl)
16195 New->setAccess(PrevDecl->getAccess());
16196
16197 DeclContext *DC = New->getDeclContext()->getRedeclContext();
16198 DC->makeDeclVisibleInContext(New);
16199 if (Name) // can be null along some error paths
16200 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16201 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16202 } else if (Name) {
16203 S = getNonFieldDeclScope(S);
16204 PushOnScopeChains(New, S, true);
16205 } else {
16206 CurContext->addDecl(New);
16207 }
16208
16209 // If this is the C FILE type, notify the AST context.
16210 if (IdentifierInfo *II = New->getIdentifier())
16211 if (!New->isInvalidDecl() &&
16212 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16213 II->isStr("FILE"))
16214 Context.setFILEDecl(New);
16215
16216 if (PrevDecl)
16217 mergeDeclAttributes(New, PrevDecl);
16218
16219 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16220 inferGslOwnerPointerAttribute(CXXRD);
16221
16222 // If there's a #pragma GCC visibility in scope, set the visibility of this
16223 // record.
16224 AddPushedVisibilityAttribute(New);
16225
16226 if (isMemberSpecialization && !New->isInvalidDecl())
16227 CompleteMemberSpecialization(New, Previous);
16228
16229 OwnedDecl = true;
16230 // In C++, don't return an invalid declaration. We can't recover well from
16231 // the cases where we make the type anonymous.
16232 if (Invalid && getLangOpts().CPlusPlus) {
16233 if (New->isBeingDefined())
16234 if (auto RD = dyn_cast<RecordDecl>(New))
16235 RD->completeDefinition();
16236 return nullptr;
16237 } else if (SkipBody && SkipBody->ShouldSkip) {
16238 return SkipBody->Previous;
16239 } else {
16240 return New;
16241 }
16242}
16243
16244void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16245 AdjustDeclIfTemplate(TagD);
16246 TagDecl *Tag = cast<TagDecl>(TagD);
16247
16248 // Enter the tag context.
16249 PushDeclContext(S, Tag);
16250
16251 ActOnDocumentableDecl(TagD);
16252
16253 // If there's a #pragma GCC visibility in scope, set the visibility of this
16254 // record.
16255 AddPushedVisibilityAttribute(Tag);
16256}
16257
16258bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16259 SkipBodyInfo &SkipBody) {
16260 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16261 return false;
16262
16263 // Make the previous decl visible.
16264 makeMergedDefinitionVisible(SkipBody.Previous);
16265 return true;
16266}
16267
16268Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16269 assert(isa<ObjCContainerDecl>(IDecl) &&((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"
) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 16270, __PRETTY_FUNCTION__))
16270 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"
) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 16270, __PRETTY_FUNCTION__))
;
16271 DeclContext *OCD = cast<DeclContext>(IDecl);
16272 assert(OCD->getLexicalParent() == CurContext &&((OCD->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("OCD->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 16273, __PRETTY_FUNCTION__))
16273 "The next DeclContext should be lexically contained in the current one.")((OCD->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("OCD->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 16273, __PRETTY_FUNCTION__))
;
16274 CurContext = OCD;
16275 return IDecl;
16276}
16277
16278void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16279 SourceLocation FinalLoc,
16280 bool IsFinalSpelledSealed,
16281 SourceLocation LBraceLoc) {
16282 AdjustDeclIfTemplate(TagD);
16283 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16284
16285 FieldCollector->StartClass();
16286
16287 if (!Record->getIdentifier())
16288 return;
16289
16290 if (FinalLoc.isValid())
16291 Record->addAttr(FinalAttr::Create(
16292 Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16293 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16294
16295 // C++ [class]p2:
16296 // [...] The class-name is also inserted into the scope of the
16297 // class itself; this is known as the injected-class-name. For
16298 // purposes of access checking, the injected-class-name is treated
16299 // as if it were a public member name.
16300 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16301 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16302 Record->getLocation(), Record->getIdentifier(),
16303 /*PrevDecl=*/nullptr,
16304 /*DelayTypeCreation=*/true);
16305 Context.getTypeDeclType(InjectedClassName, Record);
16306 InjectedClassName->setImplicit();
16307 InjectedClassName->setAccess(AS_public);
16308 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16309 InjectedClassName->setDescribedClassTemplate(Template);
16310 PushOnScopeChains(InjectedClassName, S);
16311 assert(InjectedClassName->isInjectedClassName() &&((InjectedClassName->isInjectedClassName() && "Broken injected-class-name"
) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 16312, __PRETTY_FUNCTION__))
16312 "Broken injected-class-name")((InjectedClassName->isInjectedClassName() && "Broken injected-class-name"
) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 16312, __PRETTY_FUNCTION__))
;
16313}
16314
16315void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16316 SourceRange BraceRange) {
16317 AdjustDeclIfTemplate(TagD);
16318 TagDecl *Tag = cast<TagDecl>(TagD);
16319 Tag->setBraceRange(BraceRange);
16320
16321 // Make sure we "complete" the definition even it is invalid.
16322 if (Tag->isBeingDefined()) {
16323 assert(Tag->isInvalidDecl() && "We should already have completed it")((Tag->isInvalidDecl() && "We should already have completed it"
) ? static_cast<void> (0) : __assert_fail ("Tag->isInvalidDecl() && \"We should already have completed it\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 16323, __PRETTY_FUNCTION__))
;
16324 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16325 RD->completeDefinition();
16326 }
16327
16328 if (isa<CXXRecordDecl>(Tag)) {
16329 FieldCollector->FinishClass();
16330 }
16331
16332 // Exit this scope of this tag's definition.
16333 PopDeclContext();
16334
16335 if (getCurLexicalContext()->isObjCContainer() &&
16336 Tag->getDeclContext()->isFileContext())
16337 Tag->setTopLevelDeclInObjCContainer();
16338
16339 // Notify the consumer that we've defined a tag.
16340 if (!Tag->isInvalidDecl())
16341 Consumer.HandleTagDeclDefinition(Tag);
16342}
16343
16344void Sema::ActOnObjCContainerFinishDefinition() {
16345 // Exit this scope of this interface definition.
16346 PopDeclContext();
16347}
16348
16349void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16350 assert(DC == CurContext && "Mismatch of container contexts")((DC == CurContext && "Mismatch of container contexts"
) ? static_cast<void> (0) : __assert_fail ("DC == CurContext && \"Mismatch of container contexts\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 16350, __PRETTY_FUNCTION__))
;
16351 OriginalLexicalContext = DC;
16352 ActOnObjCContainerFinishDefinition();
16353}
16354
16355void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16356 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16357 OriginalLexicalContext = nullptr;
16358}
16359
16360void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16361 AdjustDeclIfTemplate(TagD);
16362 TagDecl *Tag = cast<TagDecl>(TagD);
16363 Tag->setInvalidDecl();
16364
16365 // Make sure we "complete" the definition even it is invalid.
16366 if (Tag->isBeingDefined()) {
16367 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16368 RD->completeDefinition();
16369 }
16370
16371 // We're undoing ActOnTagStartDefinition here, not
16372 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16373 // the FieldCollector.
16374
16375 PopDeclContext();
16376}
16377
16378// Note that FieldName may be null for anonymous bitfields.
16379ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16380 IdentifierInfo *FieldName,
16381 QualType FieldTy, bool IsMsStruct,
16382 Expr *BitWidth, bool *ZeroWidth) {
16383 assert(BitWidth)((BitWidth) ? static_cast<void> (0) : __assert_fail ("BitWidth"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 16383, __PRETTY_FUNCTION__))
;
16384 if (BitWidth->containsErrors())
16385 return ExprError();
16386
16387 // Default to true; that shouldn't confuse checks for emptiness
16388 if (ZeroWidth)
16389 *ZeroWidth = true;
16390
16391 // C99 6.7.2.1p4 - verify the field type.
16392 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16393 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16394 // Handle incomplete and sizeless types with a specific error.
16395 if (RequireCompleteSizedType(FieldLoc, FieldTy,
16396 diag::err_field_incomplete_or_sizeless))
16397 return ExprError();
16398 if (FieldName)
16399 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16400 << FieldName << FieldTy << BitWidth->getSourceRange();
16401 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16402 << FieldTy << BitWidth->getSourceRange();
16403 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16404 UPPC_BitFieldWidth))
16405 return ExprError();
16406
16407 // If the bit-width is type- or value-dependent, don't try to check
16408 // it now.
16409 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16410 return BitWidth;
16411
16412 llvm::APSInt Value;
16413 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16414 if (ICE.isInvalid())
16415 return ICE;
16416 BitWidth = ICE.get();
16417
16418 if (Value != 0 && ZeroWidth)
16419 *ZeroWidth = false;
16420
16421 // Zero-width bitfield is ok for anonymous field.
16422 if (Value == 0 && FieldName)
16423 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16424
16425 if (Value.isSigned() && Value.isNegative()) {
16426 if (FieldName)
16427 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16428 << FieldName << Value.toString(10);
16429 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16430 << Value.toString(10);
16431 }
16432
16433 // The size of the bit-field must not exceed our maximum permitted object
16434 // size.
16435 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16436 return Diag(FieldLoc, diag::err_bitfield_too_wide)
16437 << !FieldName << FieldName << Value.toString(10);
16438 }
16439
16440 if (!FieldTy->isDependentType()) {
16441 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16442 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16443 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16444
16445 // Over-wide bitfields are an error in C or when using the MSVC bitfield
16446 // ABI.
16447 bool CStdConstraintViolation =
16448 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16449 bool MSBitfieldViolation =
16450 Value.ugt(TypeStorageSize) &&
16451 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16452 if (CStdConstraintViolation || MSBitfieldViolation) {
16453 unsigned DiagWidth =
16454 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16455 if (FieldName)
16456 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16457 << FieldName << Value.toString(10)
16458 << !CStdConstraintViolation << DiagWidth;
16459
16460 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16461 << Value.toString(10) << !CStdConstraintViolation
16462 << DiagWidth;
16463 }
16464
16465 // Warn on types where the user might conceivably expect to get all
16466 // specified bits as value bits: that's all integral types other than
16467 // 'bool'.
16468 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16469 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16470 << FieldName << Value.toString(10)
16471 << (unsigned)TypeWidth;
16472 }
16473 }
16474
16475 return BitWidth;
16476}
16477
16478/// ActOnField - Each field of a C struct/union is passed into this in order
16479/// to create a FieldDecl object for it.
16480Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16481 Declarator &D, Expr *BitfieldWidth) {
16482 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16483 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16484 /*InitStyle=*/ICIS_NoInit, AS_public);
16485 return Res;
16486}
16487
16488/// HandleField - Analyze a field of a C struct or a C++ data member.
16489///
16490FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16491 SourceLocation DeclStart,
16492 Declarator &D, Expr *BitWidth,
16493 InClassInitStyle InitStyle,
16494 AccessSpecifier AS) {
16495 if (D.isDecompositionDeclarator()) {
16496 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16497 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16498 << Decomp.getSourceRange();
16499 return nullptr;
16500 }
16501
16502 IdentifierInfo *II = D.getIdentifier();
16503 SourceLocation Loc = DeclStart;
16504 if (II) Loc = D.getIdentifierLoc();
16505
16506 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16507 QualType T = TInfo->getType();
16508 if (getLangOpts().CPlusPlus) {
16509 CheckExtraCXXDefaultArguments(D);
16510
16511 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16512 UPPC_DataMemberType)) {
16513 D.setInvalidType();
16514 T = Context.IntTy;
16515 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16516 }
16517 }
16518
16519 DiagnoseFunctionSpecifiers(D.getDeclSpec());
16520
16521 if (D.getDeclSpec().isInlineSpecified())
16522 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16523 << getLangOpts().CPlusPlus17;
16524 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16525 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16526 diag::err_invalid_thread)
16527 << DeclSpec::getSpecifierName(TSCS);
16528
16529 // Check to see if this name was declared as a member previously
16530 NamedDecl *PrevDecl = nullptr;
16531 LookupResult Previous(*this, II, Loc, LookupMemberName,
16532 ForVisibleRedeclaration);
16533 LookupName(Previous, S);
16534 switch (Previous.getResultKind()) {
16535 case LookupResult::Found:
16536 case LookupResult::FoundUnresolvedValue:
16537 PrevDecl = Previous.getAsSingle<NamedDecl>();
16538 break;
16539
16540 case LookupResult::FoundOverloaded:
16541 PrevDecl = Previous.getRepresentativeDecl();
16542 break;
16543
16544 case LookupResult::NotFound:
16545 case LookupResult::NotFoundInCurrentInstantiation:
16546 case LookupResult::Ambiguous:
16547 break;
16548 }
16549 Previous.suppressDiagnostics();
16550
16551 if (PrevDecl && PrevDecl->isTemplateParameter()) {
16552 // Maybe we will complain about the shadowed template parameter.
16553 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16554 // Just pretend that we didn't see the previous declaration.
16555 PrevDecl = nullptr;
16556 }
16557
16558 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16559 PrevDecl = nullptr;
16560
16561 bool Mutable
16562 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16563 SourceLocation TSSL = D.getBeginLoc();
16564 FieldDecl *NewFD
16565 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16566 TSSL, AS, PrevDecl, &D);
16567
16568 if (NewFD->isInvalidDecl())
16569 Record->setInvalidDecl();
16570
16571 if (D.getDeclSpec().isModulePrivateSpecified())
16572 NewFD->setModulePrivate();
16573
16574 if (NewFD->isInvalidDecl() && PrevDecl) {
16575 // Don't introduce NewFD into scope; there's already something
16576 // with the same name in the same scope.
16577 } else if (II) {
16578 PushOnScopeChains(NewFD, S);
16579 } else
16580 Record->addDecl(NewFD);
16581
16582 return NewFD;
16583}
16584
16585/// Build a new FieldDecl and check its well-formedness.
16586///
16587/// This routine builds a new FieldDecl given the fields name, type,
16588/// record, etc. \p PrevDecl should refer to any previous declaration
16589/// with the same name and in the same scope as the field to be
16590/// created.
16591///
16592/// \returns a new FieldDecl.
16593///
16594/// \todo The Declarator argument is a hack. It will be removed once
16595FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16596 TypeSourceInfo *TInfo,
16597 RecordDecl *Record, SourceLocation Loc,
16598 bool Mutable, Expr *BitWidth,
16599 InClassInitStyle InitStyle,
16600 SourceLocation TSSL,
16601 AccessSpecifier AS, NamedDecl *PrevDecl,
16602 Declarator *D) {
16603 IdentifierInfo *II = Name.getAsIdentifierInfo();
16604 bool InvalidDecl = false;
16605 if (D) InvalidDecl = D->isInvalidType();
16606
16607 // If we receive a broken type, recover by assuming 'int' and
16608 // marking this declaration as invalid.
16609 if (T.isNull() || T->containsErrors()) {
16610 InvalidDecl = true;
16611 T = Context.IntTy;
16612 }
16613
16614 QualType EltTy = Context.getBaseElementType(T);
16615 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16616 if (RequireCompleteSizedType(Loc, EltTy,
16617 diag::err_field_incomplete_or_sizeless)) {
16618 // Fields of incomplete type force their record to be invalid.
16619 Record->setInvalidDecl();
16620 InvalidDecl = true;
16621 } else {
16622 NamedDecl *Def;
16623 EltTy->isIncompleteType(&Def);
16624 if (Def && Def->isInvalidDecl()) {
16625 Record->setInvalidDecl();
16626 InvalidDecl = true;
16627 }
16628 }
16629 }
16630
16631 // TR 18037 does not allow fields to be declared with address space
16632 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16633 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16634 Diag(Loc, diag::err_field_with_address_space);
16635 Record->setInvalidDecl();
16636 InvalidDecl = true;
16637 }
16638
16639 if (LangOpts.OpenCL) {
16640 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16641 // used as structure or union field: image, sampler, event or block types.
16642 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16643 T->isBlockPointerType()) {
16644 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16645 Record->setInvalidDecl();
16646 InvalidDecl = true;
16647 }
16648 // OpenCL v1.2 s6.9.c: bitfields are not supported.
16649 if (BitWidth) {
16650 Diag(Loc, diag::err_opencl_bitfields);
16651 InvalidDecl = true;
16652 }
16653 }
16654
16655 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16656 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16657 T.hasQualifiers()) {
16658 InvalidDecl = true;
16659 Diag(Loc, diag::err_anon_bitfield_qualifiers);
16660 }
16661
16662 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16663 // than a variably modified type.
16664 if (!InvalidDecl && T->isVariablyModifiedType()) {
16665 bool SizeIsNegative;
16666 llvm::APSInt Oversized;
16667
16668 TypeSourceInfo *FixedTInfo =
16669 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16670 SizeIsNegative,
16671 Oversized);
16672 if (FixedTInfo) {
16673 Diag(Loc, diag::ext_vla_folded_to_constant);
16674 TInfo = FixedTInfo;
16675 T = FixedTInfo->getType();
16676 } else {
16677 if (SizeIsNegative)
16678 Diag(Loc, diag::err_typecheck_negative_array_size);
16679 else if (Oversized.getBoolValue())
16680 Diag(Loc, diag::err_array_too_large)
16681 << Oversized.toString(10);
16682 else
16683 Diag(Loc, diag::err_typecheck_field_variable_size);
16684 InvalidDecl = true;
16685 }
16686 }
16687
16688 // Fields can not have abstract class types
16689 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16690 diag::err_abstract_type_in_decl,
16691 AbstractFieldType))
16692 InvalidDecl = true;
16693
16694 bool ZeroWidth = false;
16695 if (InvalidDecl)
16696 BitWidth = nullptr;
16697 // If this is declared as a bit-field, check the bit-field.
16698 if (BitWidth) {
16699 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16700 &ZeroWidth).get();
16701 if (!BitWidth) {
16702 InvalidDecl = true;
16703 BitWidth = nullptr;
16704 ZeroWidth = false;
16705 }
16706 }
16707
16708 // Check that 'mutable' is consistent with the type of the declaration.
16709 if (!InvalidDecl && Mutable) {
16710 unsigned DiagID = 0;
16711 if (T->isReferenceType())
16712 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16713 : diag::err_mutable_reference;
16714 else if (T.isConstQualified())
16715 DiagID = diag::err_mutable_const;
16716
16717 if (DiagID) {
16718 SourceLocation ErrLoc = Loc;
16719 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16720 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16721 Diag(ErrLoc, DiagID);
16722 if (DiagID != diag::ext_mutable_reference) {
16723 Mutable = false;
16724 InvalidDecl = true;
16725 }
16726 }
16727 }
16728
16729 // C++11 [class.union]p8 (DR1460):
16730 // At most one variant member of a union may have a
16731 // brace-or-equal-initializer.
16732 if (InitStyle != ICIS_NoInit)
16733 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16734
16735 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16736 BitWidth, Mutable, InitStyle);
16737 if (InvalidDecl)
16738 NewFD->setInvalidDecl();
16739
16740 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16741 Diag(Loc, diag::err_duplicate_member) << II;
16742 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16743 NewFD->setInvalidDecl();
16744 }
16745
16746 if (!InvalidDecl && getLangOpts().CPlusPlus) {
16747 if (Record->isUnion()) {
16748 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16749 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16750 if (RDecl->getDefinition()) {
16751 // C++ [class.union]p1: An object of a class with a non-trivial
16752 // constructor, a non-trivial copy constructor, a non-trivial
16753 // destructor, or a non-trivial copy assignment operator
16754 // cannot be a member of a union, nor can an array of such
16755 // objects.
16756 if (CheckNontrivialField(NewFD))
16757 NewFD->setInvalidDecl();
16758 }
16759 }
16760
16761 // C++ [class.union]p1: If a union contains a member of reference type,
16762 // the program is ill-formed, except when compiling with MSVC extensions
16763 // enabled.
16764 if (EltTy->isReferenceType()) {
16765 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16766 diag::ext_union_member_of_reference_type :
16767 diag::err_union_member_of_reference_type)
16768 << NewFD->getDeclName() << EltTy;
16769 if (!getLangOpts().MicrosoftExt)
16770 NewFD->setInvalidDecl();
16771 }
16772 }
16773 }
16774
16775 // FIXME: We need to pass in the attributes given an AST
16776 // representation, not a parser representation.
16777 if (D) {
16778 // FIXME: The current scope is almost... but not entirely... correct here.
16779 ProcessDeclAttributes(getCurScope(), NewFD, *D);
16780
16781 if (NewFD->hasAttrs())
16782 CheckAlignasUnderalignment(NewFD);
16783 }
16784
16785 // In auto-retain/release, infer strong retension for fields of
16786 // retainable type.
16787 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16788 NewFD->setInvalidDecl();
16789
16790 if (T.isObjCGCWeak())
16791 Diag(Loc, diag::warn_attribute_weak_on_field);
16792
16793 // PPC MMA non-pointer types are not allowed as field types.
16794 if (Context.getTargetInfo().getTriple().isPPC64() &&
16795 CheckPPCMMAType(T, NewFD->getLocation()))
16796 NewFD->setInvalidDecl();
16797
16798 NewFD->setAccess(AS);
16799 return NewFD;
16800}
16801
16802bool Sema::CheckNontrivialField(FieldDecl *FD) {
16803 assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 16803, __PRETTY_FUNCTION__))
;
16804 assert(getLangOpts().CPlusPlus && "valid check only for C++")((getLangOpts().CPlusPlus && "valid check only for C++"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 16804, __PRETTY_FUNCTION__))
;
16805
16806 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16807 return false;
16808
16809 QualType EltTy = Context.getBaseElementType(FD->getType());
16810 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16811 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16812 if (RDecl->getDefinition()) {
16813 // We check for copy constructors before constructors
16814 // because otherwise we'll never get complaints about
16815 // copy constructors.
16816
16817 CXXSpecialMember member = CXXInvalid;
16818 // We're required to check for any non-trivial constructors. Since the
16819 // implicit default constructor is suppressed if there are any
16820 // user-declared constructors, we just need to check that there is a
16821 // trivial default constructor and a trivial copy constructor. (We don't
16822 // worry about move constructors here, since this is a C++98 check.)
16823 if (RDecl->hasNonTrivialCopyConstructor())
16824 member = CXXCopyConstructor;
16825 else if (!RDecl->hasTrivialDefaultConstructor())
16826 member = CXXDefaultConstructor;
16827 else if (RDecl->hasNonTrivialCopyAssignment())
16828 member = CXXCopyAssignment;
16829 else if (RDecl->hasNonTrivialDestructor())
16830 member = CXXDestructor;
16831
16832 if (member != CXXInvalid) {
16833 if (!getLangOpts().CPlusPlus11 &&
16834 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16835 // Objective-C++ ARC: it is an error to have a non-trivial field of
16836 // a union. However, system headers in Objective-C programs
16837 // occasionally have Objective-C lifetime objects within unions,
16838 // and rather than cause the program to fail, we make those
16839 // members unavailable.
16840 SourceLocation Loc = FD->getLocation();
16841 if (getSourceManager().isInSystemHeader(Loc)) {
16842 if (!FD->hasAttr<UnavailableAttr>())
16843 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16844 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16845 return false;
16846 }
16847 }
16848
16849 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16850 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16851 diag::err_illegal_union_or_anon_struct_member)
16852 << FD->getParent()->isUnion() << FD->getDeclName() << member;
16853 DiagnoseNontrivial(RDecl, member);
16854 return !getLangOpts().CPlusPlus11;
16855 }
16856 }
16857 }
16858
16859 return false;
16860}
16861
16862/// TranslateIvarVisibility - Translate visibility from a token ID to an
16863/// AST enum value.
16864static ObjCIvarDecl::AccessControl
16865TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16866 switch (ivarVisibility) {
16867 default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind"
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 16867)
;
16868 case tok::objc_private: return ObjCIvarDecl::Private;
16869 case tok::objc_public: return ObjCIvarDecl::Public;
16870 case tok::objc_protected: return ObjCIvarDecl::Protected;
16871 case tok::objc_package: return ObjCIvarDecl::Package;
16872 }
16873}
16874
16875/// ActOnIvar - Each ivar field of an objective-c class is passed into this
16876/// in order to create an IvarDecl object for it.
16877Decl *Sema::ActOnIvar(Scope *S,
16878 SourceLocation DeclStart,
16879 Declarator &D, Expr *BitfieldWidth,
16880 tok::ObjCKeywordKind Visibility) {
16881
16882 IdentifierInfo *II = D.getIdentifier();
16883 Expr *BitWidth = (Expr*)BitfieldWidth;
16884 SourceLocation Loc = DeclStart;
16885 if (II) Loc = D.getIdentifierLoc();
16886
16887 // FIXME: Unnamed fields can be handled in various different ways, for
16888 // example, unnamed unions inject all members into the struct namespace!
16889
16890 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16891 QualType T = TInfo->getType();
16892
16893 if (BitWidth) {
16894 // 6.7.2.1p3, 6.7.2.1p4
16895 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16896 if (!BitWidth)
16897 D.setInvalidType();
16898 } else {
16899 // Not a bitfield.
16900
16901 // validate II.
16902
16903 }
16904 if (T->isReferenceType()) {
16905 Diag(Loc, diag::err_ivar_reference_type);
16906 D.setInvalidType();
16907 }
16908 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16909 // than a variably modified type.
16910 else if (T->isVariablyModifiedType()) {
16911 Diag(Loc, diag::err_typecheck_ivar_variable_size);
16912 D.setInvalidType();
16913 }
16914
16915 // Get the visibility (access control) for this ivar.
16916 ObjCIvarDecl::AccessControl ac =
16917 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16918 : ObjCIvarDecl::None;
16919 // Must set ivar's DeclContext to its enclosing interface.
16920 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16921 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16922 return nullptr;
16923 ObjCContainerDecl *EnclosingContext;
16924 if (ObjCImplementationDecl *IMPDecl =
16925 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16926 if (LangOpts.ObjCRuntime.isFragile()) {
16927 // Case of ivar declared in an implementation. Context is that of its class.
16928 EnclosingContext = IMPDecl->getClassInterface();
16929 assert(EnclosingContext && "Implementation has no class interface!")((EnclosingContext && "Implementation has no class interface!"
) ? static_cast<void> (0) : __assert_fail ("EnclosingContext && \"Implementation has no class interface!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 16929, __PRETTY_FUNCTION__))
;
16930 }
16931 else
16932 EnclosingContext = EnclosingDecl;
16933 } else {
16934 if (ObjCCategoryDecl *CDecl =
16935 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16936 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16937 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16938 return nullptr;
16939 }
16940 }
16941 EnclosingContext = EnclosingDecl;
16942 }
16943
16944 // Construct the decl.
16945 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16946 DeclStart, Loc, II, T,
16947 TInfo, ac, (Expr *)BitfieldWidth);
16948
16949 if (II) {
16950 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16951 ForVisibleRedeclaration);
16952 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16953 && !isa<TagDecl>(PrevDecl)) {
16954 Diag(Loc, diag::err_duplicate_member) << II;
16955 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16956 NewID->setInvalidDecl();
16957 }
16958 }
16959
16960 // Process attributes attached to the ivar.
16961 ProcessDeclAttributes(S, NewID, D);
16962
16963 if (D.isInvalidType())
16964 NewID->setInvalidDecl();
16965
16966 // In ARC, infer 'retaining' for ivars of retainable type.
16967 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16968 NewID->setInvalidDecl();
16969
16970 if (D.getDeclSpec().isModulePrivateSpecified())
16971 NewID->setModulePrivate();
16972
16973 if (II) {
16974 // FIXME: When interfaces are DeclContexts, we'll need to add
16975 // these to the interface.
16976 S->AddDecl(NewID);
16977 IdResolver.AddDecl(NewID);
16978 }
16979
16980 if (LangOpts.ObjCRuntime.isNonFragile() &&
16981 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16982 Diag(Loc, diag::warn_ivars_in_interface);
16983
16984 return NewID;
16985}
16986
16987/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16988/// class and class extensions. For every class \@interface and class
16989/// extension \@interface, if the last ivar is a bitfield of any type,
16990/// then add an implicit `char :0` ivar to the end of that interface.
16991void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16992 SmallVectorImpl<Decl *> &AllIvarDecls) {
16993 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16994 return;
16995
16996 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16997 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16998
16999 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17000 return;
17001 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17002 if (!ID) {
17003 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17004 if (!CD->IsClassExtension())
17005 return;
17006 }
17007 // No need to add this to end of @implementation.
17008 else
17009 return;
17010 }
17011 // All conditions are met. Add a new bitfield to the tail end of ivars.
17012 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17013 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17014
17015 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17016 DeclLoc, DeclLoc, nullptr,
17017 Context.CharTy,
17018 Context.getTrivialTypeSourceInfo(Context.CharTy,
17019 DeclLoc),
17020 ObjCIvarDecl::Private, BW,
17021 true);
17022 AllIvarDecls.push_back(Ivar);
17023}
17024
17025void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17026 ArrayRef<Decl *> Fields, SourceLocation LBrac,
17027 SourceLocation RBrac,
17028 const ParsedAttributesView &Attrs) {
17029 assert(EnclosingDecl && "missing record or interface decl")((EnclosingDecl && "missing record or interface decl"
) ? static_cast<void> (0) : __assert_fail ("EnclosingDecl && \"missing record or interface decl\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 17029, __PRETTY_FUNCTION__))
;
17030
17031 // If this is an Objective-C @implementation or category and we have
17032 // new fields here we should reset the layout of the interface since
17033 // it will now change.
17034 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17035 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17036 switch (DC->getKind()) {
17037 default: break;
17038 case Decl::ObjCCategory:
17039 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17040 break;
17041 case Decl::ObjCImplementation:
17042 Context.
17043 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17044 break;
17045 }
17046 }
17047
17048 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17049 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17050
17051 // Start counting up the number of named members; make sure to include
17052 // members of anonymous structs and unions in the total.
17053 unsigned NumNamedMembers = 0;
17054 if (Record) {
17055 for (const auto *I : Record->decls()) {
17056 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17057 if (IFD->getDeclName())
17058 ++NumNamedMembers;
17059 }
17060 }
17061
17062 // Verify that all the fields are okay.
17063 SmallVector<FieldDecl*, 32> RecFields;
17064
17065 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17066 i != end; ++i) {
17067 FieldDecl *FD = cast<FieldDecl>(*i);
17068
17069 // Get the type for the field.
17070 const Type *FDTy = FD->getType().getTypePtr();
17071
17072 if (!FD->isAnonymousStructOrUnion()) {
17073 // Remember all fields written by the user.
17074 RecFields.push_back(FD);
17075 }
17076
17077 // If the field is already invalid for some reason, don't emit more
17078 // diagnostics about it.
17079 if (FD->isInvalidDecl()) {
17080 EnclosingDecl->setInvalidDecl();
17081 continue;
17082 }
17083
17084 // C99 6.7.2.1p2:
17085 // A structure or union shall not contain a member with
17086 // incomplete or function type (hence, a structure shall not
17087 // contain an instance of itself, but may contain a pointer to
17088 // an instance of itself), except that the last member of a
17089 // structure with more than one named member may have incomplete
17090 // array type; such a structure (and any union containing,
17091 // possibly recursively, a member that is such a structure)
17092 // shall not be a member of a structure or an element of an
17093 // array.
17094 bool IsLastField = (i + 1 == Fields.end());
17095 if (FDTy->isFunctionType()) {
17096 // Field declared as a function.
17097 Diag(FD->getLocation(), diag::err_field_declared_as_function)
17098 << FD->getDeclName();
17099 FD->setInvalidDecl();
17100 EnclosingDecl->setInvalidDecl();
17101 continue;
17102 } else if (FDTy->isIncompleteArrayType() &&
17103 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17104 if (Record) {
17105 // Flexible array member.
17106 // Microsoft and g++ is more permissive regarding flexible array.
17107 // It will accept flexible array in union and also
17108 // as the sole element of a struct/class.
17109 unsigned DiagID = 0;
17110 if (!Record->isUnion() && !IsLastField) {
17111 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17112 << FD->getDeclName() << FD->getType() << Record->getTagKind();
17113 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17114 FD->setInvalidDecl();
17115 EnclosingDecl->setInvalidDecl();
17116 continue;
17117 } else if (Record->isUnion())
17118 DiagID = getLangOpts().MicrosoftExt
17119 ? diag::ext_flexible_array_union_ms
17120 : getLangOpts().CPlusPlus
17121 ? diag::ext_flexible_array_union_gnu
17122 : diag::err_flexible_array_union;
17123 else if (NumNamedMembers < 1)
17124 DiagID = getLangOpts().MicrosoftExt
17125 ? diag::ext_flexible_array_empty_aggregate_ms
17126 : getLangOpts().CPlusPlus
17127 ? diag::ext_flexible_array_empty_aggregate_gnu
17128 : diag::err_flexible_array_empty_aggregate;
17129
17130 if (DiagID)
17131 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17132 << Record->getTagKind();
17133 // While the layout of types that contain virtual bases is not specified
17134 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17135 // virtual bases after the derived members. This would make a flexible
17136 // array member declared at the end of an object not adjacent to the end
17137 // of the type.
17138 if (CXXRecord && CXXRecord->getNumVBases() != 0)
17139 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17140 << FD->getDeclName() << Record->getTagKind();
17141 if (!getLangOpts().C99)
17142 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17143 << FD->getDeclName() << Record->getTagKind();
17144
17145 // If the element type has a non-trivial destructor, we would not
17146 // implicitly destroy the elements, so disallow it for now.
17147 //
17148 // FIXME: GCC allows this. We should probably either implicitly delete
17149 // the destructor of the containing class, or just allow this.
17150 QualType BaseElem = Context.getBaseElementType(FD->getType());
17151 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17152 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17153 << FD->getDeclName() << FD->getType();
17154 FD->setInvalidDecl();
17155 EnclosingDecl->setInvalidDecl();
17156 continue;
17157 }
17158 // Okay, we have a legal flexible array member at the end of the struct.
17159 Record->setHasFlexibleArrayMember(true);
17160 } else {
17161 // In ObjCContainerDecl ivars with incomplete array type are accepted,
17162 // unless they are followed by another ivar. That check is done
17163 // elsewhere, after synthesized ivars are known.
17164 }
17165 } else if (!FDTy->isDependentType() &&
17166 RequireCompleteSizedType(
17167 FD->getLocation(), FD->getType(),
17168 diag::err_field_incomplete_or_sizeless)) {
17169 // Incomplete type
17170 FD->setInvalidDecl();
17171 EnclosingDecl->setInvalidDecl();
17172 continue;
17173 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17174 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17175 // A type which contains a flexible array member is considered to be a
17176 // flexible array member.
17177 Record->setHasFlexibleArrayMember(true);
17178 if (!Record->isUnion()) {
17179 // If this is a struct/class and this is not the last element, reject
17180 // it. Note that GCC supports variable sized arrays in the middle of
17181 // structures.
17182 if (!IsLastField)
17183 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17184 << FD->getDeclName() << FD->getType();
17185 else {
17186 // We support flexible arrays at the end of structs in
17187 // other structs as an extension.
17188 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17189 << FD->getDeclName();
17190 }
17191 }
17192 }
17193 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17194 RequireNonAbstractType(FD->getLocation(), FD->getType(),
17195 diag::err_abstract_type_in_decl,
17196 AbstractIvarType)) {
17197 // Ivars can not have abstract class types
17198 FD->setInvalidDecl();
17199 }
17200 if (Record && FDTTy->getDecl()->hasObjectMember())
17201 Record->setHasObjectMember(true);
17202 if (Record && FDTTy->getDecl()->hasVolatileMember())
17203 Record->setHasVolatileMember(true);
17204 } else if (FDTy->isObjCObjectType()) {
17205 /// A field cannot be an Objective-c object
17206 Diag(FD->getLocation(), diag::err_statically_allocated_object)
17207 << FixItHint::CreateInsertion(FD->getLocation(), "*");
17208 QualType T = Context.getObjCObjectPointerType(FD->getType());
17209 FD->setType(T);
17210 } else if (Record && Record->isUnion() &&
17211 FD->getType().hasNonTrivialObjCLifetime() &&
17212 getSourceManager().isInSystemHeader(FD->getLocation()) &&
17213 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17214 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17215 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17216 // For backward compatibility, fields of C unions declared in system
17217 // headers that have non-trivial ObjC ownership qualifications are marked
17218 // as unavailable unless the qualifier is explicit and __strong. This can
17219 // break ABI compatibility between programs compiled with ARC and MRR, but
17220 // is a better option than rejecting programs using those unions under
17221 // ARC.
17222 FD->addAttr(UnavailableAttr::CreateImplicit(
17223 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17224 FD->getLocation()));
17225 } else if (getLangOpts().ObjC &&
17226 getLangOpts().getGC() != LangOptions::NonGC && Record &&
17227 !Record->hasObjectMember()) {
17228 if (FD->getType()->isObjCObjectPointerType() ||
17229 FD->getType().isObjCGCStrong())
17230 Record->setHasObjectMember(true);
17231 else if (Context.getAsArrayType(FD->getType())) {
17232 QualType BaseType = Context.getBaseElementType(FD->getType());
17233 if (BaseType->isRecordType() &&
17234 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17235 Record->setHasObjectMember(true);
17236 else if (BaseType->isObjCObjectPointerType() ||
17237 BaseType.isObjCGCStrong())
17238 Record->setHasObjectMember(true);
17239 }
17240 }
17241
17242 if (Record && !getLangOpts().CPlusPlus &&
17243 !shouldIgnoreForRecordTriviality(FD)) {
17244 QualType FT = FD->getType();
17245 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17246 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17247 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17248 Record->isUnion())
17249 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17250 }
17251 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17252 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17253 Record->setNonTrivialToPrimitiveCopy(true);
17254 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17255 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17256 }
17257 if (FT.isDestructedType()) {
17258 Record->setNonTrivialToPrimitiveDestroy(true);
17259 Record->setParamDestroyedInCallee(true);
17260 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17261 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17262 }
17263
17264 if (const auto *RT = FT->getAs<RecordType>()) {
17265 if (RT->getDecl()->getArgPassingRestrictions() ==
17266 RecordDecl::APK_CanNeverPassInRegs)
17267 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17268 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17269 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17270 }
17271
17272 if (Record && FD->getType().isVolatileQualified())
17273 Record->setHasVolatileMember(true);
17274 // Keep track of the number of named members.
17275 if (FD->getIdentifier())
17276 ++NumNamedMembers;
17277 }
17278
17279 // Okay, we successfully defined 'Record'.
17280 if (Record) {
17281 bool Completed = false;
17282 if (CXXRecord) {
17283 if (!CXXRecord->isInvalidDecl()) {
17284 // Set access bits correctly on the directly-declared conversions.
17285 for (CXXRecordDecl::conversion_iterator
17286 I = CXXRecord->conversion_begin(),
17287 E = CXXRecord->conversion_end(); I != E; ++I)
17288 I.setAccess((*I)->getAccess());
17289 }
17290
17291 // Add any implicitly-declared members to this class.
17292 AddImplicitlyDeclaredMembersToClass(CXXRecord);
17293
17294 if (!CXXRecord->isDependentType()) {
17295 if (!CXXRecord->isInvalidDecl()) {
17296 // If we have virtual base classes, we may end up finding multiple
17297 // final overriders for a given virtual function. Check for this
17298 // problem now.
17299 if (CXXRecord->getNumVBases()) {
17300 CXXFinalOverriderMap FinalOverriders;
17301 CXXRecord->getFinalOverriders(FinalOverriders);
17302
17303 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17304 MEnd = FinalOverriders.end();
17305 M != MEnd; ++M) {
17306 for (OverridingMethods::iterator SO = M->second.begin(),
17307 SOEnd = M->second.end();
17308 SO != SOEnd; ++SO) {
17309 assert(SO->second.size() > 0 &&((SO->second.size() > 0 && "Virtual function without overriding functions?"
) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 17310, __PRETTY_FUNCTION__))
17310 "Virtual function without overriding functions?")((SO->second.size() > 0 && "Virtual function without overriding functions?"
) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 17310, __PRETTY_FUNCTION__))
;
17311 if (SO->second.size() == 1)
17312 continue;
17313
17314 // C++ [class.virtual]p2:
17315 // In a derived class, if a virtual member function of a base
17316 // class subobject has more than one final overrider the
17317 // program is ill-formed.
17318 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17319 << (const NamedDecl *)M->first << Record;
17320 Diag(M->first->getLocation(),
17321 diag::note_overridden_virtual_function);
17322 for (OverridingMethods::overriding_iterator
17323 OM = SO->second.begin(),
17324 OMEnd = SO->second.end();
17325 OM != OMEnd; ++OM)
17326 Diag(OM->Method->getLocation(), diag::note_final_overrider)
17327 << (const NamedDecl *)M->first << OM->Method->getParent();
17328
17329 Record->setInvalidDecl();
17330 }
17331 }
17332 CXXRecord->completeDefinition(&FinalOverriders);
17333 Completed = true;
17334 }
17335 }
17336 }
17337 }
17338
17339 if (!Completed)
17340 Record->completeDefinition();
17341
17342 // Handle attributes before checking the layout.
17343 ProcessDeclAttributeList(S, Record, Attrs);
17344
17345 // We may have deferred checking for a deleted destructor. Check now.
17346 if (CXXRecord) {
17347 auto *Dtor = CXXRecord->getDestructor();
17348 if (Dtor && Dtor->isImplicit() &&
17349 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17350 CXXRecord->setImplicitDestructorIsDeleted();
17351 SetDeclDeleted(Dtor, CXXRecord->getLocation());
17352 }
17353 }
17354
17355 if (Record->hasAttrs()) {
17356 CheckAlignasUnderalignment(Record);
17357
17358 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17359 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17360 IA->getRange(), IA->getBestCase(),
17361 IA->getInheritanceModel());
17362 }
17363
17364 // Check if the structure/union declaration is a type that can have zero
17365 // size in C. For C this is a language extension, for C++ it may cause
17366 // compatibility problems.
17367 bool CheckForZeroSize;
17368 if (!getLangOpts().CPlusPlus) {
17369 CheckForZeroSize = true;
17370 } else {
17371 // For C++ filter out types that cannot be referenced in C code.
17372 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17373 CheckForZeroSize =
17374 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17375 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17376 CXXRecord->isCLike();
17377 }
17378 if (CheckForZeroSize) {
17379 bool ZeroSize = true;
17380 bool IsEmpty = true;
17381 unsigned NonBitFields = 0;
17382 for (RecordDecl::field_iterator I = Record->field_begin(),
17383 E = Record->field_end();
17384 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17385 IsEmpty = false;
17386 if (I->isUnnamedBitfield()) {
17387 if (!I->isZeroLengthBitField(Context))
17388 ZeroSize = false;
17389 } else {
17390 ++NonBitFields;
17391 QualType FieldType = I->getType();
17392 if (FieldType->isIncompleteType() ||
17393 !Context.getTypeSizeInChars(FieldType).isZero())
17394 ZeroSize = false;
17395 }
17396 }
17397
17398 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17399 // allowed in C++, but warn if its declaration is inside
17400 // extern "C" block.
17401 if (ZeroSize) {
17402 Diag(RecLoc, getLangOpts().CPlusPlus ?
17403 diag::warn_zero_size_struct_union_in_extern_c :
17404 diag::warn_zero_size_struct_union_compat)
17405 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17406 }
17407
17408 // Structs without named members are extension in C (C99 6.7.2.1p7),
17409 // but are accepted by GCC.
17410 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17411 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17412 diag::ext_no_named_members_in_struct_union)
17413 << Record->isUnion();
17414 }
17415 }
17416 } else {
17417 ObjCIvarDecl **ClsFields =
17418 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17419 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17420 ID->setEndOfDefinitionLoc(RBrac);
17421 // Add ivar's to class's DeclContext.
17422 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17423 ClsFields[i]->setLexicalDeclContext(ID);
17424 ID->addDecl(ClsFields[i]);
17425 }
17426 // Must enforce the rule that ivars in the base classes may not be
17427 // duplicates.
17428 if (ID->getSuperClass())
17429 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17430 } else if (ObjCImplementationDecl *IMPDecl =
17431 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17432 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")((IMPDecl && "ActOnFields - missing ObjCImplementationDecl"
) ? static_cast<void> (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 17432, __PRETTY_FUNCTION__))
;
17433 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17434 // Ivar declared in @implementation never belongs to the implementation.
17435 // Only it is in implementation's lexical context.
17436 ClsFields[I]->setLexicalDeclContext(IMPDecl);
17437 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17438 IMPDecl->setIvarLBraceLoc(LBrac);
17439 IMPDecl->setIvarRBraceLoc(RBrac);
17440 } else if (ObjCCategoryDecl *CDecl =
17441 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17442 // case of ivars in class extension; all other cases have been
17443 // reported as errors elsewhere.
17444 // FIXME. Class extension does not have a LocEnd field.
17445 // CDecl->setLocEnd(RBrac);
17446 // Add ivar's to class extension's DeclContext.
17447 // Diagnose redeclaration of private ivars.
17448 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17449 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17450 if (IDecl) {
17451 if (const ObjCIvarDecl *ClsIvar =
17452 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17453 Diag(ClsFields[i]->getLocation(),
17454 diag::err_duplicate_ivar_declaration);
17455 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17456 continue;
17457 }
17458 for (const auto *Ext : IDecl->known_extensions()) {
17459 if (const ObjCIvarDecl *ClsExtIvar
17460 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17461 Diag(ClsFields[i]->getLocation(),
17462 diag::err_duplicate_ivar_declaration);
17463 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17464 continue;
17465 }
17466 }
17467 }
17468 ClsFields[i]->setLexicalDeclContext(CDecl);
17469 CDecl->addDecl(ClsFields[i]);
17470 }
17471 CDecl->setIvarLBraceLoc(LBrac);
17472 CDecl->setIvarRBraceLoc(RBrac);
17473 }
17474 }
17475}
17476
17477/// Determine whether the given integral value is representable within
17478/// the given type T.
17479static bool isRepresentableIntegerValue(ASTContext &Context,
17480 llvm::APSInt &Value,
17481 QualType T) {
17482 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 17483, __PRETTY_FUNCTION__))
17483 "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 17483, __PRETTY_FUNCTION__))
;
17484 unsigned BitWidth = Context.getIntWidth(T);
17485
17486 if (Value.isUnsigned() || Value.isNonNegative()) {
17487 if (T->isSignedIntegerOrEnumerationType())
17488 --BitWidth;
17489 return Value.getActiveBits() <= BitWidth;
17490 }
17491 return Value.getMinSignedBits() <= BitWidth;
17492}
17493
17494// Given an integral type, return the next larger integral type
17495// (or a NULL type of no such type exists).
17496static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17497 // FIXME: Int128/UInt128 support, which also needs to be introduced into
17498 // enum checking below.
17499 assert((T->isIntegralType(Context) ||(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 17500, __PRETTY_FUNCTION__))
17500 T->isEnumeralType()) && "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 17500, __PRETTY_FUNCTION__))
;
17501 const unsigned NumTypes = 4;
17502 QualType SignedIntegralTypes[NumTypes] = {
17503 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17504 };
17505 QualType UnsignedIntegralTypes[NumTypes] = {
17506 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17507 Context.UnsignedLongLongTy
17508 };
17509
17510 unsigned BitWidth = Context.getTypeSize(T);
17511 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17512 : UnsignedIntegralTypes;
17513 for (unsigned I = 0; I != NumTypes; ++I)
17514 if (Context.getTypeSize(Types[I]) > BitWidth)
17515 return Types[I];
17516
17517 return QualType();
17518}
17519
17520EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17521 EnumConstantDecl *LastEnumConst,
17522 SourceLocation IdLoc,
17523 IdentifierInfo *Id,
17524 Expr *Val) {
17525 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17526 llvm::APSInt EnumVal(IntWidth);
17527 QualType EltTy;
17528
17529 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17530 Val = nullptr;
17531
17532 if (Val)
17533 Val = DefaultLvalueConversion(Val).get();
17534
17535 if (Val) {
17536 if (Enum->isDependentType() || Val->isTypeDependent())
17537 EltTy = Context.DependentTy;
17538 else {
17539 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17540 // underlying type, but do allow it in all other contexts.
17541 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17542 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17543 // constant-expression in the enumerator-definition shall be a converted
17544 // constant expression of the underlying type.
17545 EltTy = Enum->getIntegerType();
17546 ExprResult Converted =
17547 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17548 CCEK_Enumerator);
17549 if (Converted.isInvalid())
17550 Val = nullptr;
17551 else
17552 Val = Converted.get();
17553 } else if (!Val->isValueDependent() &&
17554 !(Val =
17555 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17556 .get())) {
17557 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17558 } else {
17559 if (Enum->isComplete()) {
17560 EltTy = Enum->getIntegerType();
17561
17562 // In Obj-C and Microsoft mode, require the enumeration value to be
17563 // representable in the underlying type of the enumeration. In C++11,
17564 // we perform a non-narrowing conversion as part of converted constant
17565 // expression checking.
17566 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17567 if (Context.getTargetInfo()
17568 .getTriple()
17569 .isWindowsMSVCEnvironment()) {
17570 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17571 } else {
17572 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17573 }
17574 }
17575
17576 // Cast to the underlying type.
17577 Val = ImpCastExprToType(Val, EltTy,
17578 EltTy->isBooleanType() ? CK_IntegralToBoolean
17579 : CK_IntegralCast)
17580 .get();
17581 } else if (getLangOpts().CPlusPlus) {
17582 // C++11 [dcl.enum]p5:
17583 // If the underlying type is not fixed, the type of each enumerator
17584 // is the type of its initializing value:
17585 // - If an initializer is specified for an enumerator, the
17586 // initializing value has the same type as the expression.
17587 EltTy = Val->getType();
17588 } else {
17589 // C99 6.7.2.2p2:
17590 // The expression that defines the value of an enumeration constant
17591 // shall be an integer constant expression that has a value
17592 // representable as an int.
17593
17594 // Complain if the value is not representable in an int.
17595 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17596 Diag(IdLoc, diag::ext_enum_value_not_int)
17597 << EnumVal.toString(10) << Val->getSourceRange()
17598 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17599 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17600 // Force the type of the expression to 'int'.
17601 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17602 }
17603 EltTy = Val->getType();
17604 }
17605 }
17606 }
17607 }
17608
17609 if (!Val) {
17610 if (Enum->isDependentType())
17611 EltTy = Context.DependentTy;
17612 else if (!LastEnumConst) {
17613 // C++0x [dcl.enum]p5:
17614 // If the underlying type is not fixed, the type of each enumerator
17615 // is the type of its initializing value:
17616 // - If no initializer is specified for the first enumerator, the
17617 // initializing value has an unspecified integral type.
17618 //
17619 // GCC uses 'int' for its unspecified integral type, as does
17620 // C99 6.7.2.2p3.
17621 if (Enum->isFixed()) {
17622 EltTy = Enum->getIntegerType();
17623 }
17624 else {
17625 EltTy = Context.IntTy;
17626 }
17627 } else {
17628 // Assign the last value + 1.
17629 EnumVal = LastEnumConst->getInitVal();
17630 ++EnumVal;
17631 EltTy = LastEnumConst->getType();
17632
17633 // Check for overflow on increment.
17634 if (EnumVal < LastEnumConst->getInitVal()) {
17635 // C++0x [dcl.enum]p5:
17636 // If the underlying type is not fixed, the type of each enumerator
17637 // is the type of its initializing value:
17638 //
17639 // - Otherwise the type of the initializing value is the same as
17640 // the type of the initializing value of the preceding enumerator
17641 // unless the incremented value is not representable in that type,
17642 // in which case the type is an unspecified integral type
17643 // sufficient to contain the incremented value. If no such type
17644 // exists, the program is ill-formed.
17645 QualType T = getNextLargerIntegralType(Context, EltTy);
17646 if (T.isNull() || Enum->isFixed()) {
17647 // There is no integral type larger enough to represent this
17648 // value. Complain, then allow the value to wrap around.
17649 EnumVal = LastEnumConst->getInitVal();
17650 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17651 ++EnumVal;
17652 if (Enum->isFixed())
17653 // When the underlying type is fixed, this is ill-formed.
17654 Diag(IdLoc, diag::err_enumerator_wrapped)
17655 << EnumVal.toString(10)
17656 << EltTy;
17657 else
17658 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17659 << EnumVal.toString(10);
17660 } else {
17661 EltTy = T;
17662 }
17663
17664 // Retrieve the last enumerator's value, extent that type to the
17665 // type that is supposed to be large enough to represent the incremented
17666 // value, then increment.
17667 EnumVal = LastEnumConst->getInitVal();
17668 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17669 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17670 ++EnumVal;
17671
17672 // If we're not in C++, diagnose the overflow of enumerator values,
17673 // which in C99 means that the enumerator value is not representable in
17674 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17675 // permits enumerator values that are representable in some larger
17676 // integral type.
17677 if (!getLangOpts().CPlusPlus && !T.isNull())
17678 Diag(IdLoc, diag::warn_enum_value_overflow);
17679 } else if (!getLangOpts().CPlusPlus &&
17680 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17681 // Enforce C99 6.7.2.2p2 even when we compute the next value.
17682 Diag(IdLoc, diag::ext_enum_value_not_int)
17683 << EnumVal.toString(10) << 1;
17684 }
17685 }
17686 }
17687
17688 if (!EltTy->isDependentType()) {
17689 // Make the enumerator value match the signedness and size of the
17690 // enumerator's type.
17691 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17692 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17693 }
17694
17695 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17696 Val, EnumVal);
17697}
17698
17699Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17700 SourceLocation IILoc) {
17701 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17702 !getLangOpts().CPlusPlus)
17703 return SkipBodyInfo();
17704
17705 // We have an anonymous enum definition. Look up the first enumerator to
17706 // determine if we should merge the definition with an existing one and
17707 // skip the body.
17708 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17709 forRedeclarationInCurContext());
17710 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17711 if (!PrevECD)
17712 return SkipBodyInfo();
17713
17714 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17715 NamedDecl *Hidden;
17716 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17717 SkipBodyInfo Skip;
17718 Skip.Previous = Hidden;
17719 return Skip;
17720 }
17721
17722 return SkipBodyInfo();
17723}
17724
17725Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17726 SourceLocation IdLoc, IdentifierInfo *Id,
17727 const ParsedAttributesView &Attrs,
17728 SourceLocation EqualLoc, Expr *Val) {
17729 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17730 EnumConstantDecl *LastEnumConst =
17731 cast_or_null<EnumConstantDecl>(lastEnumConst);
17732
17733 // The scope passed in may not be a decl scope. Zip up the scope tree until
17734 // we find one that is.
17735 S = getNonFieldDeclScope(S);
17736
17737 // Verify that there isn't already something declared with this name in this
17738 // scope.
17739 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17740 LookupName(R, S);
17741 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17742
17743 if (PrevDecl && PrevDecl->isTemplateParameter()) {
17744 // Maybe we will complain about the shadowed template parameter.
17745 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17746 // Just pretend that we didn't see the previous declaration.
17747 PrevDecl = nullptr;
17748 }
17749
17750 // C++ [class.mem]p15:
17751 // If T is the name of a class, then each of the following shall have a name
17752 // different from T:
17753 // - every enumerator of every member of class T that is an unscoped
17754 // enumerated type
17755 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17756 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17757 DeclarationNameInfo(Id, IdLoc));
17758
17759 EnumConstantDecl *New =
17760 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17761 if (!New)
17762 return nullptr;
17763
17764 if (PrevDecl) {
17765 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17766 // Check for other kinds of shadowing not already handled.
17767 CheckShadow(New, PrevDecl, R);
17768 }
17769
17770 // When in C++, we may get a TagDecl with the same name; in this case the
17771 // enum constant will 'hide' the tag.
17772 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
"Received TagDecl when not in C++!") ? static_cast<void>
(0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 17773, __PRETTY_FUNCTION__))
17773 "Received TagDecl when not in C++!")(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
"Received TagDecl when not in C++!") ? static_cast<void>
(0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 17773, __PRETTY_FUNCTION__))
;
17774 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17775 if (isa<EnumConstantDecl>(PrevDecl))
17776 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17777 else
17778 Diag(IdLoc, diag::err_redefinition) << Id;
17779 notePreviousDefinition(PrevDecl, IdLoc);
17780 return nullptr;
17781 }
17782 }
17783
17784 // Process attributes.
17785 ProcessDeclAttributeList(S, New, Attrs);
17786 AddPragmaAttributes(S, New);
17787
17788 // Register this decl in the current scope stack.
17789 New->setAccess(TheEnumDecl->getAccess());
17790 PushOnScopeChains(New, S);
17791
17792 ActOnDocumentableDecl(New);
17793
17794 return New;
17795}
17796
17797// Returns true when the enum initial expression does not trigger the
17798// duplicate enum warning. A few common cases are exempted as follows:
17799// Element2 = Element1
17800// Element2 = Element1 + 1
17801// Element2 = Element1 - 1
17802// Where Element2 and Element1 are from the same enum.
17803static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17804 Expr *InitExpr = ECD->getInitExpr();
17805 if (!InitExpr)
17806 return true;
17807 InitExpr = InitExpr->IgnoreImpCasts();
17808
17809 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17810 if (!BO->isAdditiveOp())
17811 return true;
17812 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17813 if (!IL)
17814 return true;
17815 if (IL->getValue() != 1)
17816 return true;
17817
17818 InitExpr = BO->getLHS();
17819 }
17820
17821 // This checks if the elements are from the same enum.
17822 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17823 if (!DRE)
17824 return true;
17825
17826 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17827 if (!EnumConstant)
17828 return true;
17829
17830 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17831 Enum)
17832 return true;
17833
17834 return false;
17835}
17836
17837// Emits a warning when an element is implicitly set a value that
17838// a previous element has already been set to.
17839static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17840 EnumDecl *Enum, QualType EnumType) {
17841 // Avoid anonymous enums
17842 if (!Enum->getIdentifier())
17843 return;
17844
17845 // Only check for small enums.
17846 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17847 return;
17848
17849 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17850 return;
17851
17852 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17853 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17854
17855 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17856
17857 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17858 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17859
17860 // Use int64_t as a key to avoid needing special handling for map keys.
17861 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17862 llvm::APSInt Val = D->getInitVal();
17863 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17864 };
17865
17866 DuplicatesVector DupVector;
17867 ValueToVectorMap EnumMap;
17868
17869 // Populate the EnumMap with all values represented by enum constants without
17870 // an initializer.
17871 for (auto *Element : Elements) {
17872 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17873
17874 // Null EnumConstantDecl means a previous diagnostic has been emitted for
17875 // this constant. Skip this enum since it may be ill-formed.
17876 if (!ECD) {
17877 return;
17878 }
17879
17880 // Constants with initalizers are handled in the next loop.
17881 if (ECD->getInitExpr())
17882 continue;
17883
17884 // Duplicate values are handled in the next loop.
17885 EnumMap.insert({EnumConstantToKey(ECD), ECD});
17886 }
17887
17888 if (EnumMap.size() == 0)
17889 return;
17890
17891 // Create vectors for any values that has duplicates.
17892 for (auto *Element : Elements) {
17893 // The last loop returned if any constant was null.
17894 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17895 if (!ValidDuplicateEnum(ECD, Enum))
17896 continue;
17897
17898 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17899 if (Iter == EnumMap.end())
17900 continue;
17901
17902 DeclOrVector& Entry = Iter->second;
17903 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17904 // Ensure constants are different.
17905 if (D == ECD)
17906 continue;
17907
17908 // Create new vector and push values onto it.
17909 auto Vec = std::make_unique<ECDVector>();
17910 Vec->push_back(D);
17911 Vec->push_back(ECD);
17912
17913 // Update entry to point to the duplicates vector.
17914 Entry = Vec.get();
17915
17916 // Store the vector somewhere we can consult later for quick emission of
17917 // diagnostics.
17918 DupVector.emplace_back(std::move(Vec));
17919 continue;
17920 }
17921
17922 ECDVector *Vec = Entry.get<ECDVector*>();
17923 // Make sure constants are not added more than once.
17924 if (*Vec->begin() == ECD)
17925 continue;
17926
17927 Vec->push_back(ECD);
17928 }
17929
17930 // Emit diagnostics.
17931 for (const auto &Vec : DupVector) {
17932 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")((Vec->size() > 1 && "ECDVector should have at least 2 elements."
) ? static_cast<void> (0) : __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 17932, __PRETTY_FUNCTION__))
;
17933
17934 // Emit warning for one enum constant.
17935 auto *FirstECD = Vec->front();
17936 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17937 << FirstECD << FirstECD->getInitVal().toString(10)
17938 << FirstECD->getSourceRange();
17939
17940 // Emit one note for each of the remaining enum constants with
17941 // the same value.
17942 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17943 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17944 << ECD << ECD->getInitVal().toString(10)
17945 << ECD->getSourceRange();
17946 }
17947}
17948
17949bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17950 bool AllowMask) const {
17951 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")((ED->isClosedFlag() && "looking for value in non-flag or open enum"
) ? static_cast<void> (0) : __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 17951, __PRETTY_FUNCTION__))
;
17952 assert(ED->isCompleteDefinition() && "expected enum definition")((ED->isCompleteDefinition() && "expected enum definition"
) ? static_cast<void> (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 17952, __PRETTY_FUNCTION__))
;
17953
17954 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17955 llvm::APInt &FlagBits = R.first->second;
17956
17957 if (R.second) {
17958 for (auto *E : ED->enumerators()) {
17959 const auto &EVal = E->getInitVal();
17960 // Only single-bit enumerators introduce new flag values.
17961 if (EVal.isPowerOf2())
17962 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17963 }
17964 }
17965
17966 // A value is in a flag enum if either its bits are a subset of the enum's
17967 // flag bits (the first condition) or we are allowing masks and the same is
17968 // true of its complement (the second condition). When masks are allowed, we
17969 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17970 //
17971 // While it's true that any value could be used as a mask, the assumption is
17972 // that a mask will have all of the insignificant bits set. Anything else is
17973 // likely a logic error.
17974 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17975 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17976}
17977
17978void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17979 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17980 const ParsedAttributesView &Attrs) {
17981 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17982 QualType EnumType = Context.getTypeDeclType(Enum);
17983
17984 ProcessDeclAttributeList(S, Enum, Attrs);
17985
17986 if (Enum->isDependentType()) {
17987 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17988 EnumConstantDecl *ECD =
17989 cast_or_null<EnumConstantDecl>(Elements[i]);
17990 if (!ECD) continue;
17991
17992 ECD->setType(EnumType);
17993 }
17994
17995 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17996 return;
17997 }
17998
17999 // TODO: If the result value doesn't fit in an int, it must be a long or long
18000 // long value. ISO C does not support this, but GCC does as an extension,
18001 // emit a warning.
18002 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18003 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18004 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18005
18006 // Verify that all the values are okay, compute the size of the values, and
18007 // reverse the list.
18008 unsigned NumNegativeBits = 0;
18009 unsigned NumPositiveBits = 0;
18010
18011 // Keep track of whether all elements have type int.
18012 bool AllElementsInt = true;
18013
18014 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18015 EnumConstantDecl *ECD =
18016 cast_or_null<EnumConstantDecl>(Elements[i]);
18017 if (!ECD) continue; // Already issued a diagnostic.
18018
18019 const llvm::APSInt &InitVal = ECD->getInitVal();
18020
18021 // Keep track of the size of positive and negative values.
18022 if (InitVal.isUnsigned() || InitVal.isNonNegative())
18023 NumPositiveBits = std::max(NumPositiveBits,
18024 (unsigned)InitVal.getActiveBits());
18025 else
18026 NumNegativeBits = std::max(NumNegativeBits,
18027 (unsigned)InitVal.getMinSignedBits());
18028
18029 // Keep track of whether every enum element has type int (very common).
18030 if (AllElementsInt)
18031 AllElementsInt = ECD->getType() == Context.IntTy;
18032 }
18033
18034 // Figure out the type that should be used for this enum.
18035 QualType BestType;
18036 unsigned BestWidth;
18037
18038 // C++0x N3000 [conv.prom]p3:
18039 // An rvalue of an unscoped enumeration type whose underlying
18040 // type is not fixed can be converted to an rvalue of the first
18041 // of the following types that can represent all the values of
18042 // the enumeration: int, unsigned int, long int, unsigned long
18043 // int, long long int, or unsigned long long int.
18044 // C99 6.4.4.3p2:
18045 // An identifier declared as an enumeration constant has type int.
18046 // The C99 rule is modified by a gcc extension
18047 QualType BestPromotionType;
18048
18049 bool Packed = Enum->hasAttr<PackedAttr>();
18050 // -fshort-enums is the equivalent to specifying the packed attribute on all
18051 // enum definitions.
18052 if (LangOpts.ShortEnums)
18053 Packed = true;
18054
18055 // If the enum already has a type because it is fixed or dictated by the
18056 // target, promote that type instead of analyzing the enumerators.
18057 if (Enum->isComplete()) {
18058 BestType = Enum->getIntegerType();
18059 if (BestType->isPromotableIntegerType())
18060 BestPromotionType = Context.getPromotedIntegerType(BestType);
18061 else
18062 BestPromotionType = BestType;
18063
18064 BestWidth = Context.getIntWidth(BestType);
18065 }
18066 else if (NumNegativeBits) {
18067 // If there is a negative value, figure out the smallest integer type (of
18068 // int/long/longlong) that fits.
18069 // If it's packed, check also if it fits a char or a short.
18070 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18071 BestType = Context.SignedCharTy;
18072 BestWidth = CharWidth;
18073 } else if (Packed && NumNegativeBits <= ShortWidth &&
18074 NumPositiveBits < ShortWidth) {
18075 BestType = Context.ShortTy;
18076 BestWidth = ShortWidth;
18077 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18078 BestType = Context.IntTy;
18079 BestWidth = IntWidth;
18080 } else {
18081 BestWidth = Context.getTargetInfo().getLongWidth();
18082
18083 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18084 BestType = Context.LongTy;
18085 } else {
18086 BestWidth = Context.getTargetInfo().getLongLongWidth();
18087
18088 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18089 Diag(Enum->getLocation(), diag::ext_enum_too_large);
18090 BestType = Context.LongLongTy;
18091 }
18092 }
18093 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18094 } else {
18095 // If there is no negative value, figure out the smallest type that fits
18096 // all of the enumerator values.
18097 // If it's packed, check also if it fits a char or a short.
18098 if (Packed && NumPositiveBits <= CharWidth) {
18099 BestType = Context.UnsignedCharTy;
18100 BestPromotionType = Context.IntTy;
18101 BestWidth = CharWidth;
18102 } else if (Packed && NumPositiveBits <= ShortWidth) {
18103 BestType = Context.UnsignedShortTy;
18104 BestPromotionType = Context.IntTy;
18105 BestWidth = ShortWidth;
18106 } else if (NumPositiveBits <= IntWidth) {
18107 BestType = Context.UnsignedIntTy;
18108 BestWidth = IntWidth;
18109 BestPromotionType
18110 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18111 ? Context.UnsignedIntTy : Context.IntTy;
18112 } else if (NumPositiveBits <=
18113 (BestWidth = Context.getTargetInfo().getLongWidth())) {
18114 BestType = Context.UnsignedLongTy;
18115 BestPromotionType
18116 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18117 ? Context.UnsignedLongTy : Context.LongTy;
18118 } else {
18119 BestWidth = Context.getTargetInfo().getLongLongWidth();
18120 assert(NumPositiveBits <= BestWidth &&((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?"
) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 18121, __PRETTY_FUNCTION__))
18121 "How could an initializer get larger than ULL?")((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?"
) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/lib/Sema/SemaDecl.cpp"
, 18121, __PRETTY_FUNCTION__))
;
18122 BestType = Context.UnsignedLongLongTy;
18123 BestPromotionType
18124 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18125 ? Context.UnsignedLongLongTy : Context.LongLongTy;
18126 }
18127 }
18128
18129 // Loop over all of the enumerator constants, changing their types to match
18130 // the type of the enum if needed.
18131 for (auto *D : Elements) {
18132 auto *ECD = cast_or_null<EnumConstantDecl>(D);
18133 if (!ECD) continue; // Already issued a diagnostic.
18134
18135 // Standard C says the enumerators have int type, but we allow, as an
18136 // extension, the enumerators to be larger than int size. If each
18137 // enumerator value fits in an int, type it as an int, otherwise type it the
18138 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
18139 // that X has type 'int', not 'unsigned'.
18140
18141 // Determine whether the value fits into an int.
18142 llvm::APSInt InitVal = ECD->getInitVal();
18143
18144 // If it fits into an integer type, force it. Otherwise force it to match
18145 // the enum decl type.
18146 QualType NewTy;
18147 unsigned NewWidth;
18148 bool NewSign;
18149 if (!getLangOpts().CPlusPlus &&
18150 !Enum->isFixed() &&
18151 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18152 NewTy = Context.IntTy;
18153 NewWidth = IntWidth;
18154 NewSign = true;
18155 } else if (ECD->getType() == BestType) {
18156 // Already the right type!
18157 if (getLangOpts().CPlusPlus)
18158 // C++ [dcl.enum]p4: Following the closing brace of an
18159 // enum-specifier, each enumerator has the type of its
18160 // enumeration.
18161 ECD->setType(EnumType);
18162 continue;
18163 } else {
18164 NewTy = BestType;
18165 NewWidth = BestWidth;
18166 NewSign = BestType->isSignedIntegerOrEnumerationType();
18167 }
18168
18169 // Adjust the APSInt value.
18170 InitVal = InitVal.extOrTrunc(NewWidth);
18171 InitVal.setIsSigned(NewSign);
18172 ECD->setInitVal(InitVal);
18173
18174 // Adjust the Expr initializer and type.
18175 if (ECD->getInitExpr() &&
18176 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18177 ECD->setInitExpr(ImplicitCastExpr::Create(
18178 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18179 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride()));
18180 if (getLangOpts().CPlusPlus)
18181 // C++ [dcl.enum]p4: Following the closing brace of an
18182 // enum-specifier, each enumerator has the type of its
18183 // enumeration.
18184 ECD->setType(EnumType);
18185 else
18186 ECD->setType(NewTy);
18187 }
18188
18189 Enum->completeDefinition(BestType, BestPromotionType,
18190 NumPositiveBits, NumNegativeBits);
18191
18192 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18193
18194 if (Enum->isClosedFlag()) {
18195 for (Decl *D : Elements) {
18196 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18197 if (!ECD) continue; // Already issued a diagnostic.
18198
18199 llvm::APSInt InitVal = ECD->getInitVal();
18200 if (InitVal != 0 && !InitVal.isPowerOf2() &&
18201 !IsValueInFlagEnum(Enum, InitVal, true))
18202 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18203 << ECD << Enum;
18204 }
18205 }
18206
18207 // Now that the enum type is defined, ensure it's not been underaligned.
18208 if (Enum->hasAttrs())
18209 CheckAlignasUnderalignment(Enum);
18210}
18211
18212Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18213 SourceLocation StartLoc,
18214 SourceLocation EndLoc) {
18215 StringLiteral *AsmString = cast<StringLiteral>(expr);
18216
18217 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18218 AsmString, StartLoc,
18219 EndLoc);
18220 CurContext->addDecl(New);
18221 return New;
18222}
18223
18224void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18225 IdentifierInfo* AliasName,
18226 SourceLocation PragmaLoc,
18227 SourceLocation NameLoc,
18228 SourceLocation AliasNameLoc) {
18229 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18230 LookupOrdinaryName);
18231 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18232 AttributeCommonInfo::AS_Pragma);
18233 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18234 Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18235
18236 // If a declaration that:
18237 // 1) declares a function or a variable
18238 // 2) has external linkage
18239 // already exists, add a label attribute to it.
18240 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18241 if (isDeclExternC(PrevDecl))
18242 PrevDecl->addAttr(Attr);
18243 else
18244 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18245 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18246 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18247 } else
18248 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18249}
18250
18251void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18252 SourceLocation PragmaLoc,
18253 SourceLocation NameLoc) {
18254 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18255
18256 if (PrevDecl) {
18257 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18258 } else {
18259 (void)WeakUndeclaredIdentifiers.insert(
18260 std::pair<IdentifierInfo*,WeakInfo>
18261 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18262 }
18263}
18264
18265void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18266 IdentifierInfo* AliasName,
18267 SourceLocation PragmaLoc,
18268 SourceLocation NameLoc,
18269 SourceLocation AliasNameLoc) {
18270 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18271 LookupOrdinaryName);
18272 WeakInfo W = WeakInfo(Name, NameLoc);
18273
18274 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18275 if (!PrevDecl->hasAttr<AliasAttr>())
18276 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18277 DeclApplyPragmaWeak(TUScope, ND, W);
18278 } else {
18279 (void)WeakUndeclaredIdentifiers.insert(
18280 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18281 }
18282}
18283
18284Decl *Sema::getObjCDeclContext() const {
18285 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18286}
18287
18288Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18289 bool Final) {
18290 // SYCL functions can be template, so we check if they have appropriate
18291 // attribute prior to checking if it is a template.
18292 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18293 return FunctionEmissionStatus::Emitted;
18294
18295 // Templates are emitted when they're instantiated.
18296 if (FD->isDependentContext())
18297 return FunctionEmissionStatus::TemplateDiscarded;
18298
18299 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
18300 if (LangOpts.OpenMPIsDevice) {
18301 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18302 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18303 if (DevTy.hasValue()) {
18304 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18305 OMPES = FunctionEmissionStatus::OMPDiscarded;
18306 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
18307 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) {
18308 OMPES = FunctionEmissionStatus::Emitted;
18309 }
18310 }
18311 } else if (LangOpts.OpenMP) {
18312 // In OpenMP 4.5 all the functions are host functions.
18313 if (LangOpts.OpenMP <= 45) {
18314 OMPES = FunctionEmissionStatus::Emitted;
18315 } else {
18316 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18317 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18318 // In OpenMP 5.0 or above, DevTy may be changed later by
18319 // #pragma omp declare target to(*) device_type(*). Therefore DevTy
18320 // having no value does not imply host. The emission status will be
18321 // checked again at the end of compilation unit.
18322 if (DevTy.hasValue()) {
18323 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
18324 OMPES = FunctionEmissionStatus::OMPDiscarded;
18325 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host ||
18326 *DevTy == OMPDeclareTargetDeclAttr::DT_Any)
18327 OMPES = FunctionEmissionStatus::Emitted;
18328 } else if (Final)
18329 OMPES = FunctionEmissionStatus::Emitted;
18330 }
18331 }
18332 if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
18333 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
18334 return OMPES;
18335
18336 if (LangOpts.CUDA) {
18337 // When compiling for device, host functions are never emitted. Similarly,
18338 // when compiling for host, device and global functions are never emitted.
18339 // (Technically, we do emit a host-side stub for global functions, but this
18340 // doesn't count for our purposes here.)
18341 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18342 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18343 return FunctionEmissionStatus::CUDADiscarded;
18344 if (!LangOpts.CUDAIsDevice &&
18345 (T == Sema::CFT_Device || T == Sema::CFT_Global))
18346 return FunctionEmissionStatus::CUDADiscarded;
18347
18348 // Check whether this function is externally visible -- if so, it's
18349 // known-emitted.
18350 //
18351 // We have to check the GVA linkage of the function's *definition* -- if we
18352 // only have a declaration, we don't know whether or not the function will
18353 // be emitted, because (say) the definition could include "inline".
18354 FunctionDecl *Def = FD->getDefinition();
18355
18356 if (Def &&
18357 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
18358 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
18359 return FunctionEmissionStatus::Emitted;
18360 }
18361
18362 // Otherwise, the function is known-emitted if it's in our set of
18363 // known-emitted functions.
18364 return FunctionEmissionStatus::Unknown;
18365}
18366
18367bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18368 // Host-side references to a __global__ function refer to the stub, so the
18369 // function itself is never emitted and therefore should not be marked.
18370 // If we have host fn calls kernel fn calls host+device, the HD function
18371 // does not get instantiated on the host. We model this by omitting at the
18372 // call to the kernel from the callgraph. This ensures that, when compiling
18373 // for host, only HD functions actually called from the host get marked as
18374 // known-emitted.
18375 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18376 IdentifyCUDATarget(Callee) == CFT_Global;
18377}

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

/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/ADT/PointerIntPair.h

1//===- llvm/ADT/PointerIntPair.h - Pair for pointer and int -----*- 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// This file defines the PointerIntPair class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ADT_POINTERINTPAIR_H
14#define LLVM_ADT_POINTERINTPAIR_H
15
16#include "llvm/Support/Compiler.h"
17#include "llvm/Support/PointerLikeTypeTraits.h"
18#include "llvm/Support/type_traits.h"
19#include <cassert>
20#include <cstdint>
21#include <limits>
22
23namespace llvm {
24
25template <typename T> struct DenseMapInfo;
26template <typename PointerT, unsigned IntBits, typename PtrTraits>
27struct PointerIntPairInfo;
28
29/// PointerIntPair - This class implements a pair of a pointer and small
30/// integer. It is designed to represent this in the space required by one
31/// pointer by bitmangling the integer into the low part of the pointer. This
32/// can only be done for small integers: typically up to 3 bits, but it depends
33/// on the number of bits available according to PointerLikeTypeTraits for the
34/// type.
35///
36/// Note that PointerIntPair always puts the IntVal part in the highest bits
37/// possible. For example, PointerIntPair<void*, 1, bool> will put the bit for
38/// the bool into bit #2, not bit #0, which allows the low two bits to be used
39/// for something else. For example, this allows:
40/// PointerIntPair<PointerIntPair<void*, 1, bool>, 1, bool>
41/// ... and the two bools will land in different bits.
42template <typename PointerTy, unsigned IntBits, typename IntType = unsigned,
43 typename PtrTraits = PointerLikeTypeTraits<PointerTy>,
44 typename Info = PointerIntPairInfo<PointerTy, IntBits, PtrTraits>>
45class PointerIntPair {
46 // Used by MSVC visualizer and generally helpful for debugging/visualizing.
47 using InfoTy = Info;
48 intptr_t Value = 0;
49
50public:
51 constexpr PointerIntPair() = default;
52
53 PointerIntPair(PointerTy PtrVal, IntType IntVal) {
54 setPointerAndInt(PtrVal, IntVal);
55 }
56
57 explicit PointerIntPair(PointerTy PtrVal) { initWithPointer(PtrVal); }
58
59 PointerTy getPointer() const { return Info::getPointer(Value); }
60
61 IntType getInt() const { return (IntType)Info::getInt(Value); }
62
63 void setPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION& {
64 Value = Info::updatePointer(Value, PtrVal);
65 }
66
67 void setInt(IntType IntVal) LLVM_LVALUE_FUNCTION& {
68 Value = Info::updateInt(Value, static_cast<intptr_t>(IntVal));
69 }
70
71 void initWithPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION& {
72 Value = Info::updatePointer(0, PtrVal);
73 }
74
75 void setPointerAndInt(PointerTy PtrVal, IntType IntVal) LLVM_LVALUE_FUNCTION& {
76 Value = Info::updateInt(Info::updatePointer(0, PtrVal),
77 static_cast<intptr_t>(IntVal));
78 }
79
80 PointerTy const *getAddrOfPointer() const {
81 return const_cast<PointerIntPair *>(this)->getAddrOfPointer();
82 }
83
84 PointerTy *getAddrOfPointer() {
85 assert(Value == reinterpret_cast<intptr_t>(getPointer()) &&((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __PRETTY_FUNCTION__))
86 "Can only return the address if IntBits is cleared and "((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __PRETTY_FUNCTION__))
87 "PtrTraits doesn't change the pointer")((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __PRETTY_FUNCTION__))
;
88 return reinterpret_cast<PointerTy *>(&Value);
89 }
90
91 void *getOpaqueValue() const { return reinterpret_cast<void *>(Value); }
92
93 void setFromOpaqueValue(void *Val) LLVM_LVALUE_FUNCTION& {
94 Value = reinterpret_cast<intptr_t>(Val);
95 }
96
97 static PointerIntPair getFromOpaqueValue(void *V) {
98 PointerIntPair P;
99 P.setFromOpaqueValue(V);
100 return P;
101 }
102
103 // Allow PointerIntPairs to be created from const void * if and only if the
104 // pointer type could be created from a const void *.
105 static PointerIntPair getFromOpaqueValue(const void *V) {
106 (void)PtrTraits::getFromVoidPointer(V);
107 return getFromOpaqueValue(const_cast<void *>(V));
108 }
109
110 bool operator==(const PointerIntPair &RHS) const {
111 return Value == RHS.Value;
112 }
113
114 bool operator!=(const PointerIntPair &RHS) const {
115 return Value != RHS.Value;
14
Assuming 'Value' is equal to 'RHS.Value'
15
Returning zero, which participates in a condition later
75
Assuming 'Value' is equal to 'RHS.Value'
76
Returning zero, which participates in a condition later
136
Assuming 'Value' is equal to 'RHS.Value'
137
Returning zero, which participates in a condition later
116 }
117
118 bool operator<(const PointerIntPair &RHS) const { return Value < RHS.Value; }
119 bool operator>(const PointerIntPair &RHS) const { return Value > RHS.Value; }
120
121 bool operator<=(const PointerIntPair &RHS) const {
122 return Value <= RHS.Value;
123 }
124
125 bool operator>=(const PointerIntPair &RHS) const {
126 return Value >= RHS.Value;
127 }
128};
129
130// Specialize is_trivially_copyable to avoid limitation of llvm::is_trivially_copyable
131// when compiled with gcc 4.9.
132template <typename PointerTy, unsigned IntBits, typename IntType,
133 typename PtrTraits,
134 typename Info>
135struct is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>> : std::true_type {
136#ifdef HAVE_STD_IS_TRIVIALLY_COPYABLE
137 static_assert(std::is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>>::value,
138 "inconsistent behavior between llvm:: and std:: implementation of is_trivially_copyable");
139#endif
140};
141
142
143template <typename PointerT, unsigned IntBits, typename PtrTraits>
144struct PointerIntPairInfo {
145 static_assert(PtrTraits::NumLowBitsAvailable <
146 std::numeric_limits<uintptr_t>::digits,
147 "cannot use a pointer type that has all bits free");
148 static_assert(IntBits <= PtrTraits::NumLowBitsAvailable,
149 "PointerIntPair with integer size too large for pointer");
150 enum MaskAndShiftConstants : uintptr_t {
151 /// PointerBitMask - The bits that come from the pointer.
152 PointerBitMask =
153 ~(uintptr_t)(((intptr_t)1 << PtrTraits::NumLowBitsAvailable) - 1),
154
155 /// IntShift - The number of low bits that we reserve for other uses, and
156 /// keep zero.
157 IntShift = (uintptr_t)PtrTraits::NumLowBitsAvailable - IntBits,
158
159 /// IntMask - This is the unshifted mask for valid bits of the int type.
160 IntMask = (uintptr_t)(((intptr_t)1 << IntBits) - 1),
161
162 // ShiftedIntMask - This is the bits for the integer shifted in place.
163 ShiftedIntMask = (uintptr_t)(IntMask << IntShift)
164 };
165
166 static PointerT getPointer(intptr_t Value) {
167 return PtrTraits::getFromVoidPointer(
168 reinterpret_cast<void *>(Value & PointerBitMask));
169 }
170
171 static intptr_t getInt(intptr_t Value) {
172 return (Value >> IntShift) & IntMask;
173 }
174
175 static intptr_t updatePointer(intptr_t OrigValue, PointerT Ptr) {
176 intptr_t PtrWord =
177 reinterpret_cast<intptr_t>(PtrTraits::getAsVoidPointer(Ptr));
178 assert((PtrWord & ~PointerBitMask) == 0 &&(((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned"
) ? static_cast<void> (0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/ADT/PointerIntPair.h"
, 179, __PRETTY_FUNCTION__))
179 "Pointer is not sufficiently aligned")(((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned"
) ? static_cast<void> (0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/ADT/PointerIntPair.h"
, 179, __PRETTY_FUNCTION__))
;
180 // Preserve all low bits, just update the pointer.
181 return PtrWord | (OrigValue & ~PointerBitMask);
182 }
183
184 static intptr_t updateInt(intptr_t OrigValue, intptr_t Int) {
185 intptr_t IntWord = static_cast<intptr_t>(Int);
186 assert((IntWord & ~IntMask) == 0 && "Integer too large for field")(((IntWord & ~IntMask) == 0 && "Integer too large for field"
) ? static_cast<void> (0) : __assert_fail ("(IntWord & ~IntMask) == 0 && \"Integer too large for field\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/ADT/PointerIntPair.h"
, 186, __PRETTY_FUNCTION__))
;
187
188 // Preserve all bits other than the ones we are updating.
189 return (OrigValue & ~ShiftedIntMask) | IntWord << IntShift;
190 }
191};
192
193// Provide specialization of DenseMapInfo for PointerIntPair.
194template <typename PointerTy, unsigned IntBits, typename IntType>
195struct DenseMapInfo<PointerIntPair<PointerTy, IntBits, IntType>> {
196 using Ty = PointerIntPair<PointerTy, IntBits, IntType>;
197
198 static Ty getEmptyKey() {
199 uintptr_t Val = static_cast<uintptr_t>(-1);
200 Val <<= PointerLikeTypeTraits<Ty>::NumLowBitsAvailable;
201 return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val));
202 }
203
204 static Ty getTombstoneKey() {
205 uintptr_t Val = static_cast<uintptr_t>(-2);
206 Val <<= PointerLikeTypeTraits<PointerTy>::NumLowBitsAvailable;
207 return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val));
208 }
209
210 static unsigned getHashValue(Ty V) {
211 uintptr_t IV = reinterpret_cast<uintptr_t>(V.getOpaqueValue());
212 return unsigned(IV) ^ unsigned(IV >> 9);
213 }
214
215 static bool isEqual(const Ty &LHS, const Ty &RHS) { return LHS == RHS; }
216};
217
218// Teach SmallPtrSet that PointerIntPair is "basically a pointer".
219template <typename PointerTy, unsigned IntBits, typename IntType,
220 typename PtrTraits>
221struct PointerLikeTypeTraits<
222 PointerIntPair<PointerTy, IntBits, IntType, PtrTraits>> {
223 static inline void *
224 getAsVoidPointer(const PointerIntPair<PointerTy, IntBits, IntType> &P) {
225 return P.getOpaqueValue();
226 }
227
228 static inline PointerIntPair<PointerTy, IntBits, IntType>
229 getFromVoidPointer(void *P) {
230 return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P);
231 }
232
233 static inline PointerIntPair<PointerTy, IntBits, IntType>
234 getFromVoidPointer(const void *P) {
235 return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P);
236 }
237
238 static constexpr int NumLowBitsAvailable =
239 PtrTraits::NumLowBitsAvailable - IntBits;
240};
241
242} // end namespace llvm
243
244#endif // LLVM_ADT_POINTERINTPAIR_H

/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- 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// This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
10// and dyn_cast_or_null<X>() templates.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_CASTING_H
15#define LLVM_SUPPORT_CASTING_H
16
17#include "llvm/Support/Compiler.h"
18#include "llvm/Support/type_traits.h"
19#include <cassert>
20#include <memory>
21#include <type_traits>
22
23namespace llvm {
24
25//===----------------------------------------------------------------------===//
26// isa<x> Support Templates
27//===----------------------------------------------------------------------===//
28
29// Define a template that can be specialized by smart pointers to reflect the
30// fact that they are automatically dereferenced, and are not involved with the
31// template selection process... the default implementation is a noop.
32//
33template<typename From> struct simplify_type {
34 using SimpleType = From; // The real type this represents...
35
36 // An accessor to get the real value...
37 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
38};
39
40template<typename From> struct simplify_type<const From> {
41 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
42 using SimpleType =
43 typename add_const_past_pointer<NonConstSimpleType>::type;
44 using RetType =
45 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
46
47 static RetType getSimplifiedValue(const From& Val) {
48 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
49 }
50};
51
52// The core of the implementation of isa<X> is here; To and From should be
53// the names of classes. This template can be specialized to customize the
54// implementation of isa<> without rewriting it from scratch.
55template <typename To, typename From, typename Enabler = void>
56struct isa_impl {
57 static inline bool doit(const From &Val) {
58 return To::classof(&Val);
59 }
60};
61
62/// Always allow upcasts, and perform no dynamic check for them.
63template <typename To, typename From>
64struct isa_impl<To, From, std::enable_if_t<std::is_base_of<To, From>::value>> {
65 static inline bool doit(const From &) { return true; }
66};
67
68template <typename To, typename From> struct isa_impl_cl {
69 static inline bool doit(const From &Val) {
70 return isa_impl<To, From>::doit(Val);
71 }
72};
73
74template <typename To, typename From> struct isa_impl_cl<To, const From> {
75 static inline bool doit(const From &Val) {
76 return isa_impl<To, From>::doit(Val);
77 }
78};
79
80template <typename To, typename From>
81struct isa_impl_cl<To, const std::unique_ptr<From>> {
82 static inline bool doit(const std::unique_ptr<From> &Val) {
83 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/Support/Casting.h"
, 83, __PRETTY_FUNCTION__))
;
84 return isa_impl_cl<To, From>::doit(*Val);
85 }
86};
87
88template <typename To, typename From> struct isa_impl_cl<To, From*> {
89 static inline bool doit(const From *Val) {
90 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/Support/Casting.h"
, 90, __PRETTY_FUNCTION__))
;
91 return isa_impl<To, From>::doit(*Val);
92 }
93};
94
95template <typename To, typename From> struct isa_impl_cl<To, From*const> {
96 static inline bool doit(const From *Val) {
97 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/Support/Casting.h"
, 97, __PRETTY_FUNCTION__))
;
98 return isa_impl<To, From>::doit(*Val);
99 }
100};
101
102template <typename To, typename From> struct isa_impl_cl<To, const From*> {
103 static inline bool doit(const From *Val) {
104 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/Support/Casting.h"
, 104, __PRETTY_FUNCTION__))
;
105 return isa_impl<To, From>::doit(*Val);
106 }
107};
108
109template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
110 static inline bool doit(const From *Val) {
111 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/Support/Casting.h"
, 111, __PRETTY_FUNCTION__))
;
112 return isa_impl<To, From>::doit(*Val);
113 }
114};
115
116template<typename To, typename From, typename SimpleFrom>
117struct isa_impl_wrap {
118 // When From != SimplifiedType, we can simplify the type some more by using
119 // the simplify_type template.
120 static bool doit(const From &Val) {
121 return isa_impl_wrap<To, SimpleFrom,
122 typename simplify_type<SimpleFrom>::SimpleType>::doit(
123 simplify_type<const From>::getSimplifiedValue(Val));
124 }
125};
126
127template<typename To, typename FromTy>
128struct isa_impl_wrap<To, FromTy, FromTy> {
129 // When From == SimpleType, we are as simple as we are going to get.
130 static bool doit(const FromTy &Val) {
131 return isa_impl_cl<To,FromTy>::doit(Val);
132 }
133};
134
135// isa<X> - Return true if the parameter to the template is an instance of one
136// of the template type arguments. Used like this:
137//
138// if (isa<Type>(myVal)) { ... }
139// if (isa<Type0, Type1, Type2>(myVal)) { ... }
140//
141template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
142 return isa_impl_wrap<X, const Y,
143 typename simplify_type<const Y>::SimpleType>::doit(Val);
144}
145
146template <typename First, typename Second, typename... Rest, typename Y>
147LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
148 return isa<First>(Val) || isa<Second, Rest...>(Val);
149}
150
151// isa_and_nonnull<X> - Functionally identical to isa, except that a null value
152// is accepted.
153//
154template <typename... X, class Y>
155LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa_and_nonnull(const Y &Val) {
156 if (!Val)
157 return false;
158 return isa<X...>(Val);
159}
160
161//===----------------------------------------------------------------------===//
162// cast<x> Support Templates
163//===----------------------------------------------------------------------===//
164
165template<class To, class From> struct cast_retty;
166
167// Calculate what type the 'cast' function should return, based on a requested
168// type of To and a source type of From.
169template<class To, class From> struct cast_retty_impl {
170 using ret_type = To &; // Normal case, return Ty&
171};
172template<class To, class From> struct cast_retty_impl<To, const From> {
173 using ret_type = const To &; // Normal case, return Ty&
174};
175
176template<class To, class From> struct cast_retty_impl<To, From*> {
177 using ret_type = To *; // Pointer arg case, return Ty*
178};
179
180template<class To, class From> struct cast_retty_impl<To, const From*> {
181 using ret_type = const To *; // Constant pointer arg case, return const Ty*
182};
183
184template<class To, class From> struct cast_retty_impl<To, const From*const> {
185 using ret_type = const To *; // Constant pointer arg case, return const Ty*
186};
187
188template <class To, class From>
189struct cast_retty_impl<To, std::unique_ptr<From>> {
190private:
191 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
192 using ResultType = std::remove_pointer_t<PointerType>;
193
194public:
195 using ret_type = std::unique_ptr<ResultType>;
196};
197
198template<class To, class From, class SimpleFrom>
199struct cast_retty_wrap {
200 // When the simplified type and the from type are not the same, use the type
201 // simplifier to reduce the type, then reuse cast_retty_impl to get the
202 // resultant type.
203 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
204};
205
206template<class To, class FromTy>
207struct cast_retty_wrap<To, FromTy, FromTy> {
208 // When the simplified type is equal to the from type, use it directly.
209 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
210};
211
212template<class To, class From>
213struct cast_retty {
214 using ret_type = typename cast_retty_wrap<
215 To, From, typename simplify_type<From>::SimpleType>::ret_type;
216};
217
218// Ensure the non-simple values are converted using the simplify_type template
219// that may be specialized by smart pointers...
220//
221template<class To, class From, class SimpleFrom> struct cast_convert_val {
222 // This is not a simple type, use the template to simplify it...
223 static typename cast_retty<To, From>::ret_type doit(From &Val) {
224 return cast_convert_val<To, SimpleFrom,
225 typename simplify_type<SimpleFrom>::SimpleType>::doit(
226 simplify_type<From>::getSimplifiedValue(Val));
227 }
228};
229
230template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
231 // This _is_ a simple type, just cast it.
232 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
233 typename cast_retty<To, FromTy>::ret_type Res2
234 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
235 return Res2;
236 }
237};
238
239template <class X> struct is_simple_type {
240 static const bool value =
241 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
242};
243
244// cast<X> - Return the argument parameter cast to the specified type. This
245// casting operator asserts that the type is correct, so it does not return null
246// on failure. It does not allow a null argument (use cast_or_null for that).
247// It is typically used like this:
248//
249// cast<Instruction>(myVal)->getParent()
250//
251template <class X, class Y>
252inline std::enable_if_t<!is_simple_type<Y>::value,
253 typename cast_retty<X, const Y>::ret_type>
254cast(const Y &Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/Support/Casting.h"
, 255, __PRETTY_FUNCTION__))
;
256 return cast_convert_val<
257 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
262 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/Support/Casting.h"
, 262, __PRETTY_FUNCTION__))
;
263 return cast_convert_val<X, Y,
264 typename simplify_type<Y>::SimpleType>::doit(Val);
265}
266
267template <class X, class Y>
268inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
269 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/Support/Casting.h"
, 269, __PRETTY_FUNCTION__))
;
270 return cast_convert_val<X, Y*,
271 typename simplify_type<Y*>::SimpleType>::doit(Val);
272}
273
274template <class X, class Y>
275inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
276cast(std::unique_ptr<Y> &&Val) {
277 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/Support/Casting.h"
, 277, __PRETTY_FUNCTION__))
;
278 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
279 return ret_type(
280 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
281 Val.release()));
282}
283
284// cast_or_null<X> - Functionally identical to cast, except that a null value is
285// accepted.
286//
287template <class X, class Y>
288LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
289 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
290cast_or_null(const Y &Val) {
291 if (!Val)
292 return nullptr;
293 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/Support/Casting.h"
, 293, __PRETTY_FUNCTION__))
;
294 return cast<X>(Val);
295}
296
297template <class X, class Y>
298LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<!is_simple_type<Y>::value,
299 typename cast_retty<X, Y>::ret_type>
300cast_or_null(Y &Val) {
301 if (!Val)
302 return nullptr;
303 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/Support/Casting.h"
, 303, __PRETTY_FUNCTION__))
;
304 return cast<X>(Val);
305}
306
307template <class X, class Y>
308LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
309cast_or_null(Y *Val) {
310 if (!Val) return nullptr;
311 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/llvm/include/llvm/Support/Casting.h"
, 311, __PRETTY_FUNCTION__))
;
312 return cast<X>(Val);
313}
314
315template <class X, class Y>
316inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
317cast_or_null(std::unique_ptr<Y> &&Val) {
318 if (!Val)
319 return nullptr;
320 return cast<X>(std::move(Val));
321}
322
323// dyn_cast<X> - Return the argument parameter cast to the specified type. This
324// casting operator returns null if the argument is of the wrong type, so it can
325// be used to test for a type as well as cast if successful. This should be
326// used in the context of an if statement like this:
327//
328// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
329//
330
331template <class X, class Y>
332LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
333 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
334dyn_cast(const Y &Val) {
335 return isa<X>(Val) ? cast<X>(Val) : nullptr;
29
Assuming 'Val' is not a 'BuiltinType'
30
'?' condition is false
31
Returning null pointer, which participates in a condition later
90
Assuming 'Val' is not a 'BuiltinType'
91
'?' condition is false
92
Returning null pointer, which participates in a condition later
336}
337
338template <class X, class Y>
339LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) {
340 return isa<X>(Val) ? cast<X>(Val) : nullptr;
341}
342
343template <class X, class Y>
344LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) {
345 return isa<X>(Val) ? cast<X>(Val) : nullptr;
346}
347
348// dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
349// value is accepted.
350//
351template <class X, class Y>
352LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
353 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
354dyn_cast_or_null(const Y &Val) {
355 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
356}
357
358template <class X, class Y>
359LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<!is_simple_type<Y>::value,
360 typename cast_retty<X, Y>::ret_type>
361dyn_cast_or_null(Y &Val) {
362 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
363}
364
365template <class X, class Y>
366LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
367dyn_cast_or_null(Y *Val) {
368 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
369}
370
371// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
372// taking ownership of the input pointer iff isa<X>(Val) is true. If the
373// cast is successful, From refers to nullptr on exit and the casted value
374// is returned. If the cast is unsuccessful, the function returns nullptr
375// and From is unchanged.
376template <class X, class Y>
377LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val)
378 -> decltype(cast<X>(Val)) {
379 if (!isa<X>(Val))
380 return nullptr;
381 return cast<X>(std::move(Val));
382}
383
384template <class X, class Y>
385LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) {
386 return unique_dyn_cast<X, Y>(Val);
387}
388
389// dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that
390// a null value is accepted.
391template <class X, class Y>
392LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val)
393 -> decltype(cast<X>(Val)) {
394 if (!Val)
395 return nullptr;
396 return unique_dyn_cast<X, Y>(Val);
397}
398
399template <class X, class Y>
400LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) {
401 return unique_dyn_cast_or_null<X, Y>(Val);
402}
403
404} // end namespace llvm
405
406#endif // LLVM_SUPPORT_CASTING_H

/build/llvm-toolchain-snapshot-12~++20201201111133+ea8c8a50976/clang/include/clang/Basic/OpenCLImageTypes.def

1//===-- OpenCLImageTypes.def - Metadata about BuiltinTypes ------*- 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// This file extends builtin types database with OpenCL image singleton types.
9// Custom code should define one of those three macros:
10// GENERIC_IMAGE_TYPE(Type, Id) - a generic image with its Id without an
11// access type
12// IMAGE_TYPE(Type, Id, SingletonId, AccessType, CGSuffix) - an image type
13// with given ID, singleton ID access type and a codegen suffix
14// GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) - a generic image with its Id and
15// required extension without an access type
16
17#ifdef GENERIC_IMAGE_TYPE
18
19#define IMAGE_READ_TYPE(Type, Id, Ext) GENERIC_IMAGE_TYPE(Type, Id)
20#define IMAGE_WRITE_TYPE(Type, Id, Ext)
21#define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
22
23#elif defined(GENERIC_IMAGE_TYPE_EXT)
24#define IMAGE_READ_TYPE(Type, Id, Ext) GENERIC_IMAGE_TYPE_EXT(Type, Id##ROTy, Ext)
25#define IMAGE_WRITE_TYPE(Type, Id, Ext) GENERIC_IMAGE_TYPE_EXT(Type, Id##WOTy, Ext)
26#define IMAGE_READ_WRITE_TYPE(Type, Id, Ext) GENERIC_IMAGE_TYPE_EXT(Type, Id##RWTy, Ext)
27
28#else
29#ifndef IMAGE_READ_TYPE
30#define IMAGE_READ_TYPE(Type, Id, Ext) \
31 IMAGE_TYPE(Type, Id##RO, Id##ROTy, read_only, ro)
32#endif
33#ifndef IMAGE_WRITE_TYPE
34#define IMAGE_WRITE_TYPE(Type, Id, Ext) \
35 IMAGE_TYPE(Type, Id##WO, Id##WOTy, write_only, wo)
36#endif
37#ifndef IMAGE_READ_WRITE_TYPE
38#define IMAGE_READ_WRITE_TYPE(Type, Id, Ext) \
39 IMAGE_TYPE(Type, Id##RW, Id##RWTy, read_write, rw)
40#endif
41
42#endif
43
44IMAGE_READ_TYPE(image1d, OCLImage1d, "")
146
Assuming the condition is false
45IMAGE_READ_TYPE(image1d_array, OCLImage1dArray, "")
147
Assuming the condition is false
46IMAGE_READ_TYPE(image1d_buffer, OCLImage1dBuffer, "")
148
Assuming the condition is false
47IMAGE_READ_TYPE(image2d, OCLImage2d, "")
149
Assuming the condition is false
48IMAGE_READ_TYPE(image2d_array, OCLImage2dArray, "")
150
Assuming the condition is false
49IMAGE_READ_TYPE(image2d_depth, OCLImage2dDepth, "")
151
Assuming the condition is false
50IMAGE_READ_TYPE(image2d_array_depth, OCLImage2dArrayDepth, "")
152
Assuming the condition is false
51IMAGE_READ_TYPE(image2d_msaa, OCLImage2dMSAA, "cl_khr_gl_msaa_sharing")
153
Assuming the condition is false
52IMAGE_READ_TYPE(image2d_array_msaa, OCLImage2dArrayMSAA, "cl_khr_gl_msaa_sharing")
154
Assuming the condition is false
53IMAGE_READ_TYPE(image2d_msaa_depth, OCLImage2dMSAADepth, "cl_khr_gl_msaa_sharing")
155
Assuming the condition is false
54IMAGE_READ_TYPE(image2d_array_msaa_depth, OCLImage2dArrayMSAADepth, "cl_khr_gl_msaa_sharing")
156
Assuming the condition is false
55IMAGE_READ_TYPE(image3d, OCLImage3d, "")
157
Assuming the condition is false
56
57IMAGE_WRITE_TYPE(image1d, OCLImage1d, "")
158
Assuming the condition is false
58IMAGE_WRITE_TYPE(image1d_array, OCLImage1dArray, "")
159
Assuming the condition is false
59IMAGE_WRITE_TYPE(image1d_buffer, OCLImage1dBuffer, "")
160
Assuming the condition is false
60IMAGE_WRITE_TYPE(image2d, OCLImage2d, "")
161
Assuming the condition is false
61IMAGE_WRITE_TYPE(image2d_array, OCLImage2dArray, "")
162
Assuming the condition is false
62IMAGE_WRITE_TYPE(image2d_depth, OCLImage2dDepth, "")
163
Assuming the condition is false
63IMAGE_WRITE_TYPE(image2d_array_depth, OCLImage2dArrayDepth, "")
164
Assuming the condition is false
64IMAGE_WRITE_TYPE(image2d_msaa, OCLImage2dMSAA, "cl_khr_gl_msaa_sharing")
165
Assuming the condition is false
65IMAGE_WRITE_TYPE(image2d_array_msaa, OCLImage2dArrayMSAA, "cl_khr_gl_msaa_sharing")
166
Assuming the condition is false
66IMAGE_WRITE_TYPE(image2d_msaa_depth, OCLImage2dMSAADepth, "cl_khr_gl_msaa_sharing")
167
Assuming the condition is false
67IMAGE_WRITE_TYPE(image2d_array_msaa_depth, OCLImage2dArrayMSAADepth, "cl_khr_gl_msaa_sharing")
168
Assuming the condition is false
68IMAGE_WRITE_TYPE(image3d, OCLImage3d, "cl_khr_3d_image_writes")
169
Assuming the condition is false
69
70IMAGE_READ_WRITE_TYPE(image1d, OCLImage1d, "")
170
Assuming the condition is false
71IMAGE_READ_WRITE_TYPE(image1d_array, OCLImage1dArray, "")
171
Assuming the condition is false
72IMAGE_READ_WRITE_TYPE(image1d_buffer, OCLImage1dBuffer, "")
172
Assuming the condition is false
73IMAGE_READ_WRITE_TYPE(image2d, OCLImage2d, "")
173
Assuming the condition is false
74IMAGE_READ_WRITE_TYPE(image2d_array, OCLImage2dArray, "")
174
Assuming the condition is false
75IMAGE_READ_WRITE_TYPE(image2d_depth, OCLImage2dDepth, "")
175
Assuming the condition is false
76IMAGE_READ_WRITE_TYPE(image2d_array_depth, OCLImage2dArrayDepth, "")
176
Assuming the condition is false
77IMAGE_READ_WRITE_TYPE(image2d_msaa, OCLImage2dMSAA, "cl_khr_gl_msaa_sharing")
177
Assuming the condition is false
78IMAGE_READ_WRITE_TYPE(image2d_array_msaa, OCLImage2dArrayMSAA, "cl_khr_gl_msaa_sharing")
178
Assuming the condition is false
79IMAGE_READ_WRITE_TYPE(image2d_msaa_depth, OCLImage2dMSAADepth, "cl_khr_gl_msaa_sharing")
179
Assuming the condition is false
80IMAGE_READ_WRITE_TYPE(image2d_array_msaa_depth, OCLImage2dArrayMSAADepth, "cl_khr_gl_msaa_sharing")
180
Assuming the condition is false
81IMAGE_READ_WRITE_TYPE(image3d, OCLImage3d, "")
181
Assuming the condition is true
82
83#undef IMAGE_TYPE
84#undef GENERIC_IMAGE_TYPE
85#undef IMAGE_READ_TYPE
86#undef IMAGE_WRITE_TYPE
87#undef IMAGE_READ_WRITE_TYPE