[Issue 14419] [CTFE] Need infinite loop detection?

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Mon Apr 6 09:44:44 PDT 2015


https://issues.dlang.org/show_bug.cgi?id=14419

--- Comment #6 from Jens Bauer <jens-bugzilla at gpio.dk> ---
(In reply to Kenji Hara from comment #2)
> How to do it for a complex code?
> 
> int foo(int n = 0)
> {
>     while (true)
>     {
>         ++n;
>         if (n > 1_000_000)
>             break;
>     }
>     return 1;
> }
> enum bar = foo;  // User meant to type '&foo'

I would check if the 'exit' condition changes.
When the code is compiled, it boils down to two or three interesting
assembly-languge instructions:

1: compare
2: conditional branch forward
3: branch always backward

If the argument to 'compare' changes, then the loop would most likely not be
infinite and thus most likely be safe to execute.

There might be multiple conditions, though, which makes things a bit more
complex.

However, I sense that there might be possible ways that the condition could
change on every compare, where it wouldn't be safe to just check for changes.
Example:

int Init_element(n)
{
  l = 17;
  while(1)
  {
    n = 3 - n;
    if(n == 0) break;
    l *= 31415927;
  }
  return(l);
}

Because of the 'toggling', the compiler might not be able to predict that this
keeps going on for eternity.

Such cases are of course rare, but should still be considered.

--


More information about the Digitalmars-d-bugs mailing list