Introduction

Recently, I came across a function that checks whether an array is sorted, i.e. if there is no element which would be greater than its successor. Below is a sample implementation:

bool is_sorted ( const int32_t * input , size_t n ) { if ( n < 2 ) { return true ; } for ( size_t i = 0 ; i < n - 1 ; i ++ ) { if ( input [ i ] > input [ i + 1 ]) return false ; } return true ; }

I was sure that such a trivial loop is autovectorized by all decent compilers. I checked this on Compiler Explorer and to my surprise none of compilers does it. This is the state for GCC 7.3 (and upcoming GCC 8.0), clang 6.0 and ICC 19.

This text explores possible vectorization schemas.