r/ProgrammingLanguages • Futhark • 2d ago

Hoisting explosive code out of loops

https://futhark-lang.org/blog/2026-11-18-hoisting-unsafe-code.html
19 Upvotes

6 comments sorted by

3

u/zizox99hd 2d ago

Nice post. One typo (I think?) In the very first example of the post. You mention that if m==0, we perform division by zero. But inv is a divided by n not by m.

1

u/Athas Futhark 2d ago

Indeed, thanks for noticing. At some point during the writing process I renamed the variables, and apparently messed it up.

1

u/foonathan 1d ago

Why don't you just hoist:

while x > 0 {
   let inv = foo();
   body();
}

as

if x > 0 {
    let inv = foo();
    body();
    while x > 0 {
        body();
    }
}

?

1

u/Athas Futhark 1d ago

What would be the advantage of that? There are some disadvantages:

  • It duplicates the body of the loop.
  • We cannot hoist the invariant code even further, out of that if, unless we protect it as described in the post.
  • It puts the loop as a whole into control flow, and since Futhark is a pure value-oriented language, it needs an else branch. This may make subsequent analysis harder.
  • It does not work well with parallel loops like map, which are the main thing we care about in Futhark.

1

u/foonathan 1d ago

You don't necessarily need to duplicate the body, you can jump past the condition, no? And why would you want to hoist the invariant out of the if, assuming it is not needed anywhere else? And if it is needed, you wouldn't need to protect it.

Good point about parallelization though.

1

u/Embarrassed-Crow9283 1d ago

Why not something like...

maybe let maybe_inv = foo();

and then let the inside be like:

let inv = maybe_inv.unwrap();

You can then do whatever safely and simply and maybe optimize the unwrap process separately.