Is it possible for the compiler to warn about potential stack overflows at compile time?

I'm wondering if it's technically feasible for the Swift compiler to emit a warning at compile time when the estimated stack memory usage exceeds a certain threshold.

Recently, I encountered a crash due to a stack overflow. I was able to resolve the issue by refactoring the code to use copy-on-write semantics instead. However, I feel that if there had been a compile-time warning about the potential stack usage, I could have prevented the crash ahead of time.

Since stack size can often be approximated at compile time—especially in cases involving large value types or large local variables—I’m curious if this is something that could be supported in the Swift toolchain.

Any insights or related discussions would be greatly appreciated!

1 Like

What was the memory footprint of your type before migrating to copy-on-write? By any chance did you also measure a reduction in binary size?

I believe Clang has a -Wstack-usage flag to diagnose individual functions with large stack frames. We could do something similar in Swift, perhaps by adding an LLVM pass that uses debug info to recover source locations of functions.

You can imagine something fancier which looks at the call graph and attempts to find deep call stacks, but of course that necessarily must be an approximation of the true runtime behavior.

Unspecialized generics and resilient value types also complicate the picture because those involve stack allocations of dynamic size…

3 Likes

There are many complicating factors... listing a few:

  • stack overflow could happen even for tiny values on stack frames (with deep enough recursion).
  • stack size is not known at compile time (e.g. main thread vs secondary thread vs a thread with specific thread size vs a thread on watchOS v macOS, etc).

as a linter warning like "this type is > 16K, are you sure?" - maybe that's useful.

2 Likes