Home > Software engineering >  Openmp with more than INT_MAX iterations - is it legal?
Openmp with more than INT_MAX iterations - is it legal?

Time:01-06

Here is a loop that works perfectly fine:

#include <inttypes.h>
#include <iostream>
int main() {
  for (int32_t i = -2; i < INT32_MAX-2; i  ) {
    std::cout << i << std::endl;
  }
}

Adding omp parallel for clause seems to break the code by introducing int overflow.

#include <inttypes.h>
#include <iostream>
int main() {
  #pragma omp parallel for
  for (int32_t i = -2; i < INT32_MAX; i  ) {
    std::cout << i << std::endl;
  }
}

For both clang-10 and gcc-10 the program produces no output. clang-12 on the other hand seems to handle it properly.

clang-10 at least produces some warnings:

> clang  -10 int_div.cpp -Wall -fopenmp
int_div.cpp:133:3: warning: overflow in expression; result is -2147483647 with type 'int' [-Winteger-overflow]
  for (int i = -2; i < INT32_MAX; i  ) {
  ^
int_div.cpp:133:3: warning: overflow in expression; result is 2147483646 with type 'int' [-Winteger-overflow]
int_div.cpp:133:3: warning: overflow in expression; result is -2147483647 with type 'int' [-Winteger-overflow]
int_div.cpp:133:3: warning: overflow in expression; result is -2147483647 with type 'int' [-Winteger-overflow]
int_div.cpp:133:3: warning: overflow in expression; result is -2147483647 with type 'int' [-Winteger-overflow]

Is this a legal, well defined behavior of openmp standard or an implementation bug?

CodePudding user response:

#pragma omp parallel for would result in the execution flow with omp_get_num_threads() for loop count, something like:

for (int32_t i = -2; i < INT32_MAX; i  = omp_get_num_threads())
  std::cout << i << std::endl;

for (int32_t i = -1; i < INT32_MAX; i  = omp_get_num_threads())
  std::cout << i << std::endl;

// ...

for (int32_t i = -2   omp_get_thread_num() - 1; i < INT32_MAX; i  = omp_get_num_threads())
  std::cout << i << std::endl;

The second and further threads would result in signed integer overflow.

CodePudding user response:

OpenMP loops need to compute the number of iterations before starting the loop, so the type of the loop variable needs to be such that the number is expressible. Other than that, the OMP standard allows both signed and unsigned integer types, with no restriction indicated.

  •  Tags:  
  • Related