Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 0 additions & 12 deletions docs/ReferenceGuides/UnderscoredAttributes.md
Original file line number Diff line number Diff line change
Expand Up @@ -1117,12 +1117,6 @@ if it is never explicitly bound using a typed pointer method like
bound, it must only be used with compatible typed memory accesses for as long
as the binding is active.

## `@_section("section_name")`

Places a global variable or a top-level function into a section of the object
file with the given name. It's the equivalent of clang's
`__attribute__((section))`.

## `@_semantics("uniquely.recognized.id")`

Allows the optimizer to make use of some key invariants in performance critical
Expand Down Expand Up @@ -1320,12 +1314,6 @@ for more details.

This `async` function uses the pre-SE-0338 semantics of unsafely inheriting the caller's executor. This is an underscored feature because the right way of inheriting an executor is to pass in the required executor and switch to it. Unfortunately, there are functions in the standard library which need to inherit their caller's executor but cannot change their ABI because they were not defined as `@_alwaysEmitIntoClient` in the initial release.

## `@_used`

Marks a global variable or a top-level function as "used externally" even if it
does not have visible users in the compilation unit. It's the equivalent of
clang's `__attribute__((used))`.

## `@_weakLinked`

Allows a declaration to be weakly-referenced, i.e., any references emitted by
Expand Down
2 changes: 1 addition & 1 deletion include/swift/AST/Attr.h
Original file line number Diff line number Diff line change
Expand Up @@ -714,7 +714,7 @@ class SILGenNameAttr : public DeclAttribute {
}
};

/// Defines the @_section attribute.
/// Defines the @section attribute.
class SectionAttr : public DeclAttribute {
public:
SectionAttr(StringRef Name, SourceLoc AtLoc, SourceRange Range, bool Implicit)
Expand Down
4 changes: 2 additions & 2 deletions include/swift/AST/DeclAttr.def
Original file line number Diff line number Diff line change
Expand Up @@ -753,12 +753,12 @@ DECL_ATTR(attached, MacroRole,
142)
DECL_ATTR_ALIAS(freestanding, MacroRole)

SIMPLE_DECL_ATTR(_used, Used,
SIMPLE_DECL_ATTR(used, Used,
OnAbstractFunction | OnVar,
UserInaccessible | ABIBreakingToAdd | ABIBreakingToRemove | APIBreakingToAdd | APIBreakingToRemove | ForbiddenInABIAttr,
143)

DECL_ATTR(_section, Section,
DECL_ATTR(section, Section,
OnAbstractFunction | OnVar,
UserInaccessible | ABIBreakingToAdd | ABIBreakingToRemove | APIBreakingToAdd | APIBreakingToRemove | ForbiddenInABIAttr,
144)
Expand Down
30 changes: 14 additions & 16 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -826,29 +826,29 @@ ERROR(expect_compile_time_literal,none,
"expect a compile-time constant literal", ())

ERROR(const_unsupported_enum_associated_value,none,
"enums with associated values not supported in a '@const' expression", ())
"enums with associated values not supported in a constant expression", ())
ERROR(const_unsupported_operator,none,
"unsupported operator in a '@const' expression", ())
"unsupported operator in a constant expression", ())
ERROR(const_unsupported_type,none,
"unsupported type in a '@const' expression", ())
"unsupported type in a constant expression", ())
ERROR(const_unsupported_type_expr,none,
"type expressions not supported in a '@const' expression", ())
"type expressions not supported in a constant expression", ())
ERROR(const_unsupported_closure,none,
"closures not supported in a '@const' expression", ())
"closures not supported in a constant expression", ())
ERROR(const_unsupported_keypath,none,
"keypaths not supported in a '@const' expression", ())
"keypaths not supported in a constant expression", ())
ERROR(const_opaque_decl_ref,none,
"unable to resolve variable reference in a '@const' expression", ())
"unable to resolve variable reference in a constant expression", ())
ERROR(const_opaque_func_decl_ref,none,
"unable to resolve function reference in a '@const' expression", ())
"unable to resolve function reference in a constant expression", ())
ERROR(const_non_convention_c_conversion,none,
"only 'convention(c)' function values are supported in a '@const' expression", ())
"only 'convention(c)' function values are supported in a constant expression", ())
ERROR(const_opaque_callee,none,
"unable to resolve callee in a '@const' expression", ())
"unable to resolve callee in a constant expression", ())
ERROR(const_non_const_param,none,
"reference to a non-'@const' parameter in a '@const' expression", ())
"reference to a non-'@const' parameter in a constant expression", ())
ERROR(const_unknown_default,none,
"not supported in a '@const' expression", ())
"not supported in a constant expression", ())

//------------------------------------------------------------------------------
// MARK: Import Resolution
Expand Down Expand Up @@ -2097,11 +2097,9 @@ ERROR(cdecl_feature_required,none,
"'@c' requires '-enable-experimental-feature CDecl'",
())

// @_used and @_section
ERROR(section_linkage_markers_disabled,none,
"attribute requires '-enable-experimental-feature SymbolLinkageMarkers'", ())
// @used and @section
ERROR(section_empty_name,none,
"'@_section' section name cannot be empty", ())
"'@section' section name cannot be empty", ())

// @_silgen_name and friends
WARNING(reserved_runtime_symbol_name,none,
Expand Down
3 changes: 0 additions & 3 deletions include/swift/Basic/Features.def
Original file line number Diff line number Diff line change
Expand Up @@ -323,9 +323,6 @@ EXPERIMENTAL_FEATURE(FullTypedThrows, false)
EXPERIMENTAL_FEATURE(SameElementRequirements, false)
EXPERIMENTAL_FEATURE(KeyPathWithMethodMembers, false)

// Whether to enable @_used and @_section attributes
EXPERIMENTAL_FEATURE(SymbolLinkageMarkers, true)

// Whether to emit an Embedded Swift module with "deferred" code generation,
// meaning that the only code that will be emitted into the object file is
// code that was marked as "never emit into client". For everything else,
Expand Down
2 changes: 1 addition & 1 deletion include/swift/IRGen/Linking.h
Original file line number Diff line number Diff line change
Expand Up @@ -1850,7 +1850,7 @@ class LinkEntity {
///
/// This applies only in the Embedded Swift linkage model, and is used for
/// any symbols that have not been explicitly requested to have unique
/// definitions (e.g., with @_used).
/// definitions (e.g., with @used).
bool hasNonUniqueDefinition() const;

#undef LINKENTITY_GET_FIELD
Expand Down
8 changes: 4 additions & 4 deletions include/swift/SIL/SILFunction.h
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ class SILFunction
/// If empty, use the SIL function's name directly.
StringRef AsmName;

/// Name of a section if @_section attribute was used, otherwise empty.
/// Name of a section if @section attribute was used, otherwise empty.
StringRef Section;

/// Name of a Wasm export if @_expose(wasm) attribute was used, otherwise
Expand Down Expand Up @@ -396,7 +396,7 @@ class SILFunction
/// would indicate.
unsigned HasCReferences : 1;

/// Whether attribute @_used was present
/// Whether attribute @used was present
unsigned MarkedAsUsed : 1;

/// Whether cross-module references to this function should always use weak
Expand Down Expand Up @@ -1424,15 +1424,15 @@ class SILFunction
return V && V->getAttrs().hasAttribute<AlwaysEmitIntoClientAttr>();
}

/// Return whether this function has attribute @_used on it
/// Return whether this function has attribute @used on it
bool markedAsUsed() const { return MarkedAsUsed; }
void setMarkedAsUsed(bool value) { MarkedAsUsed = value; }

/// Return custom assembler name, otherwise empty.
StringRef asmName() const { return AsmName; }
void setAsmName(StringRef value) { AsmName = value; }

/// Return custom section name if @_section was used, otherwise empty
/// Return custom section name if @section was used, otherwise empty
StringRef section() const { return Section; }
void setSection(StringRef value) { Section = value; }

Expand Down
8 changes: 4 additions & 4 deletions include/swift/SIL/SILGlobalVariable.h
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class SILGlobalVariable
/// the mangled name of the variable will be used instead.
StringRef AsmName;

/// Name of a section if @_section attribute was used, otherwise empty.
/// Name of a section if @section attribute was used, otherwise empty.
StringRef Section;

/// The lowered type of the variable.
Expand All @@ -86,7 +86,7 @@ class SILGlobalVariable
/// once (either in its declaration, or once later), making it immutable.
unsigned IsLet : 1;

/// Whether this declaration was marked `@_used`, meaning that it should be
/// Whether this declaration was marked `@used`, meaning that it should be
/// added to the llvm.used list.
unsigned IsUsed : 1;

Expand Down Expand Up @@ -162,7 +162,7 @@ class SILGlobalVariable
StringRef asmName() const { return AsmName; }
void setAsmName(StringRef value) { AsmName = value; }

/// Return custom section name if @_section was used, otherwise empty
/// Return custom section name if @section was used, otherwise empty
StringRef section() const { return Section; }
void setSection(StringRef value) { Section = value; }

Expand Down Expand Up @@ -242,7 +242,7 @@ class SILGlobalVariable
StaticInitializerBlock.eraseAllInstructions(Module);
}

/// Returns true if this global variable has `@_used` attribute.
/// Returns true if this global variable has `@used` attribute.
bool markedAsUsed() const { return IsUsed; }

void setMarkedAsUsed(bool used) { IsUsed = used; }
Expand Down
4 changes: 2 additions & 2 deletions lib/AST/Attr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1323,7 +1323,7 @@ bool DeclAttribute::printImpl(ASTPrinter &Printer, const PrintOptions &Options,
}

case DeclAttrKind::Section:
Printer.printAttrName("@_section");
Printer.printAttrName("@section");
Printer << "(\"" << cast<SectionAttr>(this)->Name << "\")";
break;

Expand Down Expand Up @@ -1977,7 +1977,7 @@ StringRef DeclAttribute::getAttrName() const {
case DeclAttrKind::Expose:
return "_expose";
case DeclAttrKind::Section:
return "_section";
return "section";
case DeclAttrKind::Documentation:
return "_documentation";
case DeclAttrKind::Nonisolated:
Expand Down
2 changes: 1 addition & 1 deletion lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1342,7 +1342,7 @@ bool AbstractStorageDecl::isCompileTimeLiteral() const {
}

bool AbstractStorageDecl::isConstValue() const {
return getAttrs().hasAttribute<ConstValAttr>();
return getAttrs().hasAttribute<ConstValAttr>() || getAttrs().hasAttribute<SectionAttr>();
}

bool AbstractStorageDecl::isTransparent() const {
Expand Down
1 change: 0 additions & 1 deletion lib/AST/FeatureSet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ UNINTERESTING_FEATURE(FlowSensitiveConcurrencyCaptures)
UNINTERESTING_FEATURE(CodeItemMacros)
UNINTERESTING_FEATURE(PreambleMacros)
UNINTERESTING_FEATURE(TupleConformances)
UNINTERESTING_FEATURE(SymbolLinkageMarkers)
UNINTERESTING_FEATURE(DeferredCodeGen)
UNINTERESTING_FEATURE(LazyImmediate)
UNINTERESTING_FEATURE(MoveOnlyClasses)
Expand Down
2 changes: 1 addition & 1 deletion lib/ASTGen/Sources/ASTGen/DeclAttrs.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1024,7 +1024,7 @@ extension ASTGenVisitor {

/// E.g.
/// ```
/// @_section("__TEXT,__mysection")
/// @section("__TEXT,__mysection")
/// ```
func generateSectionAttr(attribute node: AttributeSyntax) -> BridgedSectionAttr? {
return self.generateWithLabeledExprListArguments(attribute: node) { args in
Expand Down
4 changes: 2 additions & 2 deletions lib/IRGen/GenDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2860,7 +2860,7 @@ Address IRGenModule::getAddrOfSILGlobalVariable(SILGlobalVariable *var,
if (!forDefinition)
gvar->setComdat(nullptr);

// Mark as llvm.used if @_used, set section if @_section
// Mark as llvm.used if @used, set section if @section
if (var->markedAsUsed())
addUsedGlobal(gvar);
else if (var->shouldBePreservedForDebugger() && forDefinition)
Expand Down Expand Up @@ -3734,7 +3734,7 @@ llvm::Function *IRGenModule::getAddrOfSILFunction(
fn = createFunction(*this, link, signature, insertBefore,
f->getOptimizationMode(), shouldEmitStackProtector(f));

// Mark as llvm.used if @_used, set section if @_section
// Mark as llvm.used if @used, set section if @section
if (f->markedAsUsed())
addUsedGlobal(fn);

Expand Down
28 changes: 19 additions & 9 deletions lib/Macros/Sources/SwiftMacros/DebugDescriptionMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -252,17 +252,17 @@ extension _DebugDescriptionPropertyMacro: PeerMacro {
let summaryString = summarySegments.joined()

// Serialize the type summary into a global record, in a custom section, for LLDB to load.
let (encodedValue, encodedType) = encodeTypeSummaryRecord(typeIdentifier, summaryString)
let decl: DeclSyntax = """
#if !os(Windows)
#if os(Linux)
@_section(".lldbsummaries")
@section(".lldbsummaries")
#else
@_section("__TEXT,__lldbsummaries")
@section("__TEXT,__lldbsummaries")
#endif
@_used
static let _lldb_summary = (
\(raw: encodeTypeSummaryRecord(typeIdentifier, summaryString))
)
@used
static let _lldb_summary: \(raw: encodedType) =
\(raw: encodedValue)
#endif
"""

Expand Down Expand Up @@ -303,23 +303,33 @@ fileprivate let ENCODING_VERSION: UInt = 1
///
/// The strings (type identifier and summary) are encoded with both a length prefix (also ULEB)
/// and with a null terminator.
fileprivate func encodeTypeSummaryRecord(_ typeIdentifier: String, _ summaryString: String) -> String {
fileprivate func encodeTypeSummaryRecord(_ typeIdentifier: String, _ summaryString: String) -> (valueString: String, typeString: String) {
let encodedIdentifier = typeIdentifier.byteEncoded
let encodedSummary = summaryString.byteEncoded
let recordSize = UInt(encodedIdentifier.count + encodedSummary.count)
return """
return (valueString: """
(
/* version */ \(swiftLiteral: ENCODING_VERSION.ULEBEncoded),
/* record size */ \(swiftLiteral: recordSize.ULEBEncoded),
/* "\(typeIdentifier)" */ \(swiftLiteral: encodedIdentifier),
/* "\(summaryString)" */ \(swiftLiteral: encodedSummary)
)
""",
typeString: """
(
\(Array(repeating: "UInt8", count: ENCODING_VERSION.ULEBEncoded.count +
recordSize.ULEBEncoded.count + encodedIdentifier.count +
encodedSummary.count).joined(separator: ", "))
)
"""
)
}

extension DefaultStringInterpolation {
/// Generate a _partial_ Swift literal from the given bytes. It is partial in that must be embedded
/// into some other syntax, specifically as a tuple.
fileprivate mutating func appendInterpolation(swiftLiteral bytes: [UInt8]) {
let literalBytes = bytes.map({ "\($0) as UInt8" }).joined(separator: ", ")
let literalBytes = bytes.map({ "\($0)" }).joined(separator: ", ")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it idiomatic to use interpolation for the case where a single variable is being converted to a string ("\($0)")?

appendInterpolation(literalBytes)
}
}
Expand Down
8 changes: 7 additions & 1 deletion lib/Parse/ParseDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3211,7 +3211,7 @@ ParserStatus Parser::parseNewDeclAttribute(DeclAttributes &Attributes,
return makeParserSuccess();
}

// @_section in a local scope is not allowed.
// @section in a local scope is not allowed.
if (CurDeclContext->isLocalContext()) {
diagnose(Loc, diag::attr_name_only_at_non_local_scope, AttrName);
}
Expand Down Expand Up @@ -4349,6 +4349,12 @@ ParserStatus Parser::parseDeclAttribute(DeclAttributes &Attributes,
checkInvalidAttrName("_functionBuilder", "resultBuilder",
DeclAttrKind::ResultBuilder, diag::attr_renamed_warning);

// Historical name for @section and @used
checkInvalidAttrName("_section", "section", DeclAttrKind::Section,
diag::attr_renamed_warning);
checkInvalidAttrName("_used", "used", DeclAttrKind::Used,
diag::attr_renamed_warning);

// Historical name for 'nonisolated'.
if (!DK && Tok.getText() == "actorIndependent") {
diagnose(
Expand Down
2 changes: 1 addition & 1 deletion lib/SIL/IR/SILDeclRef.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1217,7 +1217,7 @@ bool SILDeclRef::declHasNonUniqueDefinition(const ValueDecl *decl) {
return false;
}

// - @_section and @_used imply that external tools will look for this symbol.
// - @section and @used imply that external tools will look for this symbol.
if (decl->getAttrs().hasAttribute<SectionAttr>() ||
decl->getAttrs().hasAttribute<UsedAttr>()) {
return false;
Expand Down
4 changes: 2 additions & 2 deletions lib/SILOptimizer/Mandatory/PerformanceDiagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,7 @@ class PerformanceDiagnosticsPass : public SILModuleTransform {

PerformanceDiagnostics diagnoser(*module, getAnalysis<BasicCalleeAnalysis>());

// Check that @_section, @_silgen_name is only on constant globals
// Check that @section, @_silgen_name is only on constant globals
for (SILGlobalVariable &g : module->getSILGlobals()) {
if (!g.getStaticInitializerValue() && g.mustBeInitializedStatically()) {
PrettyStackTraceSILGlobal stackTrace(
Expand All @@ -733,7 +733,7 @@ class PerformanceDiagnosticsPass : public SILModuleTransform {
if (!g.section().empty()) {
module->getASTContext().Diags.diagnose(
g.getDecl()->getLoc(), diag::bad_attr_on_non_const_global,
"@_section");
"@section");
} else if (decl && g.isDefinition() &&
decl->getAttrs().hasAttribute<SILGenNameAttr>()) {
module->getASTContext().Diags.diagnose(
Expand Down
4 changes: 2 additions & 2 deletions lib/SILOptimizer/UtilityPasses/Link.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ class SILLinker : public SILModuleTransform {
linkEmbeddedConcurrency();
}

// In embedded Swift, we need to explicitly link any @_used globals and
// In embedded Swift, we need to explicitly link any @used globals and
// functions from imported modules.
if (M.getOptions().EmbeddedSwift && LinkUsedFunctions) {
linkUsedGlobalsAndFunctions();
Expand Down Expand Up @@ -230,7 +230,7 @@ class SILLinker : public SILModuleTransform {
} else if (VarDecl *G = dyn_cast<VarDecl>(D)) {
Globals.push_back(G);
} else {
assert(false && "only funcs and globals can be @_used");
assert(false && "only funcs and globals can be @used");
}
}
}
Expand Down
Loading