Search code examples
assemblymemoryfortranheap-memorystack-memory

Is there any way to tell if a variable was optimized out?


I had some fortran code that looked something like:

 subroutine foo(mx,my,mz)
    real pts(3,mx,my,mz)
 end

the array pts was never actually used in the subroutine -- I just forgot to delete it when I refactored my code. Now, since fortran has no concept of stack vs. heap, It's up to the compiler where to allocate pts -- This is a function of the array size in gfortran, but I haven't been able to figure out how the portland group compiler handles this.

Is it possible to tell whether pts is allocated on the stack, heap, or if it is completely optimized out altogether (as it probably should be)? Is it possible to have a stackoverflow and not know it (i.e. not have a runtime error)? My instinct is that it should be possible to tell by looking at the assembly produced by the compiler, but I have no clue what I'd be looking at there.


Solution

  • The easiest way is to look at the assembly code that the compiler provides when you compile with -S or to look for symbols with the debugger. If the array is allocated on the heap, there will most probably be a call to the allocation function:

    • gfortran inserts calls to malloc
    • ifort by default allocates all arrays on the stack. If you enable automatic heap arrays by -heap-arrays <size> it will generate calls to for_alloc for heap allocation
    • PGI compilers generate calls to pgf90_auto_alloc but I have no experience with this compiler and the way it allocates arrays

    By the way, gfortran drops the array when it is not referenced even with the default optimisation level. I would guess the other compilers do the same but I won't bet on it.