Skip to content

Optimizer can't remove unused code without side effects  #66496

Closed
@DmT021

Description

@DmT021

Motivation

While prototyping a solution to this issue, I encountered a strange behavior of the optimizer.

It appears that the optimizer considers init with an assignment to a class let to be optimizable. However, it does not consider init with an assignment to a class var to be optimizable.

Let's compare these two pieces of code.

final class Foo<T> {
    let v: T

    init(_ v: T) {
        self.v = v
    }
}

@inline(never)
func testFoo() {
    _ = Foo(1)
}

And

final class Bar<T> {
    var v: T

    init(_ v: T) {
        self.v = v
    }
}

@inline(never)
func testBar() {
    _ = Bar(1)
}

The first one (with let field) compiles into no code aside from ret, as expected:

output.testFoo() -> ():
        ret

And the second one (with var field) compiles into invocation of __swift_instantiateConcreteTypeFromMangledName and swift_initStackObject:

output.testBar() -> ():
        sub     rsp, 24
        lea     rdi, [rip + (demangling cache variable for type metadata for output.Bar<Swift.Int>)]
        call    __swift_instantiateConcreteTypeFromMangledName
        mov     rsi, rsp
        mov     rdi, rax
        call    swift_initStackObject@PLT
        add     rsp, 24
        ret

Live code
It feels a little like a bug somewhere.

Solution

I don't know.

Additional context
Discussion

Metadata

Metadata

Assignees

Labels

DCEArea → compiler → SILOptimizer: Dead Code EliminationSILOptimizerArea → compiler: SIL optimization passescompilerThe Swift compiler itselffeatureA feature request or implementation

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions