ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures...
-
Upload
melanie-robertson -
Category
Documents
-
view
216 -
download
0
Transcript of ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures...
![Page 1: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/1.jpg)
ECE291ECE291
Lecture 6Lecture 6
Procedures and macrosProcedures and macros
![Page 2: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/2.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 22 of 36 of 36
Lecture outlineLecture outline
ProceduresProcedures
Procedure call mechanismProcedure call mechanism
Passing parametersPassing parameters
Local variable storageLocal variable storage
C-Style proceduresC-Style procedures
RecursionRecursion
MacrosMacros
![Page 3: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/3.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 33 of 36 of 36
Procedures definedProcedures defined
Procedures are chunks of code that usually Procedures are chunks of code that usually perform specific frequently used tasksperform specific frequently used tasksThey can be repeatedly called from someplace They can be repeatedly called from someplace else in your programselse in your programsThese are essentially the same thing as These are essentially the same thing as functions or subroutines in high-level languagesfunctions or subroutines in high-level languagesProcedures may have inputs/outputs, both, Procedures may have inputs/outputs, both, either, neithereither, neitherEssentially just labeled blocks of assembly Essentially just labeled blocks of assembly language instructions with a special return language instructions with a special return instruction at the endinstruction at the end
![Page 4: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/4.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 44 of 36 of 36
Procedure exampleProcedure example..start..start;here’s my main program;here’s my main programmov ax, 10hmov ax, 10hmov bx, 20hmov bx, 20hmov cx, 30hmov cx, 30hmov dx, 40hmov dx, 40hcall AddRegscall AddRegs ;this proc does AX + BX + CX + DX ;this proc does AX + BX + CX + DX AX AX;here’s the rest of my main program;here’s the rest of my main programcall DosExitcall DosExit
;---------------------------------------------------------------;---------------------------------------------------------------AddRegsAddRegs
add ax, bxadd ax, bxadd ax, cxadd ax, cxadd ax, dxadd ax, dx
retret
![Page 5: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/5.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 55 of 36 of 36
Proc prime directiveProc prime directive
Procs should never alter the contents of Procs should never alter the contents of any register that the procedure isn’t any register that the procedure isn’t explicitly supposed to modifyexplicitly supposed to modifyIf for example a proc is supposed to return If for example a proc is supposed to return a value in AX, it is not only okay but a value in AX, it is not only okay but required for it to modify AXrequired for it to modify AXNo other registers should be left changedNo other registers should be left changedPush them at the beginning and pop them Push them at the beginning and pop them at the endat the end
![Page 6: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/6.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 66 of 36 of 36
CallCall
Call does two thingsCall does two things It pushes the address of the instruction It pushes the address of the instruction
immediately following the call statement onto immediately following the call statement onto the stackthe stack
It loads the instruction pointer with the value It loads the instruction pointer with the value of the label marking the beginning of the of the label marking the beginning of the procedure you’re calling (this is essentially an procedure you’re calling (this is essentially an unconditional jump to the beginning of the unconditional jump to the beginning of the procedureprocedure
![Page 7: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/7.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 77 of 36 of 36
Two kinds of callsTwo kinds of calls
Near callsNear calls Allow jumps to procedures within the same Allow jumps to procedures within the same
code segmentcode segment In this case, only the instruction pointer gets In this case, only the instruction pointer gets
pushed onto the stackpushed onto the stack
Far callsFar calls Allow jumps to anywhere in the memory Allow jumps to anywhere in the memory
spacespace In this case, both the contents of the CS and In this case, both the contents of the CS and
IP registers get pushed onto the stackIP registers get pushed onto the stack
![Page 8: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/8.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 88 of 36 of 36
Passing parametersPassing parameters
Using registersUsing registers Registers are the ultimate global variablesRegisters are the ultimate global variables Your proc can simply access information the Your proc can simply access information the
calling program placed in specific registerscalling program placed in specific registers Also a simple way for your proc to send data Also a simple way for your proc to send data
back to the callerback to the caller The previous example used this methodThe previous example used this method
![Page 9: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/9.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 99 of 36 of 36
Passing parametersPassing parameters
Using global memory locationsUsing global memory locations Memory locations declared at the beginning of Memory locations declared at the beginning of
your program are global and can be accessed your program are global and can be accessed from any procedurefrom any procedure
Using a parameter blockUsing a parameter block You may pass a pointer to an array or other You may pass a pointer to an array or other
type of memory block instead of an individual type of memory block instead of an individual data valuedata value
![Page 10: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/10.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 1010 of 36 of 36
Passing parametersPassing parameters
Using the stackUsing the stack Caller pushes all arguments expected by the proc Caller pushes all arguments expected by the proc
onto the stackonto the stack Proc can access these args directly from the Proc can access these args directly from the
stack by setting up the stack by setting up the stack framestack frame..
push bppush bp ; save value of bp; save value of bp
mov bp, spmov bp, sp ; mark start of stack frame; mark start of stack frame
arg1 is at [ss:bp+4] assuming arg1 is at [ss:bp+4] assuming callcall
arg1 is at [ss:bp+6] assuming arg1 is at [ss:bp+6] assuming call farcall far
![Page 11: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/11.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 1111 of 36 of 36
ExampleExample
;call proc to calculate area of right triangle.;call proc to calculate area of right triangle.
;proc expects two word sized args to be on the stack;proc expects two word sized args to be on the stack
push 3push 3
push 4push 4
call TriangleAreacall TriangleArea
;now we must remove the variables from the stack;now we must remove the variables from the stack
;every push must be popped.;every push must be popped.
add sp, 4add sp, 4
; ax now contains 6; ax now contains 6
![Page 12: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/12.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 1212 of 36 of 36
Example continuedExample continued
TriangleAreaTriangleAreapush bppush bpmov bp, spmov bp, spy equ bp+4y equ bp+4 ;[bp+4] = y;[bp+4] = yx equ bp+6x equ bp+6 ;[bp+6] = x;[bp+6] = xpush dxpush dxmov ax, [y]mov ax, [y] ;same as mov ax, [bp+4];same as mov ax, [bp+4]mul word [x]mul word [x] ;same as mul word, [bp+6];same as mul word, [bp+6]shr ax, 1shr ax, 1 ;divide by two;divide by twopop dxpop dxpop bppop bpretret
![Page 13: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/13.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 1313 of 36 of 36
What just happened…What just happened…
E
C
A
8
6
4
2
0
SP
SP
SP
SP
SP
0003h
SS:0000
Saved BP
0004h
Return IP
Push 3Push 3Push 4Push 4Call TriangleAreaCall TriangleArea
TriangleAreaTriangleAreapush bppush bpmov bp, spmov bp, sppush dxpush dxmov ax, [bp+4]mov ax, [bp+4]mul word [bp+6]mul word [bp+6]shr ax, 1shr ax, 1pop dxpop dxpop bppop bpretret
Add sp, 4Add sp, 4
Saved DXSP
Stack fram
e
BP
![Page 14: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/14.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 1414 of 36 of 36
Local variable storageLocal variable storage
You may allocate stack space for use as local You may allocate stack space for use as local variables within proceduresvariables within procedures
Subtract from the stack pointer the number of Subtract from the stack pointer the number of bytes you need to allocate after setting up the bytes you need to allocate after setting up the stack framestack frame
At the end of your procedure, just add the same At the end of your procedure, just add the same amount you subtracted to free the memory you amount you subtracted to free the memory you allocated just before you pop bpallocated just before you pop bp
In the procedure, use the stack frame to address In the procedure, use the stack frame to address local variable storagelocal variable storage
![Page 15: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/15.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 1515 of 36 of 36
Local variable storageLocal variable storage
MyProcMyProc
;setup stack frame;setup stack frame
push bppush bp
mov bp, spmov bp, sp ;allocate space for two words;allocate space for two words
sub sp, 4sub sp, 4 ;access words at [bp-2] and [bp-;access words at [bp-2] and [bp-4]4]
……
add sp, 4add sp, 4 ;destroy local variables;destroy local variables
pop bppop bp ;restore original bp;restore original bp
retret
![Page 16: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/16.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 1616 of 36 of 36
Things to rememberThings to remember
Always make sure that your stack is Always make sure that your stack is consistent (a proc doesn’t leave consistent (a proc doesn’t leave information on the stack that wasn’t there information on the stack that wasn’t there before the procedure ran)before the procedure ran)
Always remember to save registers you Always remember to save registers you modify that don’t contain return valuesmodify that don’t contain return values
![Page 17: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/17.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 1717 of 36 of 36
C style proceduresC style procedures
Assembly procedures that can be called Assembly procedures that can be called by C programsby C programs
Must follow the same calling procedure Must follow the same calling procedure that C compilers use when building C that C compilers use when building C programsprograms
You can also call C functions from You can also call C functions from assembly programs using the same assembly programs using the same protocolprotocol
![Page 18: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/18.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 1818 of 36 of 36
C style proceduresC style procedures
Suppose a C program calls an assembly Suppose a C program calls an assembly procedure as followsprocedure as follows Proc1(a, b, c)Proc1(a, b, c)
Assume each argument is word-sizedAssume each argument is word-sizedFurther, assume the C compiler generates code Further, assume the C compiler generates code to push a, b, and c onto the stackto push a, b, and c onto the stackThe assembly language procedure must be The assembly language procedure must be assembled with the correct ret (near or far) and assembled with the correct ret (near or far) and stack handling of its procedures matching the stack handling of its procedures matching the corresponding values in the high-level modulecorresponding values in the high-level module
![Page 19: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/19.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 1919 of 36 of 36
C style proceduresC style procedures
Assume C program always makes Assume C program always makes far callfar call
So far return (retf) must end the C So far return (retf) must end the C style procedurestyle procedure
Return CS gets pushed onto the stack Return CS gets pushed onto the stack as well as return IPas well as return IP
Makes a difference when accessing Makes a difference when accessing arguments using the stack framearguments using the stack frame
C compilers push arguments in C compilers push arguments in reverse order, from right to left.reverse order, from right to left.
C is pushed first, then B, then AC is pushed first, then B, then A Lowest index from BP corresponds to Lowest index from BP corresponds to
first argumentfirst argument
BP+10
BP+8
BP+6
BP+4
BP+2
BP
c
Return CS
b
a
Return IP
Saved BP
Proc1(a, b, c)
![Page 20: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/20.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 2020 of 36 of 36
C style proceduresC style procedures
If the returned value needs four or fewer bytes, it If the returned value needs four or fewer bytes, it is by default returned in registersis by default returned in registers one or two bytes - returned in AXone or two bytes - returned in AX three or four bytes - returned in AX (low word) and in three or four bytes - returned in AX (low word) and in
DX (high byte or word), (in EAX in 32-bit mode)DX (high byte or word), (in EAX in 32-bit mode)
More than four bytesMore than four bytes the called procedure stores data in some address and the called procedure stores data in some address and
returns the offset and segment parts of that address returns the offset and segment parts of that address in AX and DX, respectivelyin AX and DX, respectively
![Page 21: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/21.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 2121 of 36 of 36
C style proceduresC style procedures
Caller is responsible for clearing the Caller is responsible for clearing the arguments from the stack as soon as it arguments from the stack as soon as it regains control after the callregains control after the call this done by the compiler that generates the this done by the compiler that generates the
appropriate codeappropriate code a far procedure called from C should end with a far procedure called from C should end with
RETF instead of RETRETF instead of RET
![Page 22: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/22.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 2222 of 36 of 36
ExampleExample
Calling and ASM proc from a C program – the proc lets Calling and ASM proc from a C program – the proc lets you display a string at a given row and columnyou display a string at a given row and column
# include <stdio.h># include <stdio.h>extern voidextern void placeStr (char *, unsigned, unsigned); placeStr (char *, unsigned, unsigned);
voidvoid main (void)main (void){{
intint n;n;for (n = 10; n < 20; ++n)for (n = 10; n < 20; ++n) placeStr (“This is the string”, n, 45);placeStr (“This is the string”, n, 45);
}}
![Page 23: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/23.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 2323 of 36 of 36
ExampleExampleGLOBAL _placeStr
SEGMENT code_placeStr; setup stack frame and save
state PUSH BPMOV BP, SPPUSH AXPUSH BXPUSH DX
; get current page - returns in BHMOV AH, 0fhINT 10h
; read unsigned args 2 and 3MOV DL, [BP+10]MOV DH, [BP+8]
;set cursor positionMOV AH, 02hINT 10h
;point to stringMOV BX, [BP+6]
;call outAsc to disp stringcall outAsc
;restore statePOP DXPOP BXPOP AXPOP BP
RETF
![Page 24: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/24.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 2424 of 36 of 36
Putting the two togetherPutting the two together
The C module must be compiledThe C module must be compiled
The assembly language module assembledThe assembly language module assembled
The pair must be linked together into an The pair must be linked together into an executableexecutable
ExternExtern in C is exactly the same as in C is exactly the same as ExternExtern in in assembly programsassembly programs
Notice that the procedure is named _placeStr, Notice that the procedure is named _placeStr, because C compilers preface all external because C compilers preface all external variables with an underscorevariables with an underscore
![Page 25: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/25.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 2525 of 36 of 36
Complete calling procedureComplete calling procedure
Program writes function parameters to stack (C is right-pusher)Program writes function parameters to stack (C is right-pusher) CALL saves program’s return address on the stack [PUSH CS (Far CALL saves program’s return address on the stack [PUSH CS (Far
Proc); PUSH IP]Proc); PUSH IP] Routine marks stack frame (PUSH BP; MOV BP, SP)Routine marks stack frame (PUSH BP; MOV BP, SP) Routine allocates stack memory for local variables (SUB SP, n)Routine allocates stack memory for local variables (SUB SP, n) Routine saves registers it modifies (push SI, push BX, push CX)Routine saves registers it modifies (push SI, push BX, push CX)
Subroutine CodeSubroutine CodeAdditional CALLs, PUSHs, POPs)Additional CALLs, PUSHs, POPs)
Routine restores registers it modifies (pop CX, pop BX, pop SI)Routine restores registers it modifies (pop CX, pop BX, pop SI) Routine deallocates stack memory for local variables (ADD SP, n)Routine deallocates stack memory for local variables (ADD SP, n) Routine restores original value of BP (POP BP)Routine restores original value of BP (POP BP) Subroutine Returns (RETF)Subroutine Returns (RETF)Program clears parameters from stack (ADD SP,p)Program clears parameters from stack (ADD SP,p)
![Page 26: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/26.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 2626 of 36 of 36
RecursionRecursion
Recursion: procedure calls itselfRecursion: procedure calls itselfRecursiveProcRecursiveProc
DECDEC AXAXJZJZ .QuitRecursion.QuitRecursionCALLCALL RecursiveProcRecursiveProc
.QuitRecursion:.QuitRecursion:RETRET
Requires a termination condition in order to stop Requires a termination condition in order to stop infinite recursioninfinite recursionMany recursively implemented algorithms are Many recursively implemented algorithms are more efficient than their iterative counterpartsmore efficient than their iterative counterparts
![Page 27: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/27.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 2727 of 36 of 36
Recursion exampleRecursion example
FactorialFactorial; Input AX = CX = Value; Input AX = CX = Value; Output AX = Value !; Output AX = Value !
DEC CXDEC CX;Test for base case;Test for base caseCMP CX,0CMP CX,0JE .FactDone JE .FactDone IMUL CXIMUL CX; Recurs; RecursCall FactorialCall Factorial
.FactDone:.FactDone:RETRET
Stack contentsAssume:
AX = CX = 4
Return IP Iteration 1CX = 4; AX = 4
Return Iteration IP 2CX = 3; AX = 12
Return Iteration IP 3CX = 2; AX = 24
Return Iteration IP 4CX = 1; AX = 24
![Page 28: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/28.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 2828 of 36 of 36
RecursionRecursion
Recursion must maintain separate copies of all Recursion must maintain separate copies of all pertinent information (parameter value, return pertinent information (parameter value, return address, local variables) for each active calladdress, local variables) for each active call
Recursive routines can consume a considerable Recursive routines can consume a considerable amount of stack spaceamount of stack space
Remember to allocate sufficient memory in your Remember to allocate sufficient memory in your stack segment when using recursionstack segment when using recursion
In general you will not know the depth to which In general you will not know the depth to which recursion will take yourecursion will take you allocate a large block of memory for the stackallocate a large block of memory for the stack
![Page 29: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/29.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 2929 of 36 of 36
MacrosMacros
A macro inserts a block of statements at A macro inserts a block of statements at various points in a program during various points in a program during assemblyassembly
Substitutions made at compile time Substitutions made at compile time NotNot a procedure—code is literally dumped a procedure—code is literally dumped
into the program with each instantiationinto the program with each instantiation Parameter names are substituted Parameter names are substituted Useful for tedious programming tasks Useful for tedious programming tasks
![Page 30: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/30.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 3030 of 36 of 36
MacrosMacros
Generic Format Generic Format %macro MACRO_NAME numargs%macro MACRO_NAME numargs
Your Code ... Your Code ...
... %{1} ... ... %{1} ...
… … %{2} ... %{2} ...
Your Code ... Your Code ...
JMP %%MyLabel JMP %%MyLabel
Your Code ... Your Code ...
%%MyLabel: %%MyLabel:
... %{N} ... ... %{N} ...
Your Code ... Your Code ...
%endmacro %endmacro
![Page 31: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/31.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 3131 of 36 of 36
Local Variables in a MacroLocal Variables in a MacroA local label is one that appears in the macro, but A local label is one that appears in the macro, but is not available outside the macrois not available outside the macro
We use the We use the %%%% prefix for defining a local label prefix for defining a local label If the label If the label MyLabel MyLabel in the previous examplein the previous example is not is not
defined as local, the assembler will flag it with errors on defined as local, the assembler will flag it with errors on the second and subsequent attempts to use the macro the second and subsequent attempts to use the macro because there would be duplicate label namesbecause there would be duplicate label names
Macros can be placed in a separate file Macros can be placed in a separate file use %include directive to include the file with external use %include directive to include the file with external
macro definitions into a programmacro definitions into a program no EXTERN statement is needed to access the macro no EXTERN statement is needed to access the macro
statements that have been includedstatements that have been included
![Page 32: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/32.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 3232 of 36 of 36
MacrosMacros
; Store into ; Store into ResultResult the signed result of the signed result of XX / / YY ; Calculate ; Calculate ResultResult = = XX / / YY ; (all 16-bit signed integers); (all 16-bit signed integers); Destroys Registers AX,DX; Destroys Registers AX,DX
%macro DIV16 3%macro DIV16 3 ; Args: Result, X, Y; Args: Result, X, YMOV AX, %{2} MOV AX, %{2} ; Load AX with Dividend ; Load AX with Dividend CWD CWD ; Extend Sign into DX; Extend Sign into DXIDIV %{3} IDIV %{3} ; Signed Division; Signed DivisionMOV %{1}, AX MOV %{1}, AX ; Store Quotient ; Store Quotient %endmacro%endmacro
![Page 33: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/33.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 3333 of 36 of 36
MacrosMacros; Example: Using the macro in a program; Example: Using the macro in a program; Variable Section; Variable Section
varX1 varX1 DW DW 2020varX2 varX2 DW DW 44varR varR RESWRESW
; Code Section; Code SectionDIV16 word [varR], word [varX1], word [varX2] DIV16 word [varR], word [varX1], word [varX2]
;Will actually generate the following code inline in your ;Will actually generate the following code inline in your program for every instantiation of the DIV16 macro (program for every instantiation of the DIV16 macro (You You won't actually see this unless you debug the programwon't actually see this unless you debug the program).).
MOV AX, word [varX1]MOV AX, word [varX1]CWDCWDIDIV word [varX2]IDIV word [varX2]MOV word [varR], AX MOV word [varR], AX
![Page 34: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/34.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 3434 of 36 of 36
Macros vs. ProceduresMacros vs. Procedures
Proc_1Proc_1MOVMOV AX, 0AX, 0MOVMOV BX, AXBX, AXMOVMOV CX, 5CX, 5RETRET
%macro Macro_1 0%macro Macro_1 0 MOVMOV AX, 0AX, 0 MOVMOV BX, AXBX, AX MOVMOV CX, 5CX, 5
%endmacro%endmacro
CALL Proc_1CALL Proc_1
……
CALL Proc_1CALL Proc_1
……
Macro_1Macro_1
……
Macro_1Macro_1
![Page 35: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/35.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 3535 of 36 of 36
Macros vs. ProceduresMacros vs. ProceduresIn the example the macro and procedure produce the In the example the macro and procedure produce the same resultsame result
The procedure definition generates code in your The procedure definition generates code in your executableexecutable
The macro definition does not produce any codeThe macro definition does not produce any code
Upon encountering Macro_1 in your code, NASM Upon encountering Macro_1 in your code, NASM assembles every statement between the %macro and assembles every statement between the %macro and %endmacro directives for Macro_1 and produces that %endmacro directives for Macro_1 and produces that code in the output filecode in the output file
At run time, the processor executes these instructions At run time, the processor executes these instructions without the call/ret overhead because the instructions without the call/ret overhead because the instructions are themselves inline in your codeare themselves inline in your code
![Page 36: ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.](https://reader036.fdocuments.us/reader036/viewer/2022062409/56649f455503460f94c66774/html5/thumbnails/36.jpg)
ECE 291 Lecture 6ECE 291 Lecture 6
Page Page 3636 of 36 of 36
Macros vs. ProceduresMacros vs. Procedures
Advantage of using macrosAdvantage of using macros execution of macro expansion is faster (no call and execution of macro expansion is faster (no call and
ret) than the execution of the same code implemented ret) than the execution of the same code implemented with procedures with procedures
DisadvantagesDisadvantages assembler copies the macro code into the program at assembler copies the macro code into the program at
each macro invocationeach macro invocation if the number of macro invocations within the program if the number of macro invocations within the program
is large then the program will be much larger than is large then the program will be much larger than when using procedureswhen using procedures