Implement function calls for 8051

Let's say you have an 8051 microcontroller without external RAM. The internal memory is 128 bytes and you have about 80 bytes. And you want to write a compiler for the stack language.

Suppose you want to compile an RPN expression 2 3 +. 8051 has built-in instructions pushand popso you can write

push #2
push #3

Then you can implement +as:

pop A     ; pop 2 into register A
pop B     ; pop 3 into register B
add A, B  ; A = A + B
push A    ; push the result on the stack

Simple, right? But in this case it is +implemented as an integrated assembly. What if you want to reuse this code and put it in a routine? Fortunately, the 8051 has instructions lcalland ret. lcall LABELpushes the return address onto the stack and goes to LABEL, and retreturns to the address indicated at the top of the stack. However, these operations interfere with our stack, so if we do lcallto get to our implementation +, the first command pop Awill print the return address instead of the value we want to use.

, , , . , .

, , ?

8051: http://sites.fas.harvard.edu/~phys123/8051_refs/8051_instruc_set_ref.pdf

+4
1

.

, , "" , . , : , , , .

:

    push #2
    push #3
    lcall   my_add
    ...

myadd:
    pop r6     ; save the return address
    pop r7
    pop a
    pop b
    add a, b
    push a
    push r7
    push r8
    ret

, " ", " " . , " ", :

myadd:
    pop r6     ; save the return address
    pop r7
    pop a
    pop b
    add a, b
    jmp  push_a_return

    ...

 ; compiler library of commonly used code:
 push_ab_return: ; used by subroutines that return answer in AB
     push b
 push_a_return: ; used by subroutines that return answer in A
     push a
 return: ; used by subroutines that don't produce a result in register
     push r7
     push r6
     ret

 push_b_return: ; used by subroutines that compute answer in B
     push b
     jmpshort return

, , , . . , , , , , - , , , .

- , , . , 8 ( ) R0..R7 A B. .

, , , ( , , [, 3- ] . -, ( ), , R0..R7, , , , ( 8- "top", ), , ( "" 64). , , 65 127 ( , , , 8051).

, . , , A, B, , , , MOV, , .

, B, ; - , , "" . , ; R6 R7 , . , .

, , , , . , ; C (GCC ). , .

, ( C)

 byte X=2;
 byte Y=3;
 { word Q=X*Y;
   call W()
 }     

 byte S;

  W()
    { S=Q; }

( )

 X to R1
 Y to location 17
 Q to the stack
 S to R3

 MOV R1,2
 MOV A, 3
 MOV 17, A
 MOV A, 17
 MOV B, A
 MOV A, R1
 MUL
 PUSH A   ; Q lives on the stack
 PUSH B
 CALL W
 POP  A   ; Q no longer needed
 POP  B
 ...

 W:
 POP R6
 POP R7
 POP A
 POP B
 MOV R3, B
 JMP PUSH_AB_RETURN

. ( ).

+2

All Articles