llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

Vectorization improvement opportunity for loops with stride

Open serguei-katkov opened this issue 8 years ago • 1 comments

Bugzilla Link 36448
Version trunk
OS Windows NT
CC @topperc,@hfinkel,@rotateright

Extended Description

Let's consider the following loop (https://godbolt.org/g/W8z3dY)

void testStride(int a[], int b[], int N) {
  for (int i = 0; i < N; i+=2)
    a[i] = b[i];
}

If we specify that we have avx-512 support (-march=skylake-avx512) LLVM will be able to vectorize it using Gather/Scatter.

However if we do not have the avx-512 support LLVM will not vectorize this loop due to its cost model detects it is inefficient because it needs to scalarize the memory access.

At the same time LLVM Vectorizer supports masked load/store but it is not used for loops with stride access. It is only used for loops with conditions.

Specifically if I re-write the loop as

void testCond(int a[], int b[], int N) {
  for (int i = 0; i < N; i++)
    if ((i % 2) == 0)
      a[i] = b[i];
}

LLVM vectorizes this loop and uses masked load/store. However it has a problem to detect a simple stride pattern for mask and computes it on each iteration.

So I guess there are two opportunities here:

  1. Support masked load/store for stride access to memory
  2. Be clever in determine invariant mask hoisting from the loop.

serguei-katkov avatar Feb 20 '18 05:02 serguei-katkov

Seems like the first question is to decide which loop is canonical:

Non-unit-stride:

for.body:
  %iv = phi i64 [ 0, %preheader ], [ %iv.next, %for.body ]
  %bptr = getelementptr inbounds i32, i32* %b, i64 %iv
  %ld = load i32, i32* %bptr
  %aptr = getelementptr inbounds i32, i32* %a, i64 %iv
  store i32 %ld, i32* %aptr
  %iv.next = add nuw nsw i64 %iv, 2
  %cmp = icmp slt i64 %iv.next, %0
  br i1 %cmp, label %for.body, label %exit
}

Or unit-stride:

for.body:  
  %iv = phi i64 [ 0, %preheader ], [ %iv.next, %for.inc ]
  %lobit = and i64 %iv, 1
  %even = icmp eq i64 %lobit, 0
  br i1 %even, label %if.even, label %for.inc

if.even:
  %bptr = getelementptr inbounds i32, i32* %b, i64 %iv
  %ld = load i32, i32* %bptr
  %aptr = getelementptr inbounds i32, i32* %a, i64 %iv
  store i32 %ld, i32* %aptr
  br label %for.inc

for.inc:
  %iv.next = add nuw nsw i64 %iv, 1
  %exitcond = icmp eq i64 %iv.next, %wide.trip.count
  br i1 %exitcond, label %fexit, label %for.body

rotateright avatar Feb 20 '18 18:02 rotateright