[LLVMdev] Is infinite empty loop dead code?

Duncan Sands baldrick at free.fr
Wed Nov 14 01:17:21 PST 2012


On 14/11/12 09:56, 陳韋任 (Wei-Ren Chen) wrote:
> On Wed, Nov 14, 2012 at 12:22:33AM -0800, Shuxin Yang wrote:
>> I do some google, I cannot find the answer...
>> I check C std, I cannot find answer either.
>>
>> Delete infinite empty loop is boring, but if C/C++ lawyers could tell it
>> is safe to to so,
>> it would obviate the need to prove a non-countable loop infinite or not
>> before
>> DCE can delete it.
>>
>> That is the answer I'm waiting for to delete a disgusting dead
>> non-countable loop in my way.
>
>    Perhaps Duncan will give you a proper keyword to search in GCC/LLVM
> ML archieve. I found a page [1], and iiuc, the C standard allow the
> implementation (i.e., the compiler) to remove such empty infinite loop.

GCC's current policy is described in the GCC manual:


    * Deleting "empty" loops.

      Historically, GCC has not deleted "empty" loops under the
      assumption that the most likely reason you would put one in a
      program is to have a delay, so deleting them will not make real
      programs run any faster.

      However, the rationale here is that optimization of a nonempty loop
      cannot produce an empty one. This held for carefully written C
      compiled with less powerful optimizers but is not always the case
      for carefully written C++ or with more powerful optimizers.  Thus
      GCC will remove operations from loops whenever it can determine
      those operations are not externally visible (apart from the time
      taken to execute them, of course).  In case the loop can be proved
      to be finite, GCC will also remove the loop itself.

      Be aware of this when performing timing tests, for instance the
      following loop can be completely removed, provided
      `some_expression' can provably not change any global state.

           {
              int sum = 0;
              int ix;

              for (ix = 0; ix != 10000; ix++)
                 sum += some_expression;
           }

      Even though `sum' is accumulated in the loop, no use is made of
      that summation, so the accumulation can be removed.


Ciao, Duncan.



More information about the llvm-dev mailing list