Simple infinite loops not looping?

In some cases, a very simple infinite while loop doesn’t loop inifinitly, I guess when the compiler (?) detects the loop is doing nothing and can never escape. Sure, I don’t see any scenario where this could be a problem, but I would like to understand why:

f(x) = while true end
f(1) # loops infinitely like expected

f(x) = while x end
f(true) # isn't stuck in the loop, exits immediatly

as soon as there’s something in the loop, or the condition accesses a global variable, this of course doesn’t happen

more oddities:

f(x) = while x<1 end
f(0)

loops forever in Julia 1.0.5 but not in more modern versions (I tested 1.3.0, 1.4.1, 1.5.2, 1.6.1)

Yes, it looks like LLVM optimizes away the loop:

julia> @code_llvm f(true)
;  @ REPL[3]:1 within `f'
define void @julia_f_169(i8 zeroext %0) {
top:
  ret void
}

This gave an infinite loop in Julia 0.4 and 0.5, but not in 0.6.

Apparently, LLVM sometimes assumes that loops with no side effects terminate—because failure to terminate is undefined behavior in C++, the compiler thinks it is allowed to do what it wants: [llvm-dev] Infinite loops with no side effects … supposedly it will be fixed in LLVM 12.

3 Likes

There is actually an open issue about this:

3 Likes