[llvm-dev] Regarding ScalarEvolution's loop backedge computation

Chawla, Pankaj via llvm-dev llvm-dev at lists.llvm.org
Thu Jun 30 12:12:35 PDT 2016

Hi Sanjoy,

Thank you for the clarification!
I will give it a try and put up the changes for review.


-----Original Message-----
From: Sanjoy Das [mailto:sanjoy at playingwithpointers.com] 
Sent: Wednesday, June 29, 2016 5:02 PM
To: Chawla, Pankaj
Cc: llvm-dev at lists.llvm.org
Subject: Re: [llvm-dev] Regarding ScalarEvolution's loop backedge computation

Hi Pankaj,

Chawla, Pankaj via llvm-dev wrote:
 > It looks like ScalarEvolution bails out of loop backedge computation if  > it cannot prove the IV stride as either positive or negative (based on  > loop control condition). I think this logic can be refined for signed IVs.
 > Consider this simple loop-
 > void foo(int *A, int n, int s) {
 > int i;
 > for(i=0; i<n; i += s) {
 > A[i]++;
 > }
 > }
 > The IV of this loop has this SCEV form-  >  > {0,+,%s}<nsw><%for.body>

This looks valid -- we already do things like this for

for (i = A; i != B; i += 5)

and compute the backedge taken count as "(B - A) / 5" (roughly :) ) since if (B - A) is not divisible by 5 then we have UB due to overflow.  We just have to be careful around cases like:

   for(i = 0; i < 60; i += s) {

"s" can be (say) -3 and the loop can take 160 backedges and then "exit(0)", avoiding the undefined behavior due to underflow.  "s" can also be zero, in which case the loop can potentially take an infinite number of backedges.

However, in the example you gave (written in LLVM's canonical rotated

   if (0 < N) {
     i = 0;
     do {
       i += s; // NSW add
     } while (i < N);

For any s <= 0 we have undefined behavior, so it is sound to assume s  > 0.

Do you want to take a crack at fixing this?  I'm traveling till the 10th of July, but I can review your change once I'm back.

-- Sanjoy

More information about the llvm-dev mailing list