Wednesday, April 20, 2011

How does the Delphi 2009 compiler handle recursive inline methods?

Do "What's wrong with using inline functions" and "Can a recursive function be inline" apply to Delphi inline functions? Furthermore, does anyone know how recursive inline functions are handled in Delphi?

From stackoverflow
  • My guess is probably not since inline is only a suggestion, but lets find out.

    A simple recursive factorial routine:

    function Factorial(const aNum: cardinal): cardinal;
    begin
      if aNum > 1 then
        Result := Factorial(aNum - 1) * aNum
      else
        Result := 1;
    end;
    

    Here is the disassembly of the call to it:

    // fact := Factorial(5);
    mov eax,$00000005
    call Factorial
    mov ebx,eax
    

    And the disassembly of the routine itself:

    // 9: begin
    push ebx
    mov ebx,eax
    // 10: if aNum > 1 then
    cmp ebx,$01
    jbe $0040ab30
    // 11: Result := Factorial(aNum - 1) * aNum
    mov eax,ebx
    dec eax
    call Factorial
    imul ebx
    pop ebx
    ret 
    // 13: Result := 1;
    0040ab30: mov eax,$00000001
    // 14: end;
    pop ebx
    ret
    

    Now we make it inline and see what is different in the call:

    // 21: fact := Factorial(5);
    mov eax,$00000005
    call Factorial
    mov ebx,eax
    

    And the routine itself:

    // 9: begin
    push ebx
    mov ebx,eax
    // 10: if aNum > 1 then
    cmp ebx,$01
    jbe $0040ab30
    // 11: Result := Factorial(aNum - 1) * aNum
    mov eax,ebx
    dec eax
    call Factorial
    imul ebx
    pop ebx
    ret     
    // 13: Result := 1;
    0040ab30: mov eax,$00000001
    // 14: end;
    pop ebx
    ret
    

    And they both appear the same to me, so I am going to stick with my original hypothesis and say they are not supported.

    BTW: this is in Delphi 2009.

    Peter Turner : Thanks for the good answer. RE: "In Delphi 2009" I was looking through my Object Pascal reference for Delphi 7, apparently inline has been a forward-compatible keyword for a long time, it just never did anything back then.
    Jim McKeeth : Seems like I remember seeing it a while ago too.
    Rob Kennedy : "Inline" used to be how you could put raw machine code into your functions. Now you just use "asm" blocks, and if you want instructions that the compiler doesn't know, you insert the bytes with DB, DW, and DD instructions.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.