assembly


Addendum

// 1. Allocate heap boxes for `aLocalVar` and `[weak self]`
%4  = alloc_box ${ var Bool }, var, name "aLocalVar"
%12 = alloc_box ${ var @sil_weak Optional<MyView> }

// 2. Initialize the weak reference in the heap box
%14 = project_box %13, 0
store_weak %16 to [init] %14

// 3. Build the closure (`partial_apply`), capturing the boxes
%23 = partial_apply %closure(%20, %21)
%24 = move_value %23 // changeToolBlock

// 4. Release caller's initialization handle to the weak box
destroy_value %12

// 5. Call the closure (the closure still retains the heap box!)
%37 = apply %36(%35) : $@callee_guaranteed (@guaranteed String) -> ()

// 6. Cleanup at the very end of keyDown
destroy_value %24 // release closure
destroy_value %4  // release aLocalVar box

The optimized SIL:

sil private [thunk] @MyView.keyDown(with:) : $@convention(objc_method) (NSEvent, MyView) -> () {
bb0(%0 : $NSEvent, %1 : $MyView):

  // 1. Stack allocations instead of heap boxes:
  %3 = alloc_stack [var_decl] $Bool, var, name "aLocalVar"
  %7 = alloc_stack [lexical] $@sil_weak Optional<MyView>

  // 2. Initialize weak self on the stack:
  %8 = enum $Optional<MyView>, #Optional.some!enumelt, %1
  store_weak %8 to [init] %7

  // 💥 3. THE FATAL BUG: AllocBoxToStack destroys and frees %7 immediately!
  destroy_addr %7                                 // <-- Destroys the weak reference!
  dealloc_stack %7                                // <-- Frees stack slot %7!

  // 4. Set up the argument string "mytest":
  %21 = struct $String (...)

  // 💥 5. Invokes the closure, passing the ALREADY DEALLOCATED %7 stack address:
  %22 = apply %13(%21, %7, %3) : $@convention(thin) (@guaranteed String, 
                                                     @inout_aliasable @sil_weak Optional<MyView>, 
                                                     @inout_aliasable Bool) -> ()

  // 6. aLocalVar stack slot %3 is properly kept alive until here:
  dealloc_stack %3
  return %26
}

And inside the closure:

sil private @specialized closure #1 in MyView.keyDown(with:) : ... {
bb0(%0 : $String, %1 : $*@sil_weak Optional<MyView>, %2 : $*Bool):
  
  // Line 41: guard let self else { return }
  %6 = load_weak %1                               // 💥 Tries to read from deallocated %7!
  switch_enum %6, case #Optional.some: bb1, case #Optional.none: bb2
  ...

  1. Logged in the Console: Weak reference loaded from 0x16f2c2810 contains 0xfad00749cbd0500 which is not in the weak references table ↩︎
Read more