# Question: re-adding \`DerivedFileUnit\`

**URL:** <https://forums.swift.org/t/question-re-adding-derivedfileunit/26427>\
**Category:** Compiler\
**Tags:** question\
**Created:** [June 28, 2019, 8:37pm UTC](https://forums.swift.org/t/question-re-adding-derivedfileunit/26427 "2019-06-28T20:37:30Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![dan-zheng](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dan-zheng/32/2534_2.png) [@dan-zheng](https://forums.swift.org/u/dan-zheng)\
**Post date:** [June 28, 2019, 8:37pm UTC](https://forums.swift.org/t/question-re-adding-derivedfileunit/26427/1 "2019-06-28T20:37:30Z")

</div>

Hello compiler experts,

A long time ago, there existed a `DerivedFileUnit` class for storing synthesized module-level declarations. However, it was removed in [this commit](https://github.com/apple/swift/commit/211c58015878614f4cdebfd859fc3d1ba54f2fbd) by @Douglas_Gregor in 2016:

```swift
[Cleanup] Eliminate DerivedFileUnit.

The only client of DerivedFileUnit was synthesized global '=='
operators for Equatable conformances, which has since been removed.

```

Now, [differentiation in Swift](https://forums.swift.org/t/pre-pitch-swift-differentiable-programming-design-overview/25992) is in need of something like `DerivedFileUnit`: the differentiation SIL transform synthesizes auxiliary struct/enum data structures and needs to add them somewhere.

So far, we've been using a hack to find an appropriate `SourceFile` for adding these structs/enums:

```cpp
// In lib/SILOptimizer/Mandatory/Differentiation.cpp:

  /// Retrieves the file unit that contains implicit declarations in the
  /// current Swift module. If it does not exist, create one.
  ///
  // FIXME: Currently it defaults to the file containing `origFn`, if it can be
  // determined. Otherwise, it defaults to any file unit in the module. To
  // handle this more properly, we should make a DerivedFileUnit class to
  // contain all synthesized implicit type declarations.
  SourceFile &getDeclarationFileUnit() {
    if (original->hasLocation())
      if (auto *declContext = original->getLocation().getAsDeclContext())
        if (auto *parentSourceFile = declContext->getParentSourceFile())
          return *parentSourceFile;
    for (auto *file : original->getModule().getSwiftModule()->getFiles())
      if (auto *src = dyn_cast<SourceFile>(file))
        return *src;
    llvm_unreachable("No files?");
  }

```

But this logic recently resulted in a AST serialization crash:

```swift
// In lib/Serialization/Serialization.cpp:

bool Serializer::isDeclXRef(const Decl *D) const {
  const DeclContext *topLevel = D->getDeclContext()->getModuleScopeContext();
  llvm::errs() << "Serializer::isDeclXRef\n";
  D->dump();
  llvm::errs() << "TOP LEVEL\n";
  topLevel->dumpContext();
  llvm::errs() << "\n";
  if (auto *decl = topLevel->getAsDecl())
    decl->dump();
  if (topLevel->getParentModule() != M)
    return true;
  if (!SF || topLevel == SF)
    return false;
  // Special-case for SIL generic parameter decls, which don't have a real
  // DeclContext.
  if (!isa<FileUnit>(topLevel)) {
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    // This assertion failure triggers. We need another special case to
    // handle structs/enums synthesized during the differentiation SIL
    // transform.
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    assert(isa<GenericTypeParamDecl>(D) && "unexpected decl kind");
    return false;
  }
  return true;
}

```

```swift
Assertion failed: (isa<GenericTypeParamDecl>(D) && "unexpected decl kind"), function isDeclXRef, file /Users/danielzheng/swift-tf/swift/lib/Serialization/Serialization.cpp, line 2043.

```

* * *

**What's the most robust fix for this issue? (In which `FileUnit` should structs/enums synthesized during SILOptimizer transform be added?)**

My guess is reviving `DerivedFileUnit` may be a good solution. [TF-623](https://bugs.swift.org/browse/TF-623) tracks this issue.

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jrose/32/408_2.png) [@jrose](https://forums.swift.org/u/jrose)\
**Post date:** [June 28, 2019, 10:17pm UTC](https://forums.swift.org/t/question-re-adding-derivedfileunit/26427/2 "2019-06-28T22:17:06Z")

</div>

Can you elaborate on what the differentiation transform is supposed to do? What are the inputs and what types are created as a result of that?

---

<div class="post-metadata">

**Author:** ![dan-zheng](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dan-zheng/32/2534_2.png) [@dan-zheng](https://forums.swift.org/u/dan-zheng)\
**Post date:** [June 28, 2019, 10:48pm UTC](https://forums.swift.org/t/question-re-adding-derivedfileunit/26427/3 "2019-06-28T22:48:46Z")

</div>

> [@jrose](#):
>
> Can you elaborate on what the differentiation transform is supposed to do? What are the inputs and what types are created as a result of that?

Sure! (The differentiation transform isn't [documented yet](https://docs.google.com/document/d/1bPepWLfRQa6CtXqKA8CDQ87uZHixNav-TFjLSisuKag/edit#heading=h.4dvbihnesjy), but will be.)

The differentiation transform implements [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation) as a SIL function transformation: it generates derivative functions for "original functions" without registered derivatives.

Auxiliary data structures are:

- **Differential structs** (struct of partially-applied differential closure values).
- **Predecessor enums** (enum representing basic block predecessors, records function execution path to implement "reverse-mode" differentiation).

The details are a bit involved, and much of it isn't relevant. [Here's a Gist with some slides explaining the data structures and transformation.](https://gist.github.com/dan-zheng/c6c8b111547adf3b84392444dca0caff)

* * *

I don't believe details of the differentiation transform are particularly important here. To summarize: type declarations synthesized during SIL transform need to be added to some (top-level?) context. Currently, they're [hackily added to a `SourceFile`](https://github.com/apple/swift/blob/b4483dac64121a60ee46a8f28f3c29ddf1c1abf5/lib/SILOptimizer/Mandatory/Differentiation.cpp#L436), leading to an AST serialization assertion failure (see above). I wonder whether reviving `DerivedFileUnit`, and adding the type declarations to it, makes sense.

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jrose/32/408_2.png) [@jrose](https://forums.swift.org/u/jrose)\
**Post date:** [June 28, 2019, 11:14pm UTC](https://forums.swift.org/t/question-re-adding-derivedfileunit/26427/4 "2019-06-28T23:14:18Z")

</div>

It sounds like the key input, then, is one function written in source with some attribute (`@differentiable` or whatever). That should mean you always have a "home" SourceFile to put declarations in: the one the function lives in. Is that not the case?

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jrose/32/408_2.png) [@jrose](https://forums.swift.org/u/jrose)\
**Post date:** [June 28, 2019, 11:17pm UTC](https://forums.swift.org/t/question-re-adding-derivedfileunit/26427/5 "2019-06-28T23:17:18Z")

</div>

Under what conditions do you _not_ have a valid location in your "hackily added to a SourceFile"?

---

<div class="post-metadata">

**Author:** ![dan-zheng](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dan-zheng/32/2534_2.png) [@dan-zheng](https://forums.swift.org/u/dan-zheng)\
**Post date:** [June 28, 2019, 11:32pm UTC](https://forums.swift.org/t/question-re-adding-derivedfileunit/26427/6 "2019-06-28T23:32:19Z")

</div>

To answer both of your questions: `getDeclarationFileUnit` is always able to get a valid `SourceFile`. The problem is this assertion failure later during AST serialization.

```swift
bool Serializer::isDeclXRef(const Decl *D) const {
  const DeclContext *topLevel = D->getDeclContext()->getModuleScopeContext();

  // DEBUG STATEMENTS.
  llvm::errs() << "TOP LEVEL:\n";
  topLevel->dumpContext();
  llvm::errs() << "SF:\n";

  if (topLevel->getParentModule() != M)
    return true;
  if (!SF || topLevel == SF)
    return false;
  // Special-case for SIL generic parameter decls, which don't have a real
  // DeclContext.
  if (!isa<FileUnit>(topLevel)) {
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    // This assertion failure triggers. We need another special case to
    // handle structs/enums synthesized during the differentiation SIL
    // transform.
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    assert(isa<GenericTypeParamDecl>(D) && "unexpected decl kind");
    return false;
  }
  return true;
}

```

```swift
FAIL: Swift(macosx-x86_64) :: AutoDiff/ast_serialization.swift (10 of 58)
...
TOP LEVEL:
0x7f87f301f848 Module name=main
SF:
(source_file "tf-623.swift"
  ...)

AST SERIALIZATION FAILURE!
(parameter 'anonname=0x7fba268792e0' interface type='_AD __$s17ast_serialization6TF_623yS2fF_bb0__ PB__src_0_wrt_0')
Assertion failed: (isa<GenericTypeParamDecl>(D) && "unexpected decl kind"), function isDeclXRef, file /Users/danielzheng/swift-build/swift/lib/Serialization/Serialization.cpp, line 2066.

7 swiftc 0x000000010df25713 swift::serialization::Serializer::isDeclXRef(swift::Decl const*) const (.cold.2) + 35
8 swiftc 0x000000010aa62ce0 swift::serialization::Serializer::addTypeRef(swift::Type) + 0
9 swiftc 0x000000010aa62855 swift::serialization::Serializer::addDeclRef(swift::Decl const*, bool) + 101
10 swiftc 0x000000010aa874af swift::serialization::Serializer::DeclSerializer::writeParameterList(swift::ParameterList const*) + 111
11 swiftc 0x000000010aa80efb swift::serialization::Serializer::DeclSerializer::visitEnumElementDecl(swift::EnumElementDecl const*) + 1163
12 swiftc 0x000000010aa6ad8e swift::serialization::Serializer::writeDecl(swift::Decl const*) + 350
13 swiftc 0x000000010aa6c456 swift::serialization::Serializer::writeAllDeclsAndTypes() + 3846
14 swiftc 0x000000010aa6d794 swift::serialization::Serializer::writeAST(llvm::PointerUnion<swift::ModuleDecl*, swift::SourceFile*>, bool) + 4212

```

You can see that `topLevel == SF` is false according to the debug statements. Note that there's "Special-case for SIL generic parameter decls" logic in `Serializer::isDeclXRef`: I made a [temporary hack patch](https://github.com/apple/swift/pull/25868) expanding that condition to unblock progress.

I wonder if there's some way to change the [`SourceFile` calculation logic](https://github.com/apple/swift/blob/b4483dac64121a60ee46a8f28f3c29ddf1c1abf5/lib/SILOptimizer/Mandatory/Differentiation.cpp#L436) so that AST serialization passes (i.e. so that `topLevel == SF`)?

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jrose/32/408_2.png) [@jrose](https://forums.swift.org/u/jrose)\
**Post date:** [June 28, 2019, 11:47pm UTC](https://forums.swift.org/t/question-re-adding-derivedfileunit/26427/7 "2019-06-28T23:47:33Z")

</div>

You didn't actually put your new declarations in the SourceFile, though, if `topLevel` is a Module.

---

<div class="post-metadata">

**Author:** ![dan-zheng](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dan-zheng/32/2534_2.png) [@dan-zheng](https://forums.swift.org/u/dan-zheng)\
**Post date:** [June 28, 2019, 11:50pm UTC](https://forums.swift.org/t/question-re-adding-derivedfileunit/26427/8 "2019-06-28T23:50:32Z")

</div>

> [@jrose](#):
>
> You didn't actually put your new declarations in the SourceFile, though, if `topLevel` is a Module.

I'm sorry, I don't fully follow. Could you spell out the problem please (and the fix, if it's clear to you)?

`getDeclarationFileUnit()` returns a `SourceFile` and `SourceFile::addVisibleDecl` is used to add the type declarations in the SIL transform. So it seems to me that the type declarations are added to the `SourceFile`.

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jrose/32/408_2.png) [@jrose](https://forums.swift.org/u/jrose)\
**Post date:** [June 28, 2019, 11:50pm UTC](https://forums.swift.org/t/question-re-adding-derivedfileunit/26427/9 "2019-06-28T23:50:35Z")

</div>

…and oh, that's a parameter. Those are generally created with a dummy DeclContext, but reparented to the FuncDecl (or SubscriptDecl, or whatever) that they're attached to later on. That must be the step you skipped, even if the function and types and stuff are created correctly.

I suggest running the ASTVerifier on your synthesized types in +Asserts builds.

---

<div class="post-metadata">

**Author:** ![dan-zheng](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dan-zheng/32/2534_2.png) [@dan-zheng](https://forums.swift.org/u/dan-zheng)\
**Post date:** [June 28, 2019, 11:52pm UTC](https://forums.swift.org/t/question-re-adding-derivedfileunit/26427/10 "2019-06-28T23:52:51Z")

</div>

> [@jrose](#):
>
> I suggest running the ASTVerifier on your synthesized types in +Asserts builds.

I wonder how to run ASTVerifier? Should I expect ASTVerifier to reveal issues in the AST other than the serialization failure?

Thanks for your help 🙂

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jrose/32/408_2.png) [@jrose](https://forums.swift.org/u/jrose)\
**Post date:** [June 29, 2019, 12:00am UTC](https://forums.swift.org/t/question-re-adding-derivedfileunit/26427/11 "2019-06-29T00:00:21Z")

</div>

> [@dan-zheng](#):
>
> I wonder how to run ASTVerifier? Should I expect ASTVerifier to reveal issues in the AST other than the serialization failure?

Very possibly. :-) You can call `swift::verify(theDecl)`. Note that this is already recursive, so you don't need to do it separately for members if they've already been created.

It looks like AbstractFunctionDecl::setParameters is already supposed to be setting the DeclContext for parameters, so you can look into why that's not happening for your case.
