Better Non-Resilient Swift Modules for Build System Integration

Hi all. I’ve been working on abstract type layouts for some time, and have been discussing with @Xi_Ge natural extensions that I’d like to see. I’d like to solicit some feedback on my design and general roadmap.

For me, the overarching goal here is to improve Swift’s incremental build speed characteristics for non resilient libraries by reducing the amount of unnecessary information that is exposed to dependent compiler invocations.

Concretely, consider if you have modules A, B and C, where A depends on B and B depends on C. Compiling each module produces some output files, and those files are inputs to dependent modules. If those inputs do not change, general purpose build systems can avoid recompiling dependent modules. Build systems like Buck and Bazel do this by comparing input files by hash to previous compile actions, caching repeated actions, but they don’t know anything about the Swift language otherwise.

Currently the Swift compiler includes many internal implementation details in these output files that cause dependent modules to re-compile, even when they don’t actually need to. My work here is all about how we can reduce the amount of internal implementation information that we leak.

Proposed Roadmap:

I want to reduce the two forms of implementation detail leaking. The first a module leaks information about internally imported modules, the second a module leaks internal information about itself. I’ve already been working on the first, the second I would like to propose:

  1. Formalization of internal imports for non-resilient modules, such that @_implementationOnly can be retired

  2. Remove module private declarations from generated binary Swift modules by default, representing private declarations that still contribute to module ABI with abstract type layouts.

I’ll give some detail on the design of both goals.

1: Formalizing internal imports for non-resilient modules

This is what I’ve been working on for a while now, but I want to re-iterate the exact goals and latest implementation strategy.

Without library evolution, if module A imports module B, and module B internal imports C, to compile A you need both B and C. This means changes to C invalidate A despite being an “internal” import. That is not true of @_implementationOnly imports, an @_implementationOnly imported module need not be provided to client module compiles, even without library evolution. I want to give internal imports this quality, and then delete @_implementationOnly from the language.

The reason access level modifiers on import statements only allow you to not provide internally imported modules to clients with library evolution, is that although declarations from internally imported modules are not allowed to contribute to public module API, they are allowed to contribute to module ABI. @_implementationOnly currently has no solution for this issue, and miscompiles are possible. Consider the canonical example:

@_implementationOnly import HiddenModule

public struct Foo {
    private let privateStoredProperty: HiddenModule.HiddenStruct
}

Without visibility into HiddenModule, clients cannot derive the layout of Foo. Instead de-serialization currently drops members including stored properties if it cannot resolve their types, leading to an incorrect layout.

Doug has laid out a proposal to fix this problem, and I have begun implementing it more or less. The core idea is that we communicate the layout information that clients are currently missing via “abstract type layout information”.

The latest iteration of my design is as follows:

  1. We provide abstract type layouts only for the types of ABI contributing type members (ex. a stored property in an exposed struct) that clients may not be able to resolve, because the type references a hidden type somewhere.

    This mirrors the existing recovery mechanisms where we use a MissingMemberDecl as a placeholder when class / protocol members fail to de-serialize to keep layout consistent. This way we don’t bloat modules with abstract type layouts of every transitively used type in the module, and don’t leak the layout of types that don’t actually contribute to module ABI.

  2. For each type identified as being in need of an abstract type layout, we largely mechanically serialize the existing lowered representations the compiler uses to guide codegen.

We serialize the approximate TypeLowering (guides SILGen) and the exact TypeInfo (guides IRGen) as well as some other properties. When layout derived from the visible representation of a type and layout derived from abstract type layout differ somehow, it is easy to create miscompilations. I’ve found it very difficult to come up with another format that faithfully captures all the subtleties of layout (ex: extra inhabitants surprised me). Therefore, I think keeping a single representation of layout as much as possible is helpful.

  1. As in the proposal, we insist that the native layout of a type, and the layout as derived from an abstract type layout match exactly.

We tolerate some types having more opaque abstract type layout representations, in that non trivial copy / destroy operations are performed via value witness or similar, but the layout itself, the details that might affect the calling convention of a function manipulating the type, must match exactly. This has implications in the next couple sections.

Acceptable Performance Penalty:

With internal becoming the default access level for imports for future Swift versions, we need to be careful that we don’t silently introduce too significant performance penalties as a result of using an abstract type layout to perform codegen.

So I want to highlight the ways in which abstract type layouts currently produce “worse” codegen. There are two areas I am aware of.

Firstly, there is the extra layer of indirection for performing non trivial value operations. That layer of indirection might not need to be quite as indirect as a value witness call (fetch metadata, fetch vw table, call function), but there will always be at least an extra function call.

Lastly, currently we don’t produce aggregate TypeLowerings from abstract type layouts, but what I consider to be a compatible non aggregate TypeLowering. That is, at the SIL level, hidden types are opaque, and a copy of such a type, can’t be lowered to individual copy SIL instructions on its members. That is not true of IRGen, where we faithfully re-create the TypeInfo. This will disable certain SIL optimizations, like ARC optimizations. This isn’t necessarily a fundamental limitation, but it is how I’ve currently implemented it, so I want to call out this distinction.

If we are to succeed in completing this project, I think we need to align on what an accepted performance penalty looks like.

Remaining Challenges:

A consequence of design point number 3 (insisting that abstract type layouts not regress layout precision), requires that our system be capable of specializing generic abstract type layouts. Consider this example:

@_implementationOnly import HiddenModule

public struct GenericVisibleStruct<T> {
   private let privatStoredProperty: HiddenModule.HiddenGenericStruct<T>
}

public func takeAGenericVisibleStructOfInt(\_ foo: GenericVisibleStruct<Int>) {}

The calling convention of takeAGenericVisibleStructOfInt will be decided with full visibility into HiddenGenericStruct<Int> and to call the function, clients must be able to reproduce the layout of HiddenGenericStruct<Int>, given only the abstract type layout of HiddenGenericStruct<T> and the layout of Int. In other words, the client needs to be able to perform generic specialization on abstract type layouts.

This is a challenge I haven’t yet tackled with the current iteration of abstract type layouts. I expect it to be achievable, but it’s a wrinkle not covered in prior discussion that I want to raise.

2: Remove module private declarations from generated binary Swift modules

We currently include all declarations in a module’s binary interface, including private declarations that clients compiling against the module should not care about. This means adding a private function to a module for example, causes client modules to re-compile, when they really shouldn’t.

For the binary module emitted in the typical case, I want to omit all these private declarations, using abstract type layouts when a private member contributes to ABI. This would extend experimental-serialize-external-decls-only: Frontend: Introduce `-experimental-serialize-external-decls-only` option by tshortli · Pull Request #68166 · swiftlang/swift · GitHub to support non resilient modules.

However, it has become clear to me from previous discussions (1) (2), that there are some consumers of binary Swift modules that require private information. In particular, @testable imports and LLDB. To handle the testable case I suggest we produce a full module when -enable-testing is passed. To handle the LLDB case, I suggest that when modules are emitted, we emit two versions, a “stripped version” for use when compiling dependent modules, and another full version for LLDB. The stripped version may point at the full version via an embedded path. This way LLDB can still find the complete version from the stripped version.

Over the long term we can replace the second full module, with debug information as described here, but we don’t block improvements in the interface the compiler uses. I think this is the better long term direction, just as we don’t include DWARF in C++ headers / clang modules, we shouldn’t need to include information needed only by the debugger in Swift module interfaces meant for the compiler.

Diagnostic Implications:

As I discussed in this forum post, removing private declarations from binary swift modules may have implications on diagnostics. The compiler can no longer differentiate between a declaration that does not exist, and one that is private. I think this is an acceptable cost to pay, and diagnostic parity is not a goal of mine, but as I discuss in the forum thread, we have options to preserve it if we see fit.

Related Note on Textual Swift Module Interfaces:

There is often discussion that if we want interfaces that leak fewer implementation details, we should use textual swift interfaces (.swiftinterface) files. We’ve attempted this, and while they are closer to what we want, textual interfaces really aren’t supported without library evolution.

private struct PrivateStorage {
  var value: Int
}

public struct PublicContainer {
  private var storage: PrivateStorage
}

If you produce a textual interface for this module without library evolution, you get a warning warning: module interfaces are only supported with -enable-library-evolution. Interface emission succeeds, but it produces a broken interface that clients will fail to load:

public struct PublicContainer {
  private var storage: ModuleName.PrivateStorage // PrivateStorage can't be resolved
}

Regardless of if we use textual interfaces, or binary modules, we need abstract type layouts if we are to support minimal interfaces for non resilient libraries. At that point, we can debate the merits of the two formats, but I would say the binary format is more performant, and the textual format is really only appropriate when it must be compatible with multiple compiler versions.

Related Note on Resilient v Non-Resilient Parity:

It is considered desirable to maintain feature parity between resilient and non resilient modules. Such parity is the basis for this whole project, and it will fix existing parity gaps. In particular, as mentioned it brings the same behavior for internal imports to non resilient modules already enjoyed by resilient modules. If desired, it could also allow emitting textual interfaces for non resilient modules.

9 Likes

This bit worries me, because Bazel at least toggles -enable-testing based on compilation mode: off for optimized builds, on for non-optimized, with the idea being that most of the time tests are being run against non-opt builds (and if you want to run them specifically against opt builds, enable the flag manually).

But changing the serialized module so drastically for -enable-testing would mean that dependency pruning couldn't be done at all on Bazel's non-opt builds, which means they wouldn't be able to benefit from any of the build performance improvements this would provide. That's unfortunate, because the majority of builds are non-opt builds.

There's been discussion in the past on the forums about how @testable is basically a hack, and I personally would love if we could just deprecate it once and for all (package is better for this now). So tying this new behavior to that flag feels like a risky idea.

2 Likes

I can see how that might be convenient, but that just seems like misconfiguration to me. In Buck any module imported from a test target is built with -enable-testing, and otherwise it is not. It isn't related to optimization mode.

But changing the serialized module so drastically for -enable-testing would mean that dependency pruning couldn't be done at all on Bazel's non-opt builds

Maybe you can explain a bit more about how dependency pruning works in Bazel, I'm not familiar. Passing -enable-testing already changes the serialized module. Are you implying the degree to which it changes might make it more or less amenable to Bazel?

There's been discussion in the past on the forums about how @testable is basically a hack, and I personally would love if we could just deprecate it once and for all (package is better for this now). So tying this new behavior to that flag feels like a risky idea.

I haven't read the threads you're referring to, maybe you can point me to them, or elaborate about your package ideas. In any case, I'm not sure the mechanism by which you trigger exposure of internal implementation details to tests really matters for this discussion. At the end of the day, we have some clients that care about implementation details and need to be exposed to them, and other that do not and don't want to be rebuilt when they change. So we inherently need two module emission modes if we are to get these benefits.

Well, it's directly derived from Xcode's behavior, which sets ENABLE_TESTABILITY in Debug configurations but not Release.

Bazel tries to avoid as much as possible pushing configuration "down" the graph from, say, a test target to a library target. That leads to configuration explosions, reduces cache hits, etc.—if you have a library Foo depended on by an application target FooApp and a test target FooTests, Bazel's model means there's only a single compiled Foo so both the app and tests can share the same artifact, leading to better cache throughput. We do support pushing down config in very limited circumstances (e.g., to push the Apple platform and minimum deployment version of an app to its library dependencies). It's not a misconfiguration, just a different fundamental design decision about the action graph than Buck made.

Today, if you have Swift library A that depends on B that depends on C through their deps attributes, we propagate the transitive closure of .swiftmodule files when compiling A—it gets both B.swiftmodule and C.swiftmodule. Now let's say B private-imports C; when we compile A, we should be able to only pass B.swiftmodule and leave C.swiftmodule out. By pruning C.swiftmodule, we avoid rerunning A's compile action if C changes but B doesn't. The catch is, another key restriction in Bazel is that that action graph is built without looking at any of the source files, so we can't just scan them to see what kind of import was used. Instead, we ask library authors to explicitly list public deps in deps and internal/private deps in implementation_deps. Then when we build the actions, we only propagate the deps modules and leave out the implementation_deps modules.

Tying this to -enable-testing, which is tied to optimization mode, means that we have to unconditionally keep all implementation_deps because they might be testably-imported, which means debug builds can never get any benefit from pruning.

They're not my ideas so much as the fact that @testable import existed so that test targets could reach into internal details of libraries under test (IMO, already a poor library design) but now package level access serves that even better since tests and libraries under test live in the same package in the SwiftPM world. Using package visibility for things you want to expose in tests means that you don't have to compile the library in two different modes depending on whether you're a test or an app client.

2 Likes

Just for my curiosity, is the re-compilation here a problem that occurs with Swift/Xcode's tooling, or only with Buck/Bazel style input hashing?

All of what you describe sounds similar to how Buck works, including that we suffer from configuration explosion from pushing configuration down the graph.

Tying this to -enable-testing, which is tied to optimization mode, means that we have to unconditionally keep all implementation_deps because they might be testably-imported, which means debug builds can never get any benefit from pruning.

Yes, but isn't that the cost of the trade off you've made by not pushing the "is this a test" configuration down the graph? I don't see a way around this, not pushing "is this a test" down the graph and not unnecessarily recompiling on internal implementation changes, seem at odds with one another. For example, it sounds like your deps are probably already over-specified as they must include any module that a client, including a test, might need. That would include internally imported modules that are used in the signatures of internal methods right?

Using package visibility for things you want to expose in tests means that you don't have to compile the library in two different modes depending on whether you're a test or an app client.

In this system, if you are going to benefit from this change, you would need to push down "is the consumer in the same package or not", and suffer from configuration explosion in that way right? That explosion would probably be worse in that instead of pushing down a binary "testing enabled state", you'd be pushing down the identity of the consuming module.

Hopefully I've made myself clear, but it seems to me the usefulness of this feature is fundamentally tied to pushing "I want to see internal implementation details" down the graph, and its up to you to decide if that is a worth while trade off.

@Xi_Ge can speak to more details I'm not sure exactly. From our conversations, I recall him mentioning that Xcode might implement some kind of more language specific "does this kind of change in inputs warrant re-compiling" check, instead of just hashing. That process could be something like stripping implementation details from the inputs, and checking if what is left changed from last time. From my perspective, that logic should be in the toolchain, and the toolchain should only publish what clients care about in the first place. In addition to being more general, hashing inputs is also likely to be much faster than some kind of bespoke "did something we care about change" check.

1 Like

HI Nuri, first of all, thank you for sharing the roadmap! I think what I was talking about is ModuleDecl::getFingerprint(). It's a hash the compiler writes into the .swiftmodule, along with per-declaration fingerprints, so swift-driver can decide whether a change in an upstream module should cause some source files in the current module to recompile.

1 Like

This is a bit of a contradiction in my mind. A non-resilient module is by definition not ABI stable. Part of the reason it is not ABI stable is that its clients take advantage of the layout information the module exposes. One of the reasons that layout is unstable is that the compiler is allowed to change the layout of anything that isn't at a library evolution boundary. Non-resilient modules and their clients must always be rebuilt together if the compiler version changes because of this risk, regardless of whether the other compiler can parse the module format.

I suppose maybe you could maybe detect that layout changed, but I'm not sure what the concrete use case is for consuming non-resilient modules built by different versions of the compiler.

Thank you for laying out the project plan with this level of detail!

The potential for surprising performance penalties do seem to me like one of the biggest challenges to the success of this project. It also implies to me that, at least to begin with, this mode is going to have to be opt-in per-module and not the default. It's unclear to me what process we would follow to gain the confidence necessary to decide to make this the default (or only) mode for all Swift compilations in the future.

I think we should spend some time thinking through how we expect developers to identify and address these costs if they are meaningful for their projects. For example, if a developer finds through profiling that hiding a certain dependency with internal import creates unacceptable indirection overhead for some performance-critical code, what do they do? Maybe they would do the same thing the author of an ABI stable module would do, which is make the layout of the type with that hidden member @frozen, and then force themselves to expose the dependency as a public import instead. Is there any way we can reason about the overhead without just enabling the feature and profiling individual executables to see how they are affected? (Probably not, but it would be interesting to see if there's a way to surface the costs somehow).

2 Likes

What about this idea: when -enable-testing is present, the default behavior could be as you described to generate the module that has the internal declarations serialized. But for build systems like Bazel that still want to be able to prune deps in the presence of that flag, we could also offer a flag like -emit-testable-swiftmodule-path <path>. If that's present, then the default .swiftmodule would be the one that only contains the public API/ABI surface (same as if -enable-testing wasn't present), and the one with the internals would be written to that other path.

That structure has some nice benefits: the presence of both -enable-testing and -emit-testable-swiftmodule-path doesn't change the nature of the standard .swiftmodule compared to when testing isn't enabled. Bazel's rules could be updated to propagate both .swiftmodule files up the graph—like Buck, I presume, they only matter for caching if a downstream action uses them as inputs. An application build would only use the public .swiftmodule files and would be able to prune dependencies as expected; a test would import the testing .swiftmodule files instead, and would be able to @testable import the ones it wants.

We might still need to be explicit about this on the build target side and ask that users who use @testable separate their deps from their testable_deps, so that we know which module to pick for any particular dependency. But this seems like it's feasible and would be the best of both worlds.

1 Like

I'm not sure what exactly you think is a contradiction, but I think we agree. What I mean to say with that section is that using textual interfaces doesn't somehow make the problem of hiding implementation details of non-resilient modules easier, or absolve us of the need for abstract type layouts.

I'm not sure what the concrete use case is for consuming non-resilient modules built by different versions of the compiler.

I agree.

1 Like

For standard compilation, probably no strong reason. But standalone tooling that wants to use typechecked information basically has to "be the frontend" in order to load modules, and it would be great to be able to write tools that compile and link against a single close-to-tip-of-tree version of the toolchain sources but could still load older modules. Because right now, if you have a build farm supporting multiple simultaneous versions of the toolchain at once, any semantic tooling you want to write has to be build multiple times to match each version of the toolchain that you have.

Is that a compelling enough reason to support this in general? Probably not, I don't think I could successfully make that argument. A better approach would be to stabilize an external interface to Sema and support compiler plugins instead.

Got it. When I first read this section, it seemed to me like it was laying out the reasons that we could not use textual formats for this purpose yet, rather than making an argument against using them at all.

I also don't know how we can reason about the overhead without profiling, but you raise a good point about needing:

  1. A plan for incremental adoption
  2. Potentially methods to point out sources of regression
  3. Tools to address that regression if necessary

In my plan, I talk about the two sources of implementation detail leakage from a module Foo. One is leaking information another module FooInternalDep which Foo internally imports, two is leaking internal information about Foo itself. We fix this by reducing the leakage to abstract type layout information from both sources, and both come with performance penalties, but the performance penalty reduction options are a bit different for the two.

@Douglas_Gregor introduces the notion of "hidden type recovery", which is when if a particular client of Foo, just so happens to import FooInternalDep, even though it is not strictly required, they should benefit from the native representation of FooInternalDep's types. I've so far made sure I always support hidden type recovery in my abstract type layouts. That gives developers more options, if all clients of Foo can't tolerate overhead then FooInternalDep should be made a public import. However, if only a subset care about performance, they can each import FooInternalDep themselves individually.

Clawing back the performance penalty imposed by abstract type layouts to describe types within Foo is more complicated. To address that problem, I would suggest users just disable the feature for Foo. We could explore an analogous option to the above resolution, where select clients of Foo can request the full native interface, but that seems complicated. There are also other options we can explore down the line for more granular control like an attribute akin to @inlinable, @frozen etc, but I also think that's too complicated for an initial design.

In terms of how users will detect these implicit regressions, I would propose an opt in warning. The warning will identify when a type is being represented by abstract type layout, and perhaps that abstract type layout has the potential to be particularly in-efficient (ie. add more layers of indirection). This could be used by particularly performance conscious developers, a sort of "strict mode".

Incremental Adoption, a need for both modules views, and reconciling the two:

The need for incremental adoption also ties into @allevato's comments about -enable-testing. It is clear that within a given build, some clients of Foo maybe be interested in Foo's full interface, FooInternalDep or both. That client might be:

  1. A test that @testable imports Foo
  2. LLDB that needs to be able to evaluate expressions on any of Foo's internal declarations
  3. A performance conscious client of Foo that wants to avoid overhead

I'd like to propose that in order to opt into this feature, you pass -emit-minimal-module-path <path>, to produce Foo.minimal.swiftmodule, while the full module will be emitted as usual to Foo.swiftmodule. Foo.minimal.swiftmodule will contain a bit flag that indicates it is minimal, and an embedded path to Foo.swiftmodule. Foo.swiftmodule will be provided to LLDB, @testable clients and performance conscious clients.

As @Adrian_Prantl describes in Module Tracking in Swift Debug Info | Swift.org, Foo.o will point to whatever module we specify with -debug-module-path. I propose that is Foo.swiftmodule (as it is today in Xcode I expect). When built with explicit modules, Foo.swiftmodule (already today) embeds paths to the modules it is built against, so that LLDB can load them.

Let's consider the case of a client module of Foo, FooClient. FooClient.o will point to FooClient.swiftmodule, which will in turn point to Foo.minimal.swiftmodule (the module it was built against). LLDB should then notice Foo.minimal.swiftmodule is minimal, and instead load Foo.swiftmodule. We do this because LLDB may at some point need to load Foo.swiftmodule to debug Foo.o, and we don't want to have already loaded Foo.minimal.swiftmodule, and then have to reconcile the two representations in memory. This difference in loading behavior (insisting on loading the full version), should be enabled in LLDB and the REPL (I think they are same). As for implicit module builds, they can always construct the full module anyways, and should be deprecated in my opinion.

In my mind, this system allows for incremental, partial adoption and requires no upfront changes in build systems (Xcode, Bazel, Buck) to maintain the status quo.

Something like that sounds good to me! As I've just talked about above, at least for builds that want to support debugging, we already have a need to produce multiple versions of the module, including a full version. I think this should naturally support your use case, when -enable-testing is passed, it won't change Foo.minimal.swiftmodule. You then pass Foo.minimal.swiftmodule to regular consumers, and Foo.swiftmodule to test consumers.

Let me know what you all think.

Does it have to be a separate warning group? or can we just put these warnings under PerformanceHints warning group?

Sure adding it to this warning group seems appropriate to me.

That sounds good to me! Whichever way we slice it (whether full is the default and minimal is optional, or vice versa), as long as we can get both, that lets us pick the right one for each use case and optimize both build graphs.

1 Like