1//===--- SemaAPINotes.cpp - API Notes Handling ----------------------------===//
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 the mapping from API notes to declaration attributes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/APINotes/APINotesReader.h"
15#include "clang/APINotes/Types.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Lex/Lexer.h"
23#include "clang/Sema/SemaObjC.h"
24#include "clang/Sema/SemaSwift.h"
25#include <stack>
26
27using namespace clang;
28
29namespace {
30enum class IsActive_t : bool { Inactive, Active };
31enum class IsSubstitution_t : bool { Original, Replacement };
32
33struct VersionedInfoMetadata {
34 /// An empty version refers to unversioned metadata.
35 VersionTuple Version;
36 unsigned IsActive : 1;
37 unsigned IsReplacement : 1;
38
39 VersionedInfoMetadata(VersionTuple Version, IsActive_t Active,
40 IsSubstitution_t Replacement)
41 : Version(Version), IsActive(Active == IsActive_t::Active),
42 IsReplacement(Replacement == IsSubstitution_t::Replacement) {}
43};
44} // end anonymous namespace
45
46/// Determine whether this is a multi-level pointer type.
47static bool isIndirectPointerType(QualType Type) {
48 QualType Pointee = Type->getPointeeType();
49 if (Pointee.isNull())
50 return false;
51
52 return Pointee->isAnyPointerType() || Pointee->isObjCObjectPointerType() ||
53 Pointee->isMemberPointerType();
54}
55
56static void applyAPINotesType(Sema &S, Decl *decl, StringRef typeString,
57 VersionedInfoMetadata metadata) {
58 if (typeString.empty())
59
60 return;
61
62 // Version-independent APINotes add "type" annotations
63 // with a versioned attribute for the client to select and apply.
64 if (S.captureSwiftVersionIndependentAPINotes()) {
65 auto *typeAttr = SwiftTypeAttr::CreateImplicit(Ctx&: S.Context, TypeString: typeString);
66 auto *versioned = SwiftVersionedAdditionAttr::CreateImplicit(
67 Ctx&: S.Context, Version: metadata.Version, AdditionalAttr: typeAttr, IsReplacedByActive: metadata.IsReplacement);
68 decl->addAttr(A: versioned);
69 } else {
70 if (!metadata.IsActive)
71 return;
72 S.ApplyAPINotesType(D: decl, TypeString: typeString);
73 }
74}
75
76/// Apply nullability to the given declaration.
77static void applyNullability(Sema &S, Decl *decl, NullabilityKind nullability,
78 VersionedInfoMetadata metadata) {
79 // Version-independent APINotes add "nullability" annotations
80 // with a versioned attribute for the client to select and apply.
81 if (S.captureSwiftVersionIndependentAPINotes()) {
82 SwiftNullabilityAttr::Kind attrNullabilityKind;
83 switch (nullability) {
84 case NullabilityKind::NonNull:
85 attrNullabilityKind = SwiftNullabilityAttr::Kind::NonNull;
86 break;
87 case NullabilityKind::Nullable:
88 attrNullabilityKind = SwiftNullabilityAttr::Kind::Nullable;
89 break;
90 case NullabilityKind::Unspecified:
91 attrNullabilityKind = SwiftNullabilityAttr::Kind::Unspecified;
92 break;
93 case NullabilityKind::NullableResult:
94 attrNullabilityKind = SwiftNullabilityAttr::Kind::NullableResult;
95 break;
96 }
97 auto *nullabilityAttr =
98 SwiftNullabilityAttr::CreateImplicit(Ctx&: S.Context, Kind: attrNullabilityKind);
99 auto *versioned = SwiftVersionedAdditionAttr::CreateImplicit(
100 Ctx&: S.Context, Version: metadata.Version, AdditionalAttr: nullabilityAttr, IsReplacedByActive: metadata.IsReplacement);
101 decl->addAttr(A: versioned);
102 return;
103 } else {
104 if (!metadata.IsActive)
105 return;
106
107 S.ApplyNullability(D: decl, Nullability: nullability);
108 }
109}
110
111/// Copy a string into ASTContext-allocated memory.
112static StringRef ASTAllocateString(ASTContext &Ctx, StringRef String) {
113 void *mem = Ctx.Allocate(Size: String.size(), Align: alignof(char *));
114 memcpy(dest: mem, src: String.data(), n: String.size());
115 return StringRef(static_cast<char *>(mem), String.size());
116}
117
118static AttributeCommonInfo getPlaceholderAttrInfo() {
119 return AttributeCommonInfo(SourceRange(),
120 AttributeCommonInfo::UnknownAttribute,
121 {AttributeCommonInfo::AS_GNU,
122 /*Spelling*/ 0, /*IsAlignas*/ false,
123 /*IsRegularKeywordAttribute*/ false});
124}
125
126namespace {
127template <typename A> struct AttrKindFor {};
128
129#define ATTR(X) \
130 template <> struct AttrKindFor<X##Attr> { \
131 static const attr::Kind value = attr::X; \
132 };
133#include "clang/Basic/AttrList.inc"
134
135/// Handle an attribute introduced by API notes.
136///
137/// \param IsAddition Whether we should add a new attribute
138/// (otherwise, we might remove an existing attribute).
139/// \param CreateAttr Create the new attribute to be added.
140template <typename A>
141void handleAPINotedAttribute(
142 Sema &S, Decl *D, bool IsAddition, VersionedInfoMetadata Metadata,
143 llvm::function_ref<A *()> CreateAttr,
144 llvm::function_ref<Decl::attr_iterator(const Decl *)> GetExistingAttr) {
145 if (Metadata.IsActive) {
146 auto Existing = GetExistingAttr(D);
147 if (Existing != D->attr_end()) {
148 // Remove the existing attribute, and treat it as a superseded
149 // non-versioned attribute.
150 auto *Versioned = SwiftVersionedAdditionAttr::CreateImplicit(
151 Ctx&: S.Context, Version: Metadata.Version, AdditionalAttr: *Existing, /*IsReplacedByActive*/ true);
152
153 D->getAttrs().erase(CI: Existing);
154 D->addAttr(A: Versioned);
155 }
156
157 // If we're supposed to add a new attribute, do so.
158 if (IsAddition) {
159 if (auto Attr = CreateAttr())
160 D->addAttr(A: Attr);
161 }
162
163 return;
164 }
165 if (IsAddition) {
166 if (auto Attr = CreateAttr()) {
167 auto *Versioned = SwiftVersionedAdditionAttr::CreateImplicit(
168 S.Context, Metadata.Version, Attr,
169 /*IsReplacedByActive*/ Metadata.IsReplacement);
170 D->addAttr(A: Versioned);
171 }
172 } else {
173 // FIXME: This isn't preserving enough information for things like
174 // availability, where we're trying to remove a /specific/ kind of
175 // attribute.
176 auto *Versioned = SwiftVersionedRemovalAttr::CreateImplicit(
177 S.Context, Metadata.Version, AttrKindFor<A>::value,
178 /*IsReplacedByActive*/ Metadata.IsReplacement);
179 D->addAttr(A: Versioned);
180 }
181}
182
183template <typename A>
184void handleAPINotedAttribute(Sema &S, Decl *D, bool ShouldAddAttribute,
185 VersionedInfoMetadata Metadata,
186 llvm::function_ref<A *()> CreateAttr) {
187 handleAPINotedAttribute<A>(
188 S, D, ShouldAddAttribute, Metadata, CreateAttr, [](const Decl *D) {
189 return llvm::find_if(D->attrs(),
190 [](const Attr *Next) { return isa<A>(Next); });
191 });
192}
193} // namespace
194
195template <typename A>
196static void handleAPINotedRetainCountAttribute(Sema &S, Decl *D,
197 bool ShouldAddAttribute,
198 VersionedInfoMetadata Metadata) {
199 // The template argument has a default to make the "removal" case more
200 // concise; it doesn't matter /which/ attribute is being removed.
201 handleAPINotedAttribute<A>(
202 S, D, ShouldAddAttribute, Metadata,
203 [&] { return new (S.Context) A(S.Context, getPlaceholderAttrInfo()); },
204 [](const Decl *D) -> Decl::attr_iterator {
205 return llvm::find_if(D->attrs(), [](const Attr *Next) -> bool {
206 return isa<CFReturnsRetainedAttr>(Val: Next) ||
207 isa<CFReturnsNotRetainedAttr>(Val: Next) ||
208 isa<NSReturnsRetainedAttr>(Val: Next) ||
209 isa<NSReturnsNotRetainedAttr>(Val: Next) ||
210 isa<CFAuditedTransferAttr>(Val: Next);
211 });
212 });
213}
214
215static void handleAPINotedRetainCountConvention(
216 Sema &S, Decl *D, VersionedInfoMetadata Metadata,
217 std::optional<api_notes::RetainCountConventionKind> Convention) {
218 if (!Convention)
219 return;
220 switch (*Convention) {
221 case api_notes::RetainCountConventionKind::None:
222 if (isa<FunctionDecl>(Val: D)) {
223 handleAPINotedRetainCountAttribute<CFUnknownTransferAttr>(
224 S, D, /*shouldAddAttribute*/ ShouldAddAttribute: true, Metadata);
225 } else {
226 handleAPINotedRetainCountAttribute<CFReturnsRetainedAttr>(
227 S, D, /*shouldAddAttribute*/ ShouldAddAttribute: false, Metadata);
228 }
229 break;
230 case api_notes::RetainCountConventionKind::CFReturnsRetained:
231 handleAPINotedRetainCountAttribute<CFReturnsRetainedAttr>(
232 S, D, /*shouldAddAttribute*/ ShouldAddAttribute: true, Metadata);
233 break;
234 case api_notes::RetainCountConventionKind::CFReturnsNotRetained:
235 handleAPINotedRetainCountAttribute<CFReturnsNotRetainedAttr>(
236 S, D, /*shouldAddAttribute*/ ShouldAddAttribute: true, Metadata);
237 break;
238 case api_notes::RetainCountConventionKind::NSReturnsRetained:
239 handleAPINotedRetainCountAttribute<NSReturnsRetainedAttr>(
240 S, D, /*shouldAddAttribute*/ ShouldAddAttribute: true, Metadata);
241 break;
242 case api_notes::RetainCountConventionKind::NSReturnsNotRetained:
243 handleAPINotedRetainCountAttribute<NSReturnsNotRetainedAttr>(
244 S, D, /*shouldAddAttribute*/ ShouldAddAttribute: true, Metadata);
245 break;
246 }
247}
248
249static void ProcessAPINotes(Sema &S, Decl *D,
250 const api_notes::CommonEntityInfo &Info,
251 VersionedInfoMetadata Metadata) {
252 // Availability
253 if (Info.Unavailable) {
254 handleAPINotedAttribute<UnavailableAttr>(S, D, ShouldAddAttribute: true, Metadata, CreateAttr: [&] {
255 return new (S.Context)
256 UnavailableAttr(S.Context, getPlaceholderAttrInfo(),
257 ASTAllocateString(Ctx&: S.Context, String: Info.UnavailableMsg));
258 });
259 }
260
261 if (Info.UnavailableInSwift) {
262 handleAPINotedAttribute<AvailabilityAttr>(
263 S, D, IsAddition: true, Metadata,
264 CreateAttr: [&] {
265 return new (S.Context) AvailabilityAttr(
266 S.Context, getPlaceholderAttrInfo(),
267 &S.Context.Idents.get(Name: "swift"), VersionTuple(), VersionTuple(),
268 VersionTuple(),
269 /*Unavailable=*/true,
270 ASTAllocateString(Ctx&: S.Context, String: Info.UnavailableMsg),
271 /*Strict=*/false,
272 /*Replacement=*/StringRef(),
273 /*Priority=*/Sema::AP_Explicit,
274 /*Environment=*/nullptr);
275 },
276 GetExistingAttr: [](const Decl *D) {
277 return llvm::find_if(Range: D->attrs(), P: [](const Attr *next) -> bool {
278 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: next))
279 if (const auto *II = AA->getPlatform())
280 return II->isStr(Str: "swift");
281 return false;
282 });
283 });
284 }
285
286 // swift_private
287 if (auto SwiftPrivate = Info.isSwiftPrivate()) {
288 handleAPINotedAttribute<SwiftPrivateAttr>(
289 S, D, ShouldAddAttribute: *SwiftPrivate, Metadata, CreateAttr: [&] {
290 return new (S.Context)
291 SwiftPrivateAttr(S.Context, getPlaceholderAttrInfo());
292 });
293 }
294
295 // swift_safety
296 if (auto SafetyKind = Info.getSwiftSafety()) {
297 bool Addition = *SafetyKind != api_notes::SwiftSafetyKind::Unspecified;
298 handleAPINotedAttribute<SwiftAttrAttr>(
299 S, D, IsAddition: Addition, Metadata,
300 CreateAttr: [&] {
301 return SwiftAttrAttr::Create(
302 Ctx&: S.Context, Attribute: *SafetyKind == api_notes::SwiftSafetyKind::Safe
303 ? "safe"
304 : "unsafe");
305 },
306 GetExistingAttr: [](const Decl *D) {
307 return llvm::find_if(Range: D->attrs(), P: [](const Attr *attr) {
308 if (const auto *swiftAttr = dyn_cast<SwiftAttrAttr>(Val: attr)) {
309 if (swiftAttr->getAttribute() == "safe" ||
310 swiftAttr->getAttribute() == "unsafe")
311 return true;
312 }
313 return false;
314 });
315 });
316 }
317
318 // swift_name
319 if (!Info.SwiftName.empty()) {
320 handleAPINotedAttribute<SwiftNameAttr>(
321 S, D, ShouldAddAttribute: true, Metadata, CreateAttr: [&]() -> SwiftNameAttr * {
322 AttributeFactory AF{};
323 AttributePool AP{AF};
324 auto &C = S.getASTContext();
325 ParsedAttr *SNA = AP.create(
326 attrName: &C.Idents.get(Name: "swift_name"), attrRange: SourceRange(), scope: AttributeScopeInfo(),
327 Param1: nullptr, Param2: nullptr, Param3: nullptr, form: ParsedAttr::Form::GNU());
328
329 if (!S.Swift().DiagnoseName(D, Name: Info.SwiftName, Loc: D->getLocation(), AL: *SNA,
330 /*IsAsync=*/false))
331 return nullptr;
332
333 return new (S.Context)
334 SwiftNameAttr(S.Context, getPlaceholderAttrInfo(),
335 ASTAllocateString(Ctx&: S.Context, String: Info.SwiftName));
336 });
337 }
338}
339
340static void ProcessAPINotes(Sema &S, Decl *D,
341 const api_notes::CommonTypeInfo &Info,
342 VersionedInfoMetadata Metadata) {
343 // swift_bridge
344 if (auto SwiftBridge = Info.getSwiftBridge()) {
345 handleAPINotedAttribute<SwiftBridgeAttr>(
346 S, D, ShouldAddAttribute: !SwiftBridge->empty(), Metadata, CreateAttr: [&] {
347 return new (S.Context)
348 SwiftBridgeAttr(S.Context, getPlaceholderAttrInfo(),
349 ASTAllocateString(Ctx&: S.Context, String: *SwiftBridge));
350 });
351 }
352
353 // ns_error_domain
354 if (auto NSErrorDomain = Info.getNSErrorDomain()) {
355 handleAPINotedAttribute<NSErrorDomainAttr>(
356 S, D, ShouldAddAttribute: !NSErrorDomain->empty(), Metadata, CreateAttr: [&] {
357 return new (S.Context)
358 NSErrorDomainAttr(S.Context, getPlaceholderAttrInfo(),
359 &S.Context.Idents.get(Name: *NSErrorDomain));
360 });
361 }
362
363 if (auto ConformsTo = Info.getSwiftConformance())
364 D->addAttr(
365 A: SwiftAttrAttr::Create(Ctx&: S.Context, Attribute: "conforms_to:" + ConformsTo.value()));
366
367 ProcessAPINotes(S, D, Info: static_cast<const api_notes::CommonEntityInfo &>(Info),
368 Metadata);
369}
370
371/// Check that the replacement type provided by API notes is reasonable.
372///
373/// This is a very weak form of ABI check.
374static bool checkAPINotesReplacementType(Sema &S, SourceLocation Loc,
375 QualType OrigType,
376 QualType ReplacementType) {
377 if (S.Context.getTypeSize(T: OrigType) !=
378 S.Context.getTypeSize(T: ReplacementType)) {
379 S.Diag(Loc, DiagID: diag::err_incompatible_replacement_type)
380 << ReplacementType << OrigType;
381 return true;
382 }
383
384 return false;
385}
386
387void Sema::ApplyAPINotesType(Decl *D, StringRef TypeString) {
388 if (!TypeString.empty() && ParseTypeFromStringCallback) {
389 auto ParsedType = ParseTypeFromStringCallback(TypeString, "<API Notes>",
390 D->getLocation());
391 if (ParsedType.isUsable()) {
392 QualType Type = Sema::GetTypeFromParser(Ty: ParsedType.get());
393 auto TypeInfo = Context.getTrivialTypeSourceInfo(T: Type, Loc: D->getLocation());
394 if (auto Var = dyn_cast<VarDecl>(Val: D)) {
395 // Make adjustments to parameter types.
396 if (isa<ParmVarDecl>(Val: Var)) {
397 Type = ObjC().AdjustParameterTypeForObjCAutoRefCount(
398 T: Type, NameLoc: D->getLocation(), TSInfo: TypeInfo);
399 Type = Context.getAdjustedParameterType(T: Type);
400 }
401
402 if (!checkAPINotesReplacementType(S&: *this, Loc: Var->getLocation(),
403 OrigType: Var->getType(), ReplacementType: Type)) {
404 Var->setType(Type);
405 Var->setTypeSourceInfo(TypeInfo);
406 }
407 } else if (auto property = dyn_cast<ObjCPropertyDecl>(Val: D)) {
408 if (!checkAPINotesReplacementType(S&: *this, Loc: property->getLocation(),
409 OrigType: property->getType(), ReplacementType: Type)) {
410 property->setType(T: Type, TSI: TypeInfo);
411 }
412 } else if (auto field = dyn_cast<FieldDecl>(Val: D)) {
413 if (!checkAPINotesReplacementType(S&: *this, Loc: field->getLocation(),
414 OrigType: field->getType(), ReplacementType: Type)) {
415 field->setType(Type);
416 field->setTypeSourceInfo(TypeInfo);
417 }
418 } else {
419 llvm_unreachable("API notes allowed a type on an unknown declaration");
420 }
421 }
422 }
423}
424
425void Sema::ApplyNullability(Decl *D, NullabilityKind Nullability) {
426 auto GetModified =
427 [&](class Decl *D, QualType QT,
428 NullabilityKind Nullability) -> std::optional<QualType> {
429 QualType Original = QT;
430 CheckImplicitNullabilityTypeSpecifier(Type&: QT, Nullability, DiagLoc: D->getLocation(),
431 AllowArrayTypes: isa<ParmVarDecl>(Val: D),
432 /*OverrideExisting=*/true);
433 return (QT.getTypePtr() != Original.getTypePtr()) ? std::optional(QT)
434 : std::nullopt;
435 };
436
437 if (auto Function = dyn_cast<FunctionDecl>(Val: D)) {
438 if (auto Modified =
439 GetModified(D, Function->getReturnType(), Nullability)) {
440 const FunctionType *FnType = Function->getType()->castAs<FunctionType>();
441 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(Val: FnType))
442 Function->setType(Context.getFunctionType(
443 ResultTy: *Modified, Args: proto->getParamTypes(), EPI: proto->getExtProtoInfo()));
444 else
445 Function->setType(
446 Context.getFunctionNoProtoType(ResultTy: *Modified, Info: FnType->getExtInfo()));
447 }
448 } else if (auto Method = dyn_cast<ObjCMethodDecl>(Val: D)) {
449 if (auto Modified = GetModified(D, Method->getReturnType(), Nullability)) {
450 Method->setReturnType(*Modified);
451
452 // Make it a context-sensitive keyword if we can.
453 if (!isIndirectPointerType(Type: *Modified))
454 Method->setObjCDeclQualifier(Decl::ObjCDeclQualifier(
455 Method->getObjCDeclQualifier() | Decl::OBJC_TQ_CSNullability));
456 }
457 } else if (auto Value = dyn_cast<ValueDecl>(Val: D)) {
458 if (auto Modified = GetModified(D, Value->getType(), Nullability)) {
459 Value->setType(*Modified);
460
461 // Make it a context-sensitive keyword if we can.
462 if (auto Parm = dyn_cast<ParmVarDecl>(Val: D)) {
463 if (Parm->isObjCMethodParameter() && !isIndirectPointerType(Type: *Modified))
464 Parm->setObjCDeclQualifier(Decl::ObjCDeclQualifier(
465 Parm->getObjCDeclQualifier() | Decl::OBJC_TQ_CSNullability));
466 }
467 }
468 } else if (auto Property = dyn_cast<ObjCPropertyDecl>(Val: D)) {
469 if (auto Modified = GetModified(D, Property->getType(), Nullability)) {
470 Property->setType(T: *Modified, TSI: Property->getTypeSourceInfo());
471
472 // Make it a property attribute if we can.
473 if (!isIndirectPointerType(Type: *Modified))
474 Property->setPropertyAttributes(
475 ObjCPropertyAttribute::kind_null_resettable);
476 }
477 }
478}
479
480/// Process API notes for a variable or property.
481static void ProcessAPINotes(Sema &S, Decl *D,
482 const api_notes::VariableInfo &Info,
483 VersionedInfoMetadata Metadata) {
484 // Type override.
485 applyAPINotesType(S, decl: D, typeString: Info.getType(), metadata: Metadata);
486
487 // Nullability.
488 if (auto Nullability = Info.getNullability())
489 applyNullability(S, decl: D, nullability: *Nullability, metadata: Metadata);
490
491 // Handle common entity information.
492 ProcessAPINotes(S, D, Info: static_cast<const api_notes::CommonEntityInfo &>(Info),
493 Metadata);
494}
495
496/// Process API notes for a parameter.
497static void ProcessAPINotes(Sema &S, ParmVarDecl *D,
498 const api_notes::ParamInfo &Info,
499 VersionedInfoMetadata Metadata) {
500 // noescape
501 if (auto NoEscape = Info.isNoEscape())
502 handleAPINotedAttribute<NoEscapeAttr>(S, D, ShouldAddAttribute: *NoEscape, Metadata, CreateAttr: [&] {
503 return new (S.Context) NoEscapeAttr(S.Context, getPlaceholderAttrInfo());
504 });
505
506 if (auto Lifetimebound = Info.isLifetimebound())
507 handleAPINotedAttribute<LifetimeBoundAttr>(
508 S, D, ShouldAddAttribute: *Lifetimebound, Metadata, CreateAttr: [&] {
509 return new (S.Context)
510 LifetimeBoundAttr(S.Context, getPlaceholderAttrInfo());
511 });
512
513 // Retain count convention
514 handleAPINotedRetainCountConvention(S, D, Metadata,
515 Convention: Info.getRetainCountConvention());
516
517 // Handle common entity information.
518 ProcessAPINotes(S, D, Info: static_cast<const api_notes::VariableInfo &>(Info),
519 Metadata);
520}
521
522/// Process API notes for a global variable.
523static void ProcessAPINotes(Sema &S, VarDecl *D,
524 const api_notes::GlobalVariableInfo &Info,
525 VersionedInfoMetadata metadata) {
526 // Handle common entity information.
527 ProcessAPINotes(S, D, Info: static_cast<const api_notes::VariableInfo &>(Info),
528 Metadata: metadata);
529}
530
531/// Process API notes for a C field.
532static void ProcessAPINotes(Sema &S, FieldDecl *D,
533 const api_notes::FieldInfo &Info,
534 VersionedInfoMetadata metadata) {
535 // Handle common entity information.
536 ProcessAPINotes(S, D, Info: static_cast<const api_notes::VariableInfo &>(Info),
537 Metadata: metadata);
538}
539
540/// Process API notes for an Objective-C property.
541static void ProcessAPINotes(Sema &S, ObjCPropertyDecl *D,
542 const api_notes::ObjCPropertyInfo &Info,
543 VersionedInfoMetadata Metadata) {
544 // Handle common entity information.
545 ProcessAPINotes(S, D, Info: static_cast<const api_notes::VariableInfo &>(Info),
546 Metadata);
547
548 if (auto AsAccessors = Info.getSwiftImportAsAccessors()) {
549 handleAPINotedAttribute<SwiftImportPropertyAsAccessorsAttr>(
550 S, D, ShouldAddAttribute: *AsAccessors, Metadata, CreateAttr: [&] {
551 return new (S.Context) SwiftImportPropertyAsAccessorsAttr(
552 S.Context, getPlaceholderAttrInfo());
553 });
554 }
555}
556
557namespace {
558typedef llvm::PointerUnion<FunctionDecl *, ObjCMethodDecl *> FunctionOrMethod;
559}
560
561/// Process API notes for a function or method.
562static void ProcessAPINotes(Sema &S, FunctionOrMethod AnyFunc,
563 const api_notes::FunctionInfo &Info,
564 VersionedInfoMetadata Metadata) {
565 // Find the declaration itself.
566 FunctionDecl *FD = dyn_cast<FunctionDecl *>(Val&: AnyFunc);
567 Decl *D = FD;
568 ObjCMethodDecl *MD = nullptr;
569 if (!D) {
570 MD = cast<ObjCMethodDecl *>(Val&: AnyFunc);
571 D = MD;
572 }
573
574 assert((FD || MD) && "Expecting Function or ObjCMethod");
575
576 // Nullability of return type.
577 if (Info.NullabilityAudited)
578 applyNullability(S, decl: D, nullability: Info.getReturnTypeInfo(), metadata: Metadata);
579
580 // Add [[clang::unsafe_buffer_usage]]
581 if (Info.UnsafeBufferUsage && !D->getAttr<UnsafeBufferUsageAttr>()) {
582 handleAPINotedAttribute<UnsafeBufferUsageAttr>(S, D, ShouldAddAttribute: true, Metadata, CreateAttr: [&]() {
583 return UnsafeBufferUsageAttr::Create(Ctx&: S.getASTContext(),
584 CommonInfo: getPlaceholderAttrInfo());
585 });
586 }
587
588 // Parameters.
589 unsigned NumParams = FD ? FD->getNumParams() : MD->param_size();
590
591 bool AnyTypeChanged = false;
592 for (unsigned I = 0; I != NumParams; ++I) {
593 ParmVarDecl *Param = FD ? FD->getParamDecl(i: I) : MD->param_begin()[I];
594 QualType ParamTypeBefore = Param->getType();
595
596 if (I < Info.Params.size())
597 ProcessAPINotes(S, D: Param, Info: Info.Params[I], Metadata);
598
599 // Nullability.
600 if (Info.NullabilityAudited)
601 applyNullability(S, decl: Param, nullability: Info.getParamTypeInfo(index: I), metadata: Metadata);
602
603 if (ParamTypeBefore.getAsOpaquePtr() != Param->getType().getAsOpaquePtr())
604 AnyTypeChanged = true;
605 }
606
607 // returns_(un)retained
608 if (!Info.SwiftReturnOwnership.empty())
609 D->addAttr(A: SwiftAttrAttr::Create(Ctx&: S.Context,
610 Attribute: "returns_" + Info.SwiftReturnOwnership));
611
612 // Result type override.
613 QualType OverriddenResultType;
614 if (Metadata.IsActive && !Info.ResultType.empty() &&
615 S.ParseTypeFromStringCallback) {
616 auto ParsedType = S.ParseTypeFromStringCallback(
617 Info.ResultType, "<API Notes>", D->getLocation());
618 if (ParsedType.isUsable()) {
619 QualType ResultType = Sema::GetTypeFromParser(Ty: ParsedType.get());
620
621 if (MD) {
622 if (!checkAPINotesReplacementType(S, Loc: D->getLocation(),
623 OrigType: MD->getReturnType(), ReplacementType: ResultType)) {
624 auto ResultTypeInfo =
625 S.Context.getTrivialTypeSourceInfo(T: ResultType, Loc: D->getLocation());
626 MD->setReturnType(ResultType);
627 MD->setReturnTypeSourceInfo(ResultTypeInfo);
628 }
629 } else if (!checkAPINotesReplacementType(
630 S, Loc: FD->getLocation(), OrigType: FD->getReturnType(), ReplacementType: ResultType)) {
631 OverriddenResultType = ResultType;
632 AnyTypeChanged = true;
633 }
634 }
635 }
636
637 // If the result type or any of the parameter types changed for a function
638 // declaration, we have to rebuild the type.
639 if (FD && AnyTypeChanged) {
640 if (const auto *fnProtoType = FD->getType()->getAs<FunctionProtoType>()) {
641 if (OverriddenResultType.isNull())
642 OverriddenResultType = fnProtoType->getReturnType();
643
644 SmallVector<QualType, 4> ParamTypes;
645 for (auto Param : FD->parameters())
646 ParamTypes.push_back(Elt: Param->getType());
647
648 FD->setType(S.Context.getFunctionType(ResultTy: OverriddenResultType, Args: ParamTypes,
649 EPI: fnProtoType->getExtProtoInfo()));
650 } else if (!OverriddenResultType.isNull()) {
651 const auto *FnNoProtoType = FD->getType()->castAs<FunctionNoProtoType>();
652 FD->setType(S.Context.getFunctionNoProtoType(
653 ResultTy: OverriddenResultType, Info: FnNoProtoType->getExtInfo()));
654 }
655 }
656
657 // Retain count convention
658 handleAPINotedRetainCountConvention(S, D, Metadata,
659 Convention: Info.getRetainCountConvention());
660
661 // Handle common entity information.
662 ProcessAPINotes(S, D, Info: static_cast<const api_notes::CommonEntityInfo &>(Info),
663 Metadata);
664}
665
666/// Process API notes for a C++ method.
667static void ProcessAPINotes(Sema &S, CXXMethodDecl *Method,
668 const api_notes::CXXMethodInfo &Info,
669 VersionedInfoMetadata Metadata) {
670 if (Info.This && Info.This->isLifetimebound() &&
671 !lifetimes::implicitObjectParamIsLifetimeBound(FD: Method)) {
672 auto MethodType = Method->getType();
673 auto *attr = ::new (S.Context)
674 LifetimeBoundAttr(S.Context, getPlaceholderAttrInfo());
675 QualType AttributedType =
676 S.Context.getAttributedType(attr, modifiedType: MethodType, equivalentType: MethodType);
677 TypeLocBuilder TLB;
678 TLB.pushFullCopy(L: Method->getTypeSourceInfo()->getTypeLoc());
679 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(T: AttributedType);
680 TyLoc.setAttr(attr);
681 Method->setType(AttributedType);
682 Method->setTypeSourceInfo(TLB.getTypeSourceInfo(Context&: S.Context, T: AttributedType));
683 }
684
685 ProcessAPINotes(S, AnyFunc: (FunctionOrMethod)Method, Info, Metadata);
686}
687
688/// Process API notes for a global function.
689static void ProcessAPINotes(Sema &S, FunctionDecl *D,
690 const api_notes::GlobalFunctionInfo &Info,
691 VersionedInfoMetadata Metadata) {
692 // Handle common function information.
693 ProcessAPINotes(S, AnyFunc: FunctionOrMethod(D),
694 Info: static_cast<const api_notes::FunctionInfo &>(Info), Metadata);
695}
696
697/// Process API notes for an enumerator.
698static void ProcessAPINotes(Sema &S, EnumConstantDecl *D,
699 const api_notes::EnumConstantInfo &Info,
700 VersionedInfoMetadata Metadata) {
701 // Handle common information.
702 ProcessAPINotes(S, D, Info: static_cast<const api_notes::CommonEntityInfo &>(Info),
703 Metadata);
704}
705
706/// Process API notes for an Objective-C method.
707static void ProcessAPINotes(Sema &S, ObjCMethodDecl *D,
708 const api_notes::ObjCMethodInfo &Info,
709 VersionedInfoMetadata Metadata) {
710 // Designated initializers.
711 if (Info.DesignatedInit) {
712 handleAPINotedAttribute<ObjCDesignatedInitializerAttr>(
713 S, D, ShouldAddAttribute: true, Metadata, CreateAttr: [&] {
714 if (ObjCInterfaceDecl *IFace = D->getClassInterface())
715 IFace->setHasDesignatedInitializers();
716
717 return new (S.Context) ObjCDesignatedInitializerAttr(
718 S.Context, getPlaceholderAttrInfo());
719 });
720 }
721
722 // Handle common function information.
723 ProcessAPINotes(S, AnyFunc: FunctionOrMethod(D),
724 Info: static_cast<const api_notes::FunctionInfo &>(Info), Metadata);
725}
726
727/// Process API notes for a tag.
728static void ProcessAPINotes(Sema &S, TagDecl *D, const api_notes::TagInfo &Info,
729 VersionedInfoMetadata Metadata) {
730 if (auto ImportAs = Info.SwiftImportAs)
731 D->addAttr(A: SwiftAttrAttr::Create(Ctx&: S.Context, Attribute: "import_" + ImportAs.value()));
732
733 if (auto RetainOp = Info.SwiftRetainOp)
734 D->addAttr(A: SwiftAttrAttr::Create(Ctx&: S.Context, Attribute: "retain:" + RetainOp.value()));
735
736 if (auto ReleaseOp = Info.SwiftReleaseOp)
737 D->addAttr(
738 A: SwiftAttrAttr::Create(Ctx&: S.Context, Attribute: "release:" + ReleaseOp.value()));
739 if (auto DestroyOp = Info.SwiftDestroyOp)
740 D->addAttr(
741 A: SwiftAttrAttr::Create(Ctx&: S.Context, Attribute: "destroy:" + DestroyOp.value()));
742 if (auto DefaultOwnership = Info.SwiftDefaultOwnership)
743 D->addAttr(A: SwiftAttrAttr::Create(
744 Ctx&: S.Context, Attribute: "returned_as_" + DefaultOwnership.value() + "_by_default"));
745
746 if (auto Copyable = Info.isSwiftCopyable()) {
747 if (!*Copyable)
748 D->addAttr(A: SwiftAttrAttr::Create(Ctx&: S.Context, Attribute: "~Copyable"));
749 }
750
751 if (auto Escapable = Info.isSwiftEscapable()) {
752 D->addAttr(A: SwiftAttrAttr::Create(Ctx&: S.Context,
753 Attribute: *Escapable ? "Escapable" : "~Escapable"));
754 }
755
756 if (auto Extensibility = Info.EnumExtensibility) {
757 using api_notes::EnumExtensibilityKind;
758 bool ShouldAddAttribute = (*Extensibility != EnumExtensibilityKind::None);
759 handleAPINotedAttribute<EnumExtensibilityAttr>(
760 S, D, ShouldAddAttribute, Metadata, CreateAttr: [&] {
761 EnumExtensibilityAttr::Kind kind;
762 switch (*Extensibility) {
763 case EnumExtensibilityKind::None:
764 llvm_unreachable("remove only");
765 case EnumExtensibilityKind::Open:
766 kind = EnumExtensibilityAttr::Open;
767 break;
768 case EnumExtensibilityKind::Closed:
769 kind = EnumExtensibilityAttr::Closed;
770 break;
771 }
772 return new (S.Context)
773 EnumExtensibilityAttr(S.Context, getPlaceholderAttrInfo(), kind);
774 });
775 }
776
777 if (auto FlagEnum = Info.isFlagEnum()) {
778 handleAPINotedAttribute<FlagEnumAttr>(S, D, ShouldAddAttribute: *FlagEnum, Metadata, CreateAttr: [&] {
779 return new (S.Context) FlagEnumAttr(S.Context, getPlaceholderAttrInfo());
780 });
781 }
782
783 // Handle common type information.
784 ProcessAPINotes(S, D, Info: static_cast<const api_notes::CommonTypeInfo &>(Info),
785 Metadata);
786}
787
788/// Process API notes for a typedef.
789static void ProcessAPINotes(Sema &S, TypedefNameDecl *D,
790 const api_notes::TypedefInfo &Info,
791 VersionedInfoMetadata Metadata) {
792 // swift_wrapper
793 using SwiftWrapperKind = api_notes::SwiftNewTypeKind;
794
795 if (auto SwiftWrapper = Info.SwiftWrapper) {
796 handleAPINotedAttribute<SwiftNewTypeAttr>(
797 S, D, ShouldAddAttribute: *SwiftWrapper != SwiftWrapperKind::None, Metadata, CreateAttr: [&] {
798 SwiftNewTypeAttr::NewtypeKind Kind;
799 switch (*SwiftWrapper) {
800 case SwiftWrapperKind::None:
801 llvm_unreachable("Shouldn't build an attribute");
802
803 case SwiftWrapperKind::Struct:
804 Kind = SwiftNewTypeAttr::NK_Struct;
805 break;
806
807 case SwiftWrapperKind::Enum:
808 Kind = SwiftNewTypeAttr::NK_Enum;
809 break;
810 }
811 AttributeCommonInfo SyntaxInfo{
812 SourceRange(),
813 AttributeCommonInfo::AT_SwiftNewType,
814 {AttributeCommonInfo::AS_GNU, SwiftNewTypeAttr::GNU_swift_wrapper,
815 /*IsAlignas*/ false, /*IsRegularKeywordAttribute*/ false}};
816 return new (S.Context) SwiftNewTypeAttr(S.Context, SyntaxInfo, Kind);
817 });
818 }
819
820 // Handle common type information.
821 ProcessAPINotes(S, D, Info: static_cast<const api_notes::CommonTypeInfo &>(Info),
822 Metadata);
823}
824
825/// Process API notes for an Objective-C class or protocol.
826static void ProcessAPINotes(Sema &S, ObjCContainerDecl *D,
827 const api_notes::ContextInfo &Info,
828 VersionedInfoMetadata Metadata) {
829 // Handle common type information.
830 ProcessAPINotes(S, D, Info: static_cast<const api_notes::CommonTypeInfo &>(Info),
831 Metadata);
832}
833
834/// Process API notes for an Objective-C class.
835static void ProcessAPINotes(Sema &S, ObjCInterfaceDecl *D,
836 const api_notes::ContextInfo &Info,
837 VersionedInfoMetadata Metadata) {
838 if (auto AsNonGeneric = Info.getSwiftImportAsNonGeneric()) {
839 handleAPINotedAttribute<SwiftImportAsNonGenericAttr>(
840 S, D, ShouldAddAttribute: *AsNonGeneric, Metadata, CreateAttr: [&] {
841 return new (S.Context)
842 SwiftImportAsNonGenericAttr(S.Context, getPlaceholderAttrInfo());
843 });
844 }
845
846 if (auto ObjcMembers = Info.getSwiftObjCMembers()) {
847 handleAPINotedAttribute<SwiftObjCMembersAttr>(
848 S, D, ShouldAddAttribute: *ObjcMembers, Metadata, CreateAttr: [&] {
849 return new (S.Context)
850 SwiftObjCMembersAttr(S.Context, getPlaceholderAttrInfo());
851 });
852 }
853
854 // Handle information common to Objective-C classes and protocols.
855 ProcessAPINotes(S, D: static_cast<clang::ObjCContainerDecl *>(D), Info,
856 Metadata);
857}
858
859/// If we're applying API notes with an active, non-default version, and the
860/// versioned API notes have a SwiftName but the declaration normally wouldn't
861/// have one, add a removal attribute to make it clear that the new SwiftName
862/// attribute only applies to the active version of \p D, not to all versions.
863///
864/// This must be run \em before processing API notes for \p D, because otherwise
865/// any existing SwiftName attribute will have been packaged up in a
866/// SwiftVersionedAdditionAttr.
867template <typename SpecificInfo>
868static void maybeAttachUnversionedSwiftName(
869 Sema &S, Decl *D,
870 const api_notes::APINotesReader::VersionedInfo<SpecificInfo> Info) {
871 if (D->hasAttr<SwiftNameAttr>())
872 return;
873 if (!Info.getSelected())
874 return;
875
876 // Is the active slice versioned, and does it set a Swift name?
877 VersionTuple SelectedVersion;
878 SpecificInfo SelectedInfoSlice;
879 std::tie(SelectedVersion, SelectedInfoSlice) = Info[*Info.getSelected()];
880 if (SelectedVersion.empty())
881 return;
882 if (SelectedInfoSlice.SwiftName.empty())
883 return;
884
885 // Does the unversioned slice /not/ set a Swift name?
886 for (const auto &VersionAndInfoSlice : Info) {
887 if (!VersionAndInfoSlice.first.empty())
888 continue;
889 if (!VersionAndInfoSlice.second.SwiftName.empty())
890 return;
891 }
892
893 // Then explicitly call that out with a removal attribute.
894 VersionedInfoMetadata DummyFutureMetadata(
895 SelectedVersion, IsActive_t::Inactive, IsSubstitution_t::Replacement);
896 handleAPINotedAttribute<SwiftNameAttr>(
897 S, D, /*add*/ false, DummyFutureMetadata, []() -> SwiftNameAttr * {
898 llvm_unreachable("should not try to add an attribute here");
899 });
900}
901
902/// Processes all versions of versioned API notes.
903///
904/// Just dispatches to the various ProcessAPINotes functions in this file.
905template <typename SpecificDecl, typename SpecificInfo>
906static void ProcessVersionedAPINotes(
907 Sema &S, SpecificDecl *D,
908 const api_notes::APINotesReader::VersionedInfo<SpecificInfo> Info) {
909
910 if (!S.captureSwiftVersionIndependentAPINotes())
911 maybeAttachUnversionedSwiftName(S, D, Info);
912
913 unsigned Selected = Info.getSelected().value_or(Info.size());
914
915 VersionTuple Version;
916 SpecificInfo InfoSlice;
917 for (unsigned i = 0, e = Info.size(); i != e; ++i) {
918 std::tie(Version, InfoSlice) = Info[i];
919 auto Active = (i == Selected) ? IsActive_t::Active : IsActive_t::Inactive;
920 auto Replacement = IsSubstitution_t::Original;
921
922 // When collecting all APINotes as version-independent,
923 // capture all as inactive and defer to the client to select the
924 // right one.
925 if (S.captureSwiftVersionIndependentAPINotes()) {
926 Active = IsActive_t::Inactive;
927 Replacement = IsSubstitution_t::Original;
928 } else if (Active == IsActive_t::Inactive && Version.empty()) {
929 Replacement = IsSubstitution_t::Replacement;
930 Version = Info[Selected].first;
931 }
932
933 ProcessAPINotes(S, D, InfoSlice,
934 VersionedInfoMetadata(Version, Active, Replacement));
935 }
936}
937
938static std::optional<api_notes::Context>
939UnwindNamespaceContext(DeclContext *DC, api_notes::APINotesManager &APINotes) {
940 if (auto NamespaceContext = dyn_cast<NamespaceDecl>(Val: DC)) {
941 for (auto Reader : APINotes.findAPINotes(Loc: NamespaceContext->getLocation())) {
942 // Retrieve the context ID for the parent namespace of the decl.
943 std::stack<NamespaceDecl *> NamespaceStack;
944 {
945 for (auto CurrentNamespace = NamespaceContext; CurrentNamespace;
946 CurrentNamespace =
947 dyn_cast<NamespaceDecl>(Val: CurrentNamespace->getParent())) {
948 if (!CurrentNamespace->isInlineNamespace())
949 NamespaceStack.push(x: CurrentNamespace);
950 }
951 }
952 std::optional<api_notes::ContextID> NamespaceID;
953 while (!NamespaceStack.empty()) {
954 auto CurrentNamespace = NamespaceStack.top();
955 NamespaceStack.pop();
956 NamespaceID =
957 Reader->lookupNamespaceID(Name: CurrentNamespace->getName(), ParentNamespaceID: NamespaceID);
958 if (!NamespaceID)
959 return std::nullopt;
960 }
961 if (NamespaceID)
962 return api_notes::Context(*NamespaceID,
963 api_notes::ContextKind::Namespace);
964 }
965 }
966 return std::nullopt;
967}
968
969static std::optional<api_notes::Context>
970UnwindTagContext(TagDecl *DC, api_notes::APINotesManager &APINotes) {
971 assert(DC && "tag context must not be null");
972 for (auto Reader : APINotes.findAPINotes(Loc: DC->getLocation())) {
973 // Retrieve the context ID for the parent tag of the decl.
974 std::stack<TagDecl *> TagStack;
975 {
976 for (auto CurrentTag = DC; CurrentTag;
977 CurrentTag = dyn_cast<TagDecl>(Val: CurrentTag->getParent()))
978 TagStack.push(x: CurrentTag);
979 }
980 assert(!TagStack.empty());
981 std::optional<api_notes::Context> Ctx =
982 UnwindNamespaceContext(DC: TagStack.top()->getDeclContext(), APINotes);
983 while (!TagStack.empty()) {
984 auto CurrentTag = TagStack.top();
985 TagStack.pop();
986 auto CtxID = Reader->lookupTagID(Name: CurrentTag->getName(), ParentCtx: Ctx);
987 if (!CtxID)
988 return std::nullopt;
989 Ctx = api_notes::Context(*CtxID, api_notes::ContextKind::Tag);
990 }
991 return Ctx;
992 }
993 return std::nullopt;
994}
995
996/// Process API notes that are associated with this declaration, mapping them
997/// to attributes as appropriate.
998void Sema::ProcessAPINotes(Decl *D) {
999 if (!D)
1000 return;
1001 if (!APINotes.hasAPINotes())
1002 return;
1003 auto Readers = APINotes.findAPINotes(Loc: D->getLocation());
1004 if (Readers.empty())
1005 return;
1006
1007 auto *DC = D->getDeclContext();
1008 // Globals.
1009 if (DC->isFileContext() || DC->isNamespace() ||
1010 DC->getDeclKind() == Decl::LinkageSpec) {
1011 std::optional<api_notes::Context> APINotesContext =
1012 UnwindNamespaceContext(DC, APINotes);
1013 // Global variables.
1014 if (auto VD = dyn_cast<VarDecl>(Val: D)) {
1015 for (auto Reader : Readers) {
1016 auto Info =
1017 Reader->lookupGlobalVariable(Name: VD->getName(), Ctx: APINotesContext);
1018 ProcessVersionedAPINotes(S&: *this, D: VD, Info);
1019 }
1020
1021 return;
1022 }
1023
1024 // Global functions.
1025 if (auto FD = dyn_cast<FunctionDecl>(Val: D)) {
1026 if (FD->getDeclName().isIdentifier()) {
1027 for (auto Reader : Readers) {
1028 auto Info =
1029 Reader->lookupGlobalFunction(Name: FD->getName(), Ctx: APINotesContext);
1030 ProcessVersionedAPINotes(S&: *this, D: FD, Info);
1031 }
1032 }
1033
1034 return;
1035 }
1036
1037 // Objective-C classes.
1038 if (auto Class = dyn_cast<ObjCInterfaceDecl>(Val: D)) {
1039 for (auto Reader : Readers) {
1040 auto Info = Reader->lookupObjCClassInfo(Name: Class->getName());
1041 ProcessVersionedAPINotes(S&: *this, D: Class, Info);
1042 }
1043
1044 return;
1045 }
1046
1047 // Objective-C protocols.
1048 if (auto Protocol = dyn_cast<ObjCProtocolDecl>(Val: D)) {
1049 for (auto Reader : Readers) {
1050 auto Info = Reader->lookupObjCProtocolInfo(Name: Protocol->getName());
1051 ProcessVersionedAPINotes(S&: *this, D: Protocol, Info);
1052 }
1053
1054 return;
1055 }
1056
1057 // Tags
1058 if (auto Tag = dyn_cast<TagDecl>(Val: D)) {
1059 // Determine the name of the entity to search for. If this is an
1060 // anonymous tag that gets its linked name from a typedef, look for the
1061 // typedef name. This allows tag-specific information to be added
1062 // to the declaration.
1063 std::string LookupName;
1064 if (auto typedefName = Tag->getTypedefNameForAnonDecl())
1065 LookupName = typedefName->getName().str();
1066 else
1067 LookupName = Tag->getName().str();
1068
1069 // Use the source location to discern if this Tag is an OPTIONS macro.
1070 // For now we would like to limit this trick of looking up the APINote tag
1071 // using the EnumDecl's QualType in the case where the enum is anonymous.
1072 // This is only being used to support APINotes lookup for C++
1073 // NS/CF_OPTIONS when C++-Interop is enabled.
1074 std::string MacroName =
1075 LookupName.empty() && Tag->getOuterLocStart().isMacroID()
1076 ? clang::Lexer::getImmediateMacroName(
1077 Loc: Tag->getOuterLocStart(),
1078 SM: Tag->getASTContext().getSourceManager(), LangOpts)
1079 .str()
1080 : "";
1081
1082 if (LookupName.empty() && isa<clang::EnumDecl>(Val: Tag) &&
1083 (MacroName == "CF_OPTIONS" || MacroName == "NS_OPTIONS" ||
1084 MacroName == "OBJC_OPTIONS" || MacroName == "SWIFT_OPTIONS")) {
1085
1086 clang::QualType T = llvm::cast<clang::EnumDecl>(Val: Tag)->getIntegerType();
1087 LookupName = clang::QualType::getAsString(
1088 split: T.split(), Policy: getASTContext().getPrintingPolicy());
1089 }
1090
1091 for (auto Reader : Readers) {
1092 if (auto ParentTag = dyn_cast<TagDecl>(Val: Tag->getDeclContext()))
1093 APINotesContext = UnwindTagContext(DC: ParentTag, APINotes);
1094 auto Info = Reader->lookupTag(Name: LookupName, Ctx: APINotesContext);
1095 ProcessVersionedAPINotes(S&: *this, D: Tag, Info);
1096 }
1097
1098 return;
1099 }
1100
1101 // Typedefs
1102 if (auto Typedef = dyn_cast<TypedefNameDecl>(Val: D)) {
1103 for (auto Reader : Readers) {
1104 auto Info = Reader->lookupTypedef(Name: Typedef->getName(), Ctx: APINotesContext);
1105 ProcessVersionedAPINotes(S&: *this, D: Typedef, Info);
1106 }
1107
1108 return;
1109 }
1110 }
1111
1112 // Enumerators.
1113 if (DC->getRedeclContext()->isFileContext() ||
1114 DC->getRedeclContext()->isExternCContext()) {
1115 if (auto EnumConstant = dyn_cast<EnumConstantDecl>(Val: D)) {
1116 for (auto Reader : Readers) {
1117 auto Info = Reader->lookupEnumConstant(Name: EnumConstant->getName());
1118 ProcessVersionedAPINotes(S&: *this, D: EnumConstant, Info);
1119 }
1120
1121 return;
1122 }
1123 }
1124
1125 if (auto ObjCContainer = dyn_cast<ObjCContainerDecl>(Val: DC)) {
1126 // Location function that looks up an Objective-C context.
1127 auto GetContext = [&](api_notes::APINotesReader *Reader)
1128 -> std::optional<api_notes::ContextID> {
1129 if (auto Protocol = dyn_cast<ObjCProtocolDecl>(Val: ObjCContainer)) {
1130 if (auto Found = Reader->lookupObjCProtocolID(Name: Protocol->getName()))
1131 return *Found;
1132
1133 return std::nullopt;
1134 }
1135
1136 if (auto Impl = dyn_cast<ObjCCategoryImplDecl>(Val: ObjCContainer)) {
1137 if (auto Cat = Impl->getCategoryDecl())
1138 ObjCContainer = Cat->getClassInterface();
1139 else
1140 return std::nullopt;
1141 }
1142
1143 if (auto Category = dyn_cast<ObjCCategoryDecl>(Val: ObjCContainer)) {
1144 if (Category->getClassInterface())
1145 ObjCContainer = Category->getClassInterface();
1146 else
1147 return std::nullopt;
1148 }
1149
1150 if (auto Impl = dyn_cast<ObjCImplDecl>(Val: ObjCContainer)) {
1151 if (Impl->getClassInterface())
1152 ObjCContainer = Impl->getClassInterface();
1153 else
1154 return std::nullopt;
1155 }
1156
1157 if (auto Class = dyn_cast<ObjCInterfaceDecl>(Val: ObjCContainer)) {
1158 if (auto Found = Reader->lookupObjCClassID(Name: Class->getName()))
1159 return *Found;
1160
1161 return std::nullopt;
1162 }
1163
1164 return std::nullopt;
1165 };
1166
1167 // Objective-C methods.
1168 if (auto Method = dyn_cast<ObjCMethodDecl>(Val: D)) {
1169 for (auto Reader : Readers) {
1170 if (auto Context = GetContext(Reader)) {
1171 // Map the selector.
1172 Selector Sel = Method->getSelector();
1173 SmallVector<StringRef, 2> SelPieces;
1174 if (Sel.isUnarySelector()) {
1175 SelPieces.push_back(Elt: Sel.getNameForSlot(argIndex: 0));
1176 } else {
1177 for (unsigned i = 0, n = Sel.getNumArgs(); i != n; ++i)
1178 SelPieces.push_back(Elt: Sel.getNameForSlot(argIndex: i));
1179 }
1180
1181 api_notes::ObjCSelectorRef SelectorRef;
1182 SelectorRef.NumArgs = Sel.getNumArgs();
1183 SelectorRef.Identifiers = SelPieces;
1184
1185 auto Info = Reader->lookupObjCMethod(CtxID: *Context, Selector: SelectorRef,
1186 IsInstanceMethod: Method->isInstanceMethod());
1187 ProcessVersionedAPINotes(S&: *this, D: Method, Info);
1188 }
1189 }
1190 }
1191
1192 // Objective-C properties.
1193 if (auto Property = dyn_cast<ObjCPropertyDecl>(Val: D)) {
1194 for (auto Reader : APINotes.findAPINotes(Loc: D->getLocation())) {
1195 if (auto Context = GetContext(Reader)) {
1196 bool isInstanceProperty =
1197 (Property->getPropertyAttributesAsWritten() &
1198 ObjCPropertyAttribute::kind_class) == 0;
1199 auto Info = Reader->lookupObjCProperty(CtxID: *Context, Name: Property->getName(),
1200 IsInstance: isInstanceProperty);
1201 ProcessVersionedAPINotes(S&: *this, D: Property, Info);
1202 }
1203 }
1204
1205 return;
1206 }
1207 }
1208
1209 if (auto TagContext = dyn_cast<TagDecl>(Val: DC)) {
1210 if (auto CXXMethod = dyn_cast<CXXMethodDecl>(Val: D)) {
1211 if (!isa<CXXConstructorDecl>(Val: CXXMethod) &&
1212 !isa<CXXDestructorDecl>(Val: CXXMethod) &&
1213 !isa<CXXConversionDecl>(Val: CXXMethod)) {
1214 for (auto Reader : Readers) {
1215 if (auto Context = UnwindTagContext(DC: TagContext, APINotes)) {
1216 std::string MethodName;
1217 if (CXXMethod->isOverloadedOperator())
1218 MethodName =
1219 std::string("operator") +
1220 getOperatorSpelling(Operator: CXXMethod->getOverloadedOperator());
1221 else
1222 MethodName = CXXMethod->getName();
1223
1224 auto Info = Reader->lookupCXXMethod(CtxID: Context->id, Name: MethodName);
1225 ProcessVersionedAPINotes(S&: *this, D: CXXMethod, Info);
1226 }
1227 }
1228 }
1229 }
1230
1231 if (auto Field = dyn_cast<FieldDecl>(Val: D)) {
1232 if (!Field->isUnnamedBitField() && !Field->isAnonymousStructOrUnion()) {
1233 for (auto Reader : Readers) {
1234 if (auto Context = UnwindTagContext(DC: TagContext, APINotes)) {
1235 auto Info = Reader->lookupField(CtxID: Context->id, Name: Field->getName());
1236 ProcessVersionedAPINotes(S&: *this, D: Field, Info);
1237 }
1238 }
1239 }
1240 }
1241
1242 if (auto Tag = dyn_cast<TagDecl>(Val: D)) {
1243 for (auto Reader : Readers) {
1244 if (auto Context = UnwindTagContext(DC: TagContext, APINotes)) {
1245 auto Info = Reader->lookupTag(Name: Tag->getName(), Ctx: Context);
1246 ProcessVersionedAPINotes(S&: *this, D: Tag, Info);
1247 }
1248 }
1249 }
1250 }
1251}
1252