Problem in Fortran Matrix Offloading: Transpose Example
Fortran stores matrix in Column-Major ordering, while normal backends stores matrix in Row-Major ordering, which will brings trouble.
I will use matrix transpose as an example to explain.
1 Problem
Consider following example:
In Fortran, we create a matrix A, print it, stores in memory and returns a pointer pF.
Pass pF to a different backend, suppose C++, do a transpose and stores the result in pc
Back to Fortran, recover data from pC, print it.
Question: will step 3 print the correct result as we expected?
2 Case 1: N×N Matrix
Suppose the original matrix is 3×3 matrix:
AFortran=147258369(Printed in Step 1)
When Fortran stores it in memory, it will become something like:
[1,4,7,2,5,8,3,6,9](Memory Stored from Fortran)
Pass to C++ backend, when recovering, C++ would think it is a matrix like:
AC++=123456789
Do the transpose, it becomes:
(AC++)T=147258369
Save to pC:
[1,2,3,4,5,6,7,8,9](Memory Stored from Cpp)
When recovering from it, Fortran again scans it thinking is stores in columns:
(AFortran)T=123456789(Printed in Step 3)
Notice that the result is correct by coincident! Because we scan the memory in a wrong way TWICE.
3 Case 2: N×M Matrix (N=M)
We’re not this lucky if we’re going to transpose matrix with different length in size.
Suppose the original matrix is 2×3 matrix:
BFortran=[142536](Printed in Step 1)
When Fortran stores it in memory, it will become something like:
[1,4,2,5,3,6](Memory Stored from Fortran)
Pass to C++ backend, when recovering, C++ would think it is a matrix like:
BC++=[154326]
Do the transpose, it becomes:
(BC++)T=142536
Save to pC:
[1,5,4,3,2,6](Memory Stored from Cpp)
When recovering from it, Fortran again scans it thinking is stores in columns:
(BFortran)T=154326(Printed in Step 3)
Notice that this is NOT the correct transpose of step 1.