Commit Graph

431 Commits

Author SHA1 Message Date
Ben Cohen 0efa0b5eaf IRGen: guard against null clang type when emitting lazy ObjC protocol metadata (#88817)
- **Explanation**: Fix a compiler crash when a module imports `Dispatch`
(without `Foundation`) and holds a `DispatchSourceTimer?`-typed property
under Swift 6 mode. IRGen was dereferencing a null `clang::CanQualType`
when emitting lazy metadata for `NSObjectProtocol.description` /
  `.debugDescription`.                                      

- **Scope**: Three local null-guards in `lib/IRGen/GenObjC.cpp`
(`emitObjCGetterDescriptorParts(VarDecl *)`,
`emitObjCSetterDescriptorParts(VarDecl *)`,
`getObjCEncodingForPropertyType`). No change when `getObjCPropertyType`
returns a valid type.
 
- **Issues**: Reported against Xcode 6.0, 6.1, and 6.2 toolchains on
macOS. Does not reproduce on Linux or with `.swiftLanguageMode(.v5)`.
Minimal repro: `import Dispatch` + `class C { fileprivate var timer:
DispatchSourceTimer? }`.

- **Risk**: Very low. Local null-guards on a known-fragile path. Full
IRGen suite (1031 tests) passes. The placeholder metadata emitted in the
guarded case is never dispatched through at runtime (the real
`NSObjectProtocol` comes from Objective-C).
                                     
- **Testing**: New
`test/IRGen/objc_protocol_lazy_definition_null_clang_type.swift`
compiles the reproducer under `-swift-version 6` and checks
`MyClass.timer.getter`'s IR is emitted. Verified the crash reproduces
without the fix and is gone with it.

The root cause sits in SIL type lowering: for
`NSObjectProtocol.description`'s foreign getter,
`TypeConverter::getLoweredCBridgedType` looks up `String:
_ObjectiveCBridgeable` through the user's module, and the conformance
(defined in Foundation) isn't visible when Foundation isn't imported.
The principled fix (widen the bridging-conformance lookup for well-known
bridged Swift types will be a follow-up that doesn't need to go to 6.4.
2026-05-05 05:48:08 -07:00
Gabor Horvath 64fb3cb925 [cxx-interop] Fix a missing offset adjustment when calling FRTs
We already generate forwarding methods that can fix up the base offset
when we call base methods. Unfortunately, these forwarding methods were
not used when we emitted a call to a refcount operation of a foreign
reference type where the annotation is on the type itself but the
operation was inherited from a base.

rdar://173210238
2026-03-24 16:36:37 +00:00
Slava Pestov d09c773536 IRGen: Fix yet another typed throws crash
- Fixes https://github.com/swiftlang/swift/issues/86347.
2026-01-08 14:20:42 -05:00
Meghana Gupta a0c939bd3b Use @inout result convention for mutate accessors 2025-10-20 09:05:32 -07:00
Ellis Hoag 2c919e138e [ObjC][Gen] Emit ObjC strings to respective sections (#84300)
Clang emits ObjC strings into special sections

https://github.com/llvm/llvm-project/blob/d5e7c27d53887e6ae490d8e26193a54987728458/clang/lib/CodeGen/CGObjCMac.cpp#L4056-L4072

As far as I can tell from `CGObjCMac.cpp`:
* types go into `__objc_methtype`
* class, category, and protocol names go into `__objc_classname`
* method names, property names, and property types go into
`__objc_methname`

See also https://github.com/swiftlang/swift/pull/84236.
2025-09-30 08:42:11 -07:00
Egor Zhdan e78ce6165f [cxx-interop] Allow retain/release operations to be methods
Some foreign reference types such as IUnknown define retain/release operations as methods of the type.

Previously Swift only supported retain/release operations as standalone functions.

The syntax for member functions would be `SWIFT_SHARED_REFERENCE(.doRetain, .doRelease)`.

rdar://160696723
2025-09-22 12:01:17 +01:00
Meghana Gupta 1cff471c57 Introduce ResultConvention::Guaranteed and ResultConvention::GuaranteedAddress
ResultConvention::Guaranteed will be used by borrow accessors when the storage type can be returned by value.

ResultConvention::GuaranteedAddress will be used by mutate accessors and borrow accessors when the storage type
cannot be returned by value.
2025-09-09 14:45:40 -07:00
Janat Baig 798c0f51a4 Merge branch 'main' into temp-branch 2025-08-23 11:11:04 -04:00
JanBaig 988a3dcf25 [SIL] Introduce new SILDeclRef 2025-07-29 21:16:11 -04:00
Anthony Latsis f8577a2731 IRGen: Address llvm::Type::getPointerTo deprecation
See https://github.com/llvm/llvm-project/pull/113331.
2025-07-21 12:37:15 +01:00
Nate Chandler d1f1b4c86b [CoroutineAccessors] Use swiftcorocc if available.
When it's available, use an open-coded allocator function that returns
an alloca without popping if the allocator is nullptr and otherwise
calls swift_coro_alloc.  When it's not available, use the malloc
allocator in the synchronous context.
2025-02-27 18:20:53 -08:00
Becca Royal-Gordon 0ce403d680 [NFC] Add some pretty stack traces
These would have helped us to debug rdar://142693093 more quickly.
2025-01-21 17:33:09 -08:00
Konrad `ktoso` Malawski 7d1ce789ad Revert "Revert "Isolated synchronous deinit"" 2024-09-17 17:35:38 +09:00
Alex Hoppen c5aa49ba64 Revert "Isolated synchronous deinit" 2024-09-03 18:11:26 -07:00
Mykola Pokhylets 816d62c972 Merge remote-tracking branch 'upstream/main' into mpokhylets/isolated-deinit
# Conflicts:
#	include/swift/Basic/Features.def
#	lib/SILGen/SILGenDestructor.cpp
#	test/Concurrency/flow_isolation.swift
#	test/abi/macOS/arm64/concurrency.swift
#	test/abi/macOS/x86_64/concurrency.swift
2024-07-11 13:11:59 +02:00
Mykola Pokhylets b189495518 Introduced isolated deinit as a SIL entity 2024-07-11 13:09:05 +02:00
Akira Hatanaka 42bc49d3fe Add a new parameter convention @in_cxx for non-trivial C++ classes that are passed indirectly and destructed by the caller (#73019)
This corresponds to the parameter-passing convention of the Itanium C++
ABI, in which the argument is passed indirectly and possibly modified,
but not destroyed, by the callee.

@in_cxx is handled the same way as @in in callers and @in_guaranteed in
callees. OwnershipModelEliminator emits the call to destroy_addr that is
needed to destroy the argument in the caller.

rdar://122707697
2024-06-27 09:44:04 -07:00
Tim Kientzle 1d961ba22d Add #include "swift/Basic/Assertions.h" to a lot of source files
Although I don't plan to bring over new assertions wholesale
into the current qualification branch, it's entirely possible
that various minor changes in main will use the new assertions;
having this basic support in the release branch will simplify that.
(This is why I'm adding the includes as a separate pass from
rewriting the individual assertions)
2024-06-05 19:37:30 -07:00
Egor Zhdan bd6da5dc64 [cxx-interop][IRGen] Do not try to retain/release a null pointer
This teaches IRGen to only emit a lifetime operation (retain or release) for a C++ foreign reference type if the pointer is not `nullptr`.

Previously the compiler would in some cases emit a release call for `nullptr`, which breaks the assumption that the argument to a custom release function is `_Nonnull`. For instance:
```
var globalOptional: MyRefType? = nil
func foo() { globalOptional = MyRefType.create() }
```
When emitting IR for the assignment operation to `globalOptional`, the compiler would emit code to first retrieve the existing value of `globalOptional` and release it. If the value is `nil`, it does not need to be released.

rdar://97532642
2024-05-07 20:20:45 +01:00
Ben Barham ef8825bfe6 Migrate llvm::Optional to std::optional
LLVM has removed llvm::Optional, move over to std::optional. Also
clang-format to fix up all the renamed #includes.
2024-02-21 11:20:06 -08:00
Arnold Schwaighofer 2f94890e5f IRGen: Remove supportsTypedPointers, getNonOpaquePointerElementType, isOpaqueOrPointeeTypeMatches
Typed pointers are no longer supported by llvm.

rdar://121083958
2024-01-17 07:33:30 -08:00
swift-ci 745d48ad03 Merge remote-tracking branch 'origin/main' into rebranch 2023-10-07 09:34:00 -07:00
Arnold Schwaighofer b0424759d7 Add support for objective c protocol symbolic references
Using symbolic references instead of a text based mangling avoids the
expensive type descriptor scan when objective c protocols are requested.

rdar://111536582
2023-10-05 13:11:32 -07:00
swift-ci 74ccb1c9fd Merge remote-tracking branch 'origin/main' into rebranch 2023-08-23 12:35:53 -07:00
nate-chandler c3b8091815 Revert "Use clang.arc.attachedcall for emission of objc_retainAutoreleasedReturnValue" 2023-08-23 10:11:35 -07:00
swift-ci 73cf37d597 Merge remote-tracking branch 'origin/main' into rebranch 2023-08-16 17:33:42 -07:00
Pavel Yaskevich eee923bc42 [IRGen] [AST] NFC: Remove @runtimeMetadata related code and metadata records 2023-08-15 12:17:31 -07:00
Ben Barham b134541111 [rebranch] Fix API changes from LLVM update
`insert` inserts *before* the given iterator. The `insertAfter` calls
thus need a `std::next` when converted to `insert`.

Resolves rdar://113145355.
2023-08-01 13:10:33 -07:00
Evan Wilde 8ce6ee8dd1 Updating API usages
LLVM deprecated, renamed, and removed a bunch of APIs. This patch
contains a lot of the changes needed to deal with that.

The SetVector type changed the template parameters.

APInt updated multiple names, countPopulation became popcount,
getAllOnesValue became getAllOnes, getNullValue became getZero, etc...

Clang type nullability check stopped taking a clang AST context.

The LLVM IRGen Function type stopped exposing basic block list directly,
but gained enough API surface that the translation isn't too bad.
(GenControl.cpp, LLVMMergeFunctions.cpp)

llvm::Optional had a transform function. That was being used in a couple
of places, so I've added a new implementation under STLExtras that
transforms valid optionals, otherwise it returns nullopt.
2023-07-17 10:53:42 -07:00
Arnold Schwaighofer bb84f17a3d Don't use clang.arc.attachedcall on non-darwin OSs
We have implemented a work-around where we have implemented
objc_retainAutoreleasedReturnValue in a library.  When using
clang.arc.attachedcall llvm might optimize the call to objc_retain which
we have not defined a stub for. (Alternatively, we could define
objc_retain in swift-corelibs-libdispatch/src/swift/DispatchStubs.cc)
2023-07-06 22:29:17 -07:00
Arnold Schwaighofer 2568e45120 Use clang.arc.attachedcall for emission of objc_retainAutoreleasedReturnValue
rdar://110019256
2023-07-06 05:41:20 -07:00
Evan Wilde f3ff561c6f [NFC] add llvm namespace to Optional and None
This is phase-1 of switching from llvm::Optional to std::optional in the
next rebranch. llvm::Optional was removed from upstream LLVM, so we need
to migrate off rather soon. On Darwin, std::optional, and llvm::Optional
have the same layout, so we don't need to be as concerned about ABI
beyond the name mangling. `llvm::Optional` is only returned from one
function in
```
getStandardTypeSubst(StringRef TypeName,
                     bool allowConcurrencyManglings);
```
It's the return value, so it should not impact the mangling of the
function, and the layout is the same as `std::optional`, so it should be
mostly okay. This function doesn't appear to have users, and the ABI was
already broken 2 years ago for concurrency and no one seemed to notice
so this should be "okay".

I'm doing the migration incrementally so that folks working on main can
cherry-pick back to the release/5.9 branch. Once 5.9 is done and locked
away, then we can go through and finish the replacement. Since `None`
and `Optional` show up in contexts where they are not `llvm::None` and
`llvm::Optional`, I'm preparing the work now by going through and
removing the namespace unwrapping and making the `llvm` namespace
explicit. This should make it fairly mechanical to go through and
replace llvm::Optional with std::optional, and llvm::None with
std::nullopt. It's also a change that can be brought onto the
release/5.9 with minimal impact. This should be an NFC change.
2023-06-27 09:03:52 -07:00
Erik Eckstein 24837b4d10 IRGen: change a few enum utility functions to be able to create enums in static initializers
Instead of passing `IRGenFunction`, pass the `IRGenModule` and the `IRBuilder`.
This makes enum creation not dependent on the presence of a function.

NFC, just refactoring.
2023-05-25 16:28:41 +02:00
Arnold Schwaighofer 7646e04bf2 IRGen: Another fix for compiling under opaque pointers 2023-05-11 11:33:48 -07:00
swift-ci 0b49ac49d7 Merge remote-tracking branch 'origin/main' into rebranch 2023-01-29 10:33:27 -08:00
John McCall d25a8aec8b Add explicit lowering for value packs and pack expansions.
- SILPackType carries whether the elements are stored directly
  in the pack, which we're not currently using in the lowering,
  but it's probably something we'll want in the final ABI.
  Having this also makes it clear that we're doing the right
  thing with substitution and element lowering.  I also toyed
  with making this a scalar type, which made it necessary in
  various places, although eventually I pulled back to the
  design where we always use packs as addresses.

- Pack boundaries are a core ABI concept, so the lowering has
  to wrap parameter pack expansions up as packs.  There are huge
  unimplemented holes here where the abstraction pattern will
  need to tell us how many elements to gather into the pack,
  but a naive approach is good enough to get things off the
  ground.

- Pack conventions are related to the existing parameter and
  result conventions, but they're different on enough grounds
  that they deserve to be separated.
2023-01-29 03:29:06 -05:00
swift-ci f476abf4a1 Merge remote-tracking branch 'origin/main' into rebranch 2022-12-20 17:13:36 -08:00
Pavel Yaskevich b83b0943b5 [SILDeclRef] RuntimeMetadata: Add a special kind for runtime attribute generator
A new `RuntimeAttributeGenerator` is used to reference runtime
attribute generator functions synthesized by SILGen.
`#function` magic literal points to the declaration that declaration
attribute is attached to.
2022-12-20 09:45:01 -08:00
swift-ci 328e716489 Merge remote-tracking branch 'origin/main' into rebranch 2022-12-12 07:33:19 -08:00
Nate Chandler 8d8577e5b0 [SIL] Removed Indirect_In_Constant convention.
It is no different from @in.

Continue parse @in_constant in textual and serialized SIL, but just as
an alias for @in.
2022-12-09 21:54:00 -08:00
Erik Eckstein d89c6b2d70 Merge remote-tracking branch 'origin/main' into rebranch 2022-12-01 07:48:51 +01:00
Dario Rexin 3cf40ea504 [IRGen] Re-introduce TypeLayout strings (#62059)
* Introduce TypeLayout Strings

Layout strings encode the structure of a type into a byte string that can be
interpreted by a runtime function to achieve a destroy or copy. Rather than
generating ir for a destroy/assignWithCopy/etc, we instead generate a layout
string which encodes enough information for a called runtime function to
perform the operation for us. Value witness functions tend to be quite large,
so this allows us to replace them with a single call instead. This gives us the
option of making a codesize/runtime cost trade off.

* Added Attribute @_GenerateLayoutBytecode

This marks a type definition that should use generic bytecode based
value witnesses rather than generating the standard suite of
value witness functions. This should reduce the codesize of the binary
for a runtime interpretation of the bytecode cost.

* Statically link in implementation

Summary:
This creates a library to store the runtime functions in to deploy to
runtimes that do not implement bytecode layouts. Right now, that is
everything. Once these are added to the runtime itself, it can be used
to deploy to old runtimes.

* Implement Destroy at Runtime Using LayoutStrings

If GenerateLayoutBytecode is enabled, Create a layout string and use it
to call swift_generic_destroy

* Add Resilient type and Archetype Support for BytecodeLayouts

Add Resilient type and Archetype Support to Bytecode Layouts

* Implement Bytecode assign/init with copy/take

Implements swift_generic_initialize and swift_generic_assign to allow copying
types using bytecode based witnesses.

* Add EnumTag Support

* Add IRGen Bytecode Layouts Test

Added a test to ensure layouts are correct and getting generated

* Implement BytecodeLayouts ObjC retain/release

* Fix for Non static alignments in aligned groups

* Disable MultiEnums

MultiEnums currently have some correctness issues with non fixed multienum
types. Disabling them for now then going to attempt a correct implementation in
a follow up patch

* Fixes after merge

* More fixes

* Possible fix for native unowned

* Use TypeInfoeBasedTypeLayoutEntry for all scalars when ForceStructTypeLayouts is disabled

* Remove @_GenerateBytecodeLayout attribute

* Fix typelayout_based_value_witness.swift

Co-authored-by: Gwen Mittertreiner <gwenm@fb.com>
Co-authored-by: Gwen Mittertreiner <gwen.mittertreiner@gmail.com>
2022-11-29 21:05:22 -08:00
swift-ci 768509a3dd Merge remote-tracking branch 'origin/main' into rebranch 2022-11-29 05:53:52 -08:00
Arnold Schwaighofer b79bef92aa Merge pull request #62279 from aschwaighofer/objc_protocol_emission_fix
IRGen: Use the exact traversal that clang uses to find non-runtime implied protocols
2022-11-29 05:38:05 -08:00
Arnold Schwaighofer b2c05fc582 IRGen: Use the exact traversal that clang uses to find non-runtime implied protocols
And only replace the variable inside of the clang generated protocol-refs list.
This should make this resilient to mismatches in the protocol list order.
2022-11-28 10:50:12 -08:00
swift-ci efef52a86e Merge remote-tracking branch 'origin/main' into rebranch 2022-11-28 09:33:40 -08:00
eeckstein 527d9a85d2 Merge pull request #62217 from eeckstein/fix-warnings
Fix warnings in main and rebranch
2022-11-28 18:32:12 +01:00
swift-ci 2d01a15710 Merge remote-tracking branch 'origin/main' into rebranch 2022-11-28 08:54:15 -08:00
Erik Eckstein f94a4fff7c IRGen: fix a memory use-after-free problem in updateProtocolRefs
Getting the `protocolRefs` constant must not be hoisted out of the loop because this constant might be deleted by `oldVar->replaceAllUsesWith(newOpd)`.

rdar://102554134
2022-11-23 15:54:43 +01:00
Erik Eckstein ab1b343dad use new llvm::Optional API
`getValue` -> `value`
`getValueOr` -> `value_or`
`hasValue` -> `has_value`
`map` -> `transform`

The old API will be deprecated in the rebranch.
To avoid merge conflicts, use the new API already in the main branch.

rdar://102362022
2022-11-21 19:44:24 +01:00