Author Topic: Nasm & gfortran  (Read 11559 times)

nobody

  • Guest
Nasm & gfortran
« on: December 14, 2008, 05:06:08 PM »
Hi

I'm dissecting a Fortran function (32-bit) to see how things
get passed around and returned. Unlike C, Fortran calls by
reference so pointers are automatically passed in function
args, and the function's return value must be assigned to the
function name before returning.

Here's the function:

integer function incr(k)
      incr = k + 1
      return
      end

And a main program if anyone is adventurous enough to run it:

integer  k

k = 0
      k = incr(k)
      print *, k
      end

And here's the output listing incr.s from gfortran -S incr.f,
with a few of my comments:

.file   "incr.f"
   .text
.globl incr_
   .type   incr_, @function
incr_:
   pushl   %ebp
   movl   %esp, %ebp
   subl   $16, %esp
   movl   8(%ebp), %eax       ;eax gets addr of 1st arg
   movl   (%eax), %eax          ;gets contents of addr
   addl   $1, %eax                  ;increment eax
   movl   %eax, -4(%ebp)      ;save return value
   movl   -4(%ebp), %eax      ; ???
   leave
   ret
   .size   incr_, .-incr_
   .ident   "GCC: (GNU) 4.3.2 20081105 (Red Hat 4.3.2-7)"
   .section   .note.GNU-stack,"",@progbits


My question is, What is going on in the last two movl ops?
It looks like the 2nd movl is just doing the reverse of the
1st movl, like a=b followed by b=a.

Michael

nobody

  • Guest
Re: Nasm & gfortran
« Reply #1 on: December 14, 2008, 10:01:14 PM »
Maybe intending:

mov [ebp -4], eax
; popa - but we didn't need to pusha
mov eax, [ebp -4]

I don't know anything about Fortran. Gcc will produce some pretty dumb code if not given an optimization switch (-O2 or -O3). If gfortran has such an optimization switch, try that...

Best,
Frank

nobody

  • Guest
Re: Nasm & gfortran
« Reply #2 on: December 15, 2008, 03:47:04 AM »
Learning by doing. Awesome!

And, just like C,  it looks like I can leave the return value in EAX (for 32-bit).

Thanks,

Michael

===============

[michael@localhost ~]$ gfortran -S -O2 incr.f
[michael@localhost ~]$ cat incr.s
   .file   "incr.f"
   .text
   .p2align 4,,15
.globl incr_
   .type   incr_, @function
incr_:
   pushl   %ebp
   movl   %esp, %ebp
   movl   8(%ebp), %eax
   popl   %ebp
   movl   (%eax), %eax
   addl   $1, %eax
   ret
   .size   incr_, .-incr_
   .ident   "GCC: (GNU) 4.3.2 20081105 (Red Hat 4.3.2-7)"
   .section   .note.GNU-stack,"",@progbits
[michael@localhost ~]$