Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Naked recursion segfaults the compiler #163

Open
Hugobros3 opened this issue Jun 24, 2024 · 1 comment
Open

Naked recursion segfaults the compiler #163

Hugobros3 opened this issue Jun 24, 2024 · 1 comment

Comments

@Hugobros3
Copy link
Contributor

The following snippet (written using AnyDSL/artic#23):

#[export]
fn main (a : i32) -> i32 {
    test(a)
}

fn test(a : i32) -> ! {
  test2(a)
}

fn test2(a : i32) -> ! {
  test(a)
}

Crashes the compiler because ETA-reduction in Importer is greedy and skips rebuilding test, only attempting to rebuild the callee test2, and then vice versa, endlessly up until we get a segfault.

m-kurtenacker added a commit that referenced this issue Jun 24, 2024
* C backend: do not expect body->arg(0) to always exist in emit_epilogue.
* LLVM Backend: Do not expect ret to exist in CodeGen::convert(Type*).
@Hugobros3
Copy link
Contributor Author

This patch should fix the issue:

diff --git a/src/thorin/transform/importer.cpp b/src/thorin/transform/importer.cpp
index 2bebb9d07..6c97a0cb9 100644
--- a/src/thorin/transform/importer.cpp
+++ b/src/thorin/transform/importer.cpp
@@ -65,10 +65,15 @@ const Def* Importer::rewrite(const Def* const odef) {
                     goto rebuild;
 
                 if (body->args() == cont->params_as_defs()) {
-                    src().VLOG("simplify: continuation {} calls a free def: {}", cont->unique_name(), body->callee());
                     // We completely replace the original continuation
                     // If we don't do so, then we miss some simplifications
-                    return instantiate(body->callee());
+                    src().VLOG("simplify: continuation {} calls a free def: {}", cont->unique_name(), body->callee());
+                    // However, we need a safety in the case of 'naked' recursion:
+                    auto safety = cont->stub(*this, instantiate(cont->type())->as<FnType>());
+                    insert(odef, safety);
+                    auto eta_reduced = instantiate(body->callee());
+                    safety->jump(eta_reduced, safety->params_as_defs());
+                    return eta_reduced;
                 } else {
                     // build the permutation of the arguments
                     Array<size_t> perm(body->num_args());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant