Commit Graph

166 Commits

Author SHA1 Message Date
Doug Gregor
43df05a89c [SE-0470] Prohibit isolated conformances in dynamic casts marked as such
Certain dynamic casts cannot work safely with isolated conformances,
regardless of what executor the code runs on. For such cases, reject
all attempts to conform to the type.
2025-03-26 22:31:52 -07:00
Doug Gregor
296e14662a Rework runtime entrypoints for isolated conformance checking
Replace the pair of global actor type/conformance we are passing around with
a general "conformance execution context" that could grow new functionality
over time. Add three external symbols to the runtime:

* swift_conformsToProtocolWithExecutionContext: a conforms-to-protocol check
  that also captures the execution context that should be checked before
  using the conformance for anything. The only execution context right now
  is for an isolated conformance.
* swift_isInConformanceExecutionContext: checks whether the function is
  being executed in the given execution context, i.e., running on the
  executor for the given global actor.
* swift_ConformanceExecutionContextSize: the size of the conformance
  execution context. Client code outside of the Swift runtime can allocate
  a pointer-aligned region of memory of this size to use with the runtime
  functions above.
2025-03-07 23:52:20 -08:00
Doug Gregor
48aa75d86f [Isolated conformances] Cache resolved global actor for conformances
In the prior implementation of runtime resolution of isolated conformances,
the runtime had to look in both the protocol conformance descriptor and
in all conditional conformance requirements (recursively) to find any
isolated conformances. If it found one, it had to demangle the global
actor type to metadata. Since swift_conformsToProtocol is a hot path through
the runtime, we can't afford this non-constant-time work in the common
case.

Instead, cache the resolved global actor and witness table as part of the
conformance cache, so that we have access to this information every time
we look up a witness table for a conformance. Propagate this up through
various callers (e.g., generic requirement checking) to the point where
we either stash it in the cache or check it at runtime. This gets us down
to a very quick check (basically, NULL-or-not) for nonisolated conformances,
and just one check for isolated conformances.
2025-03-07 23:51:46 -08:00
Doug Gregor
6dd141ad54 Replace dlsym of swift_task_isCurrentGlobalActor with a constructor hook
Following the approach taken with the concurrency-specific type
descriptors, register a hook function for the "is current global actor"
check used for isolated conformances.
2025-03-07 23:51:43 -08:00
Alejandro Alonso
3d8a9d4554 Implement same type checking at runtime 2024-09-04 15:13:51 -07:00
Alejandro Alonso
9903d71f91 More changes to get off of ssize_t 2024-09-04 15:13:49 -07:00
Alejandro Alonso
7c85261a77 Add runtime support 2024-09-04 15:13:27 -07:00
Mike Ash
b86fe88c43 [Runtime] Fix key argument indexing when checking invertible protocols.
Track the key argument index separately from the generic parameter index when performing the invertible protocol checking in _checkGenericRequirements. This keeps the indexing correct when a non-key argument is followed by a key argument.

rdar://128774651
2024-06-11 12:39:23 -04:00
Doug Gregor
bbfdf7b36a Merge pull request #72470 from DougGregor/dynamic-suppressible-protocols
Metadata and runtime support for suppressible protocol requirements
2024-03-27 11:49:00 -07:00
Doug Gregor
b167eece42 Metadata and runtime support for suppressible protocol requirements
Introduce metadata and runtime support for describing conformances to
"suppressible" protocols such as `Copyable`. The metadata changes occur
in several different places:

* Context descriptors gain a flag bit to indicate when the type itself has
  suppressed one or more suppressible protocols (e.g., it is `~Copyable`).
  When the bit is set, the context will have a trailing
  `SuppressibleProtocolSet`, a 16-bit bitfield that records one bit for
  each suppressed protocol. Types with no suppressed conformances will
  leave the bit unset (so the metadata is unchanged), and older runtimes
  don't look at the bit, so they will ignore the extra data.
* Generic context descriptors gain a flag bit to indicate when the type
  has conditional conformances to suppressible protocols. When set,
  there will be trailing metadata containing another
  `SuppressibleProtocolSet` (a subset of the one in the main context
  descriptor) indicating which suppressible protocols have conditional
  conformances, followed by the actual lists of generic requirements
  for each of the conditional conformances. Again, if there are no
  conditional conformances to suppressible protocols, the bit won't be
  set. Old runtimes ignore the bit and any trailing metadata.
* Generic requirements get a new "kind", which provides an ignored
  protocol set (another `SuppressibleProtocolSet`) stating which
  suppressible protocols should *not* be checked for the subject type
  of the generic requirement. For example, this encodes a requirement
  like `T: ~Copyable`. These generic requirements can occur anywhere
  that there is a generic requirement list, e.g., conditional
  conformances and extended existentials. Older runtimes handle unknown
  generic requirement kinds by stating that the requirement isn't
  satisfied.

Extend the runtime to perform checking of the suppressible
conformances on generic arguments as part of checking generic
requirements. This checking follows the defaults of the language, which
is that every generic argument must conform to each of the suppressible
protocols unless there is an explicit generic requirement that states
which suppressible protocols to ignore. Thus, a generic parameter list
`<T, Y where T: ~Escapable>` will check that `T` is `Copyable` but
not that it is `Escapable`, and check that `U` is both `Copyable` and
`Escapable`. To implement this, we collect the ignored protocol sets
from these suppressed requirements while processing the generic
requirements, then check all of the generic arguments against any
conformances not suppressed.

Answering the actual question "does `X` conform to `Copyable`?" (for
any suppressible protocol) looks at the context descriptor metadata to
answer the question, e.g.,

1. If there is no "suppressed protocol set", then the type conforms.
This covers types that haven't suppressed any conformances, including
all types that predate noncopyable generics.
2. If the suppressed protocol set doesn't contain `Copyable`, then the
type conforms.
3. If the type is generic and has a conditional conformance to
`Copyable`, evaluate the generic requirements for that conditional
conformance to answer whether it conforms.

The procedure above handles the bits of a `SuppressibleProtocolSet`
opaquely, with no mapping down to specific protocols. Therefore, the
same implementation will work even with future suppressible protocols,
including back deployment.

The end result of this is that we can dynamically evaluate conditional
conformances to protocols that depend on conformances to suppressible
protocols.

Implements rdar://123466649.
2024-03-21 14:57:47 -07:00
Mike Ash
0491192337 [Runtime] Remove ExternalGenericMetadataBuilder. 2024-03-21 17:56:17 -04: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
Mike Ash
b8b59c4bac [ExternalGenericMetadataBuilder] Add a test that validates built metadata against the runtime.
We run the builder, then use a small program that converts the JSON output into C code that generates the data. Compile that into a bundle, then load it as the prespecializations library. Then scan all the entries in the table and compare them with what the runtime builds dynamically.
2024-01-31 17:03:27 -05:00
Mike Ash
edb292dda5 [Runtime] Do a proper hash table lookup in the prespecializations library.
We were doing a linear scan of the table contents as a stopgap. Stop doing that, and compute the proper key for the lookup, matching the one used in the builder.
2024-01-26 12:04:02 -05:00
Mike Ash
4341102c92 [Tools] Add a library to build specialized generic metadata out of process.
This library uses GenericMetadataBuilder with a ReaderWriter that can read data and resolve pointers from MachO files, and emit a JSON representation of a dylib containing the built metadata.

We use LLVM's binary file readers to parse the MachO files and resolve fixups so we can follow pointers. This code is somewhat MachO specific, but could be generalized to other formats that LLVM supports.

rdar://116592577
2024-01-24 20:45:50 -05:00
Mike Ash
29c350e813 [Runtime] Create an external generic metadata builder.
Create a version of the metadata specialization code which is abstracted so that it can work in different contexts, such as building specialized metadata from dylibs on disk rather than from inside a running process.

The GenericMetadataBuilder class is templatized on a ReaderWriter. The ReaderWriter abstracts out everything that's different between in-process and external construction of this data. Instead of reading and writing pointers directly, the builder calls the ReaderWriter to resolve and write pointers. The ReaderWriter also handles symbol lookups and looking up other Swift types by name.

This is accompanied by a simple implementation of the ReaderWriter which works in-process. The abstracted calls to resolve and write pointers are implemented using standard pointer dereferencing.

A new SWIFT_DEBUG_VALIDATE_EXTERNAL_GENERIC_METADATA_BUILDER environment variable uses the in-process ReaderWriter to validate the builder by running it in parallel with the existing metadata builder code in the runtime. When enabled, the GenericMetadataBuilder is used to build a second copy of metadata built by the runtime, and the two are compared to ensure that they match. When this environment variable is not set, the new builder code is inactive.

The builder is incomplete, and this initial version only works on structs. Any unsupported type produces an error, and skips the validation.

rdar://116592420
2024-01-11 09:15:02 -05:00
Alejandro Alonso
a0c8465f0c Refactor _gatherWrittenGenericParameters
Fix some bugs
2023-11-06 10:31:20 -08:00
Alejandro Alonso
de8233a5d6 Revert "Merge pull request #68844 from Azoy/gather-no-parameters"
This reverts commit ccaf427fc3, reversing
changes made to bf45c55530.
2023-10-10 19:36:20 -07:00
Alejandro Alonso
3ddec4fd83 Wrap _checkGenericRequirements instead for _instantiateCheckedGenericMetadata 2023-10-09 15:02:29 -07:00
Kuba Mracek
aab7eab240 Be consistent about guarding SWIFT_HAS_OPAQUE_ISAS with SWIFT_OBJC_INTEROP 2023-07-13 09:03:19 -07:00
Slava Pestov
3052e36f7e Runtime: Fix dynamic casts of variadic types that conditionally conform 2023-06-21 13:42:57 -04:00
Slava Pestov
d776f71b4f Runtime: Teach checkGenericRequirements() to check same-shape and conformance pack requirements 2023-03-09 09:42:00 -05:00
Slava Pestov
17086962c3 Runtime: Add swift_getTypePackByMangledName() entry point
For now this has SWIFT_RUNTIME_LIBRARY_VISIBILITY, but in the
future we might want to make it public so that IRGen can use it
to build packs out of concrete types.
2023-03-09 01:54:51 -05:00
Slava Pestov
cdd1c6da57 Runtime: Move MetadataOrPack to Private.h 2023-03-09 01:54:51 -05:00
Slava Pestov
bcf6f26579 Runtime: Make SubstGenericParametersFromWrittenArgs and _gatherWrittenGenericArgs() completely private to MetadataLoookup.cpp 2023-03-09 01:54:51 -05:00
Slava Pestov
b3cb845ea3 Runtime: support metadata packs in _buildDemanglingForNominalType()
This adds a bunch of new code but once I finish refactoring the other
demangling stuff, I should be able to remove

- gatherWrittenGenericArgs()
- _gatherGenericParameters()
- SubstGenericParametersFromWrittenArgs
2023-03-03 14:16:53 -05:00
Arnold Schwaighofer
0f9bfac94b Remove undefined behavior in RelativeWitnessTable::getDescription() 2023-02-02 07:02:21 -08:00
Egor Zhdan
84a1ffcb33 [Shims] Include SwiftShims headers without ../
This replaces a number of `#include`-s like this:
```
#include "../../../stdlib/public/SwiftShims/Visibility.h"
```
with this:
```
#include "swift/shims/Visibility.h"
```

This is needed to allow SwiftCompilerSources to use C++ headers which include SwiftShims headers. Currently trying to do that results in errors:
```
swift/swift/include/swift/Demangling/../../../stdlib/public/SwiftShims/module.modulemap:1:8: error: redefinition of module 'SwiftShims'
module SwiftShims {
       ^
Builds.noindex/swift/swift/bootstrapping0/lib/swift/shims/module.modulemap:1:8: note: previously defined here
module SwiftShims {
       ^
```
This happens because the headers in both the source dir and the build dir refer to SwiftShims headers by relative path, and both the source root and the build root contain SwiftShims headers (which are equivalent, but since they are located in different dirs, Clang treats them as different modules).
2022-09-14 11:14:50 +01:00
Robert Widmann
14edd57e3e Generalize Metadata Lookup for Shapes 2022-06-15 18:19:33 -06:00
Jonathan Grynspan
9644c7390f 58711 - swift_slowAlloc() and friends should be marked SWIFT_NODISCARD 2022-05-06 11:05:12 -04:00
Jonathan Grynspan
770fd107de 58686: swift_slowAlloc() _et al._ should be marked returns-nonnull to improve codegen 2022-05-05 23:18:48 -04:00
Pavel Yaskevich
e801e4e2b7 [Distributed] Runtime: Add a way to fetch witness tables for given generic env/arguments 2022-01-24 10:18:00 -08:00
Adrian Prantl
fede775269 Make Objective-C interoperability configurable in the runtime
In order to be able to debug, for example, a Linux process from a macOS host, we
need to be able to initialize a ReflectionContext without Objective-C
interoperability. This patch turns ObjCInterOp into another template trait, so
it's possible to instantiate a non-ObjC MetadataReader on a system built with
ObjC-interop (but not vice versa).

This patch changes the class hierarchy to

                          TargetMetadata<Runtime>
                                    |
                          TargetHeapMetadata<Runtime>
                                    |
                          TargetAnyClassMetadata<Runtime>
                                   /                \
                                  /               TargetAnyClassMetadataObjCInterop<Runtime>
                                 /                              \
TargetClassMetadata<Runtime, TargetAnyClassMetadata<Runtime>>    \
                                                                  \
                    TargetClassMetadata<Runtime, TargetAnyClassMetadataObjCInterop<Runtime>>

TargetAnyClassMetadataObjCInterop inherits from TargetAnyClassMetadata because
most of the implementation is the same. This choice makes TargetClassMetadata a
bit tricky. In this patch I went with templating the parent class.

rdar://87179578
2022-01-20 18:28:18 -08:00
Kuba Mracek
080d513c30 Only #include <TargetConditionals.h> when it's present 2021-11-26 18:53:34 -08:00
Alastair Houghton
cd99995d84 [Tests] Re-add round-trip type test.
This was reverted in 12fa024 because it broke the iOS simulator build.

rdar://37170485
2021-08-17 09:51:22 +01:00
Mishal Shah
f45195454f Revert "[Tests] Add a test to round-trip types through mangled names." 2021-08-16 14:03:39 -07:00
Alastair Houghton
8e12cd0b62 [Tests] Add a test to round-trip types through mangled names.
Added a new test to the test suite that round trips Swift types through
mangled names and checks that we get the same type back that we started
with.

rdar://37170485
2021-08-16 11:22:21 +01:00
Kuba (Brecka) Mracek
6b40a092b9 Move the actual Obj-C parts of ReflectionMirror.mm into a separate file, make ReflectionMirror.mm a .cpp file (#34025) 2020-09-25 07:29:03 -07:00
Mike Ash
fd6922f92d Add error reporting when looking up types by demangled name. 2020-08-28 14:43:51 -04:00
Kuba (Brecka) Mracek
4cfaeee6df Match the #ifdefs between _swift_isNonPointerIsaObjCClass and objectUsesNativeSwiftReferenceCounting (#33510) 2020-08-17 17:34:11 -07:00
Mike Ash
e57961c95f [Runtime] Fix the ISA mask assert for ARM64 running on ARM64e hardware. 2020-08-07 14:18:16 -04:00
Mike Ash
17833beb7b [Runtime] Fix SWIFT_ISA_MASK for ARM64 simulators.
rdar://problem/65059017
2020-07-06 15:20:20 -04:00
Mishal Shah
194d5d06f1 [Apple Silicon] Use a correct isa mask on Apple Silicon without signed isas 2020-07-02 19:20:40 -07:00
Saleem Abdulrasool
e72b43f374 runtime: namespace SmallVectorImpl for inline namespace
This adjusts the use of `SmallVectorImpl` to allow the runtime to use
inline namespaces for its local copy of LLVMSupport.
2020-05-13 11:10:47 -07:00
Saleem Abdulrasool
96313ce3e1 runtime: explicitly namespace ArrayRef in shared headers
There are a set of headers shared between the Swift compiler and the
runtime.  Ensure that we explicitly use `llvm::ArrayRef` rather than
`ArrayRef` which is aliased to `::llvm::ArrayRef`.  Doing so enables us
to replace the `ArrayRef` with an inline namespaced version fixing ODR
violations when the swift runtime is loaded into an address space with
LLVM.
2020-05-13 08:42:06 -07:00
Saleem Abdulrasool
04eeff5b8d runtime: remove llvm/Support header usage
This reduces the dependency on `LLVMSupport`.  This is the first step
towards helping move towards a local fork of the LLVM ADT to ensure that
static linking of the Swift runtime and core library does not result in
ODR violations.
2020-05-07 13:36:13 -07:00
Saleem Abdulrasool
9731704cc7 runtime: replace LLVM_LIBRARY_VISIBILITY with SWIFT_LIBRARY_VISIBILITY (NFC)
This replaces `LLVM_LIBRARY_VISIBILITY` with `SWIFT_LIBRARY_VISIBILTIY`
througout the runtime.  The purpose of this attribution is unclear -
building with `-fvisibility=hidden` would accomplish this.  This is an
entirely mechanical change replacing the macro with the Swift namespaced
variant instead.
2020-05-06 08:30:17 -07:00
Ben Cohen
60b4f38660 Eliminate context descriptor cache (#29151) 2020-01-13 15:59:32 -08:00
tbkka
fdb1926421 [SR-5289] Teach Mirror how to handle unowned/unmanaged references (#28823)
SR-5289: Teach Mirror how to inspect weak, unowned, and unmanaged refs

Correctly reflect weak, unowned, and unmanaged references
to both Swift and Obj-C types (including existential references to
such types) that occur in both Swift class objects and in Swift
structs.

This includes the specific reported case (unowned reference to an
Obj-C object) and several related ones.

Related changes in this PR:

* Tweak internal bitmap used for tracking ownership modifiers
  to reject unsupported combinations.

* Move FieldType into ReflectionMirror.mm
  FieldType is really just an internal implementation detail
	of this one source file, so it does not belong in an ABI header.

* Use TypeReferenceOwnership directly to track field ownership
  This avoids bitwise copying of properties and localizes some
	of the knowledge about reference ownership

* Generate a top-level "copyFieldContents" from ReferenceStorage.def
  Adding new ownership types to ReferenceStorage.def will now
	automatically produce calls to `copy*FieldContents` - failure
	to provide a suitable implementation will fail the build.

* Add `deallocateBoxForExistentialIn` to match `allocateBoxForExistentialIn`

Caveat:  The unit tests are not as strict as I'd like.  Attempting to make them
so ran afoul of otherwise-unrelated bugs in dynamic casting.
2019-12-17 09:42:52 -08:00
Mishal Shah
ca693eeca3 Revert "SR-5289: Teach Mirror how to handle unowned/unmanaged references (#28368)"
This reverts commit 9c638ae60d.
2019-12-16 17:24:30 -08:00