The Machine Code
Now that we have the BASICs out of the way, we can get down to the microcode or the machine code portion of our program. It is not my intention to provide an introductory lesson in 68000 assembly language programming with this article. However, I do intend to cover QL specific instructions (i.e., Traps and Vectors). There are a number of books available to teach the basic instruction set of the 68000 family of chips. One series of books is available from Motorola for a very reasonable charge.
Before I get started with our discussion of the various supporting machine code programs, a short disclaimer. This program was my first attempt at coding in 68K code. Experienced programmers will find some awkward and round-about approaches in the code.
MANDELBROT SOURCE CODE
start
One of the important things to remember, when writing machine code for the QL, is that the Register D0 must contain the value of 0 for a successful return to BASIC. The QL uses this register to provide for error traps and reports when returning from Trap or Vector calls. Any value, other than 0 in D0, is seen by the ROM as an error when returning to BASIC, or concluding a Trap/Vector call. See pages 19-20 of the Concepts section of the QL User’s Guide for a breakdown of the Error Report Codes. D0 will contain a negative value for an official error (i.e., -1 = not complete; -2 = invalid job,; etc.). The first routine in our source code, start, simply locates and stores the location of the array data area to be used by the machine code program.
calc
Our next section is one of the round-about methods I warned you about. Its role is to retrieve, from BASIC, certain floating point values needed for the reiterative calculations. The straight-forward approach would be to obtain these values from within the machine code program, using an input from keyboard routine. Even so, some valuable lessons can be learned from this section of code. In the QL, the SuperBASIC memory area is dynamic. It can grow or shrink and move about within memory. For this reason, the A6 register is used to point to the base address of this area. Any particular location in this area, including SuperBASIC system variables or the BASIC program, is referenced relative to A6. Each area of this memory is indexed by two pointers, for the start and the end. These “stacks” are upside down. The SuperBASIC system variables start at offset $00. (Note: I will be using “$” to indicate numbers in HEX.) Each procedure, function, and variable created from within SuperBASIC is indexed via a name table and a name list. Their starting addresses are found in the SuperBASIC system variables area. Their offsets are $18 (BV.NTBAS) and $20 (BV.NLBAS) respectively–both long words. Their ending addresses are found at offsets $1C (BV.NTP) and $24 (BV.NLP).
The Name Table is composed of blocks of eight bytes. This block contains information on the type, a pointer to the location in Name List, and a pointer to the value. See Table 1 for a complete breakdown of this information.
Let’s now look at the calc routine of the code. The comments accompanying the first few lines of this routine are misleading. The result of move.l $1c9a6),a1 does not retrieve the actual address, only the offset from A6. By adding A6 to A1, the actual ending address of the table is found. Since the SuperBASIC variables we wish to pass to the machine code program are floating point, we are looking in the Name Table for the occurence of “$0202” (see Table 1). The actual names are stored in the Name List with one byte for the length of the name, followed by the ASCII of the name. Checks are made through the Name Table for floating point variables. If one is found, its entry in the Name List is calculated and a check for either c1 or c2 is carried out. By declaring the machine code variable space as a long word of 0 and by transferring the data from the Name List into the first 3 bytes of space, we can make a long word check against D1 and D2 (see section labeled flpoint). The Name List is not arranged in a normal 68000 manner. It is customary, in 68K assembly language, to insure that all addresses be on word boundaries (i.e., even addresses). When found, the addresses of the actual floating point values are stored in their appropriate machine code spots.
Floating point variables are stored in the QL with six bytes (a 16-bit exponent with a 32-bit mantissa). Integers are stored as two’s-complemented words. The QL stores strings with the first word defining the length of the string, followed by the actual string itself. If the string is an odd number of bytes long, it will be stored with a spare byte to adhere to the normal 68K convention of word boundary addresses. Array storage is rather complex. There is one long word as a relative pointer to the actual start of data. This is followed by a word for the number of dimensions. For each dimension, a pair of words is used which define the dimension along with an index multiplier for it. This preamble is followed by the actual array, using the same format as stated above for integer, floating point, or string.
set_up
The first portion of this section moves the actual floating point data from the SuperBASIC variable area into our machine code variable area. We are now ready for our first voyage into the QL ROM via Vector utilities–floating point math.
Before any calculations are carried out, a check for ample space on the maths stack should be performed. This is accomplished by the Vector utility $11A (BV.CHRIX – reserve space on maths stack). Upon entry, D1 should contain the number of bytes needed (as a long word). When exited, the following registers are effected:
D1 corrupted A0 preserved
D2 corrupted A1 preserved
D3 corrupted A2 preserved
A3 preserved
If there is insufficient space on the stack, this Vector call will expand it. This may entail moving the stack’s location. The location of the stack is found by checking the SuperBASIC variable BV.RIP, which has the offset from A6 of $58.
bigloop
Floating point routines, within the QL ROM, are accessed by two different Vectors, RI.EXEC – $11C for one operation and RI.EXECB – $11E for a list of operations. Upon entry, the following registers should be set up as follows:
D0.W operation code (RI.EXEC only) D7.L set to 0 to insure reliable execution A1.L pointer to maths stack (relative to A6) A3.L pointer to the list of operations (RI.EXECB only) A4.L pointer to base of variable area (relative to A6)
The following registers are affected by the call:
D1 preserved A0 preserved
D2 preserved A1 updated pointer to maths stack
D3 preserved A2 preserved
A3 preserved
A4 preserved
An error report -18 in D0 will indicate an arithmetic overflow.
See Table 2 for the various math functions available. All results of the math operations will be found on the top of the stack. RI.DUP (duplicate) is the only exception, in that it will increase the stack by one item and update the stack pointer leaving two items on the stack. The first four remove the first item on the stack and replace it with the result. The next four (along with RI.POWFP) take both items on the stack and replace them with one item and thus decrease the size of the stack. The remaining functions will remove the top item on the stack and replace it with the result. To use the RI.EXECB (list of operations), A3 should point to the list of bytes (opcodes). This list must end with $00.
All of the math operations carried out by this portion of the code have only two items on the stack, though room was reserved for 4 floating point numbers. This allows us to leave certain items on the stack and by changing the stack pointer, carry out another operation. Finally, this new result can be combined with other items left on the stack for further math operations. This saves the need of pulling items off the stack, storing and retrieving them when needed later. Scan the code between bigloop and check and see if you can trace this manipulation of the maths stack. (Refer to the first article in this series to see a BASIC version of the calculations being carried out by this portion of the code.)
The remainder of the Madelbrot Source Code should be fairly self explanatory.
SNAPSHOT SOURCE CODE
IMPORTANT NOTE: There is a major error in both the source code and the BASIC loader (Listing 4, TDM Nov/Dec ’87) for the Snapshot machine code routine. A “typo” reversed two numbers in the source code. In the source code, lines labeled snapshot and paste should read 131086 not 131068. In the BASIC Listing (see lines 1000 and 1020) “8828,1,-4,16890” should read 8828,2,14,16890. My apologies to all who could not de-bug this careless error.
This is a straight-forward piece of code. It reads a group of bytes form a certian section of the screen’s memory map and stores them in a variable area contained in the machine code program. My approach to accomplish this was rather amateurish, but quick and dirty. To find the actual starting point for the upper left-hand corner of the mini-window area, I POKE’d numbers into the screen’s memory until I found the exact point. the screen’s memory starts at $20000 or 131072d and is a total of 32K long. The actual screen grid is 128 bytes wide and 256 bytes high. The mini-window is 24 bytes wide and 36 bytes high. The window starts 14 bytes from the start of the screen and is 24 bytes wide. By adding 80 to the last address of the window’s scan line, we will be exactly 1 line below the start of the previous location (or a total of 128 bytes). The paste routine reverses this process by moving the copy of the mini-window area back to the screen.
PLOTTER SOURCE CODE
start
This machine code module contains two separate routines. One, start, plots the mandelbrot map from already compiled data. The other one, plot, draws the map while it is being calculated. The first section of code (start, m_loop and n_loop) run through the already calculated data, setting the proper ink color and plotting each point to the screen. Let’s examine the various subroutines used by both routines.
convert
This subroutine is a maths operation executed by calling the RI.EXEC Vector previously discussed. Before we can plot a point to the screen, the x and y coordinates must be in floating point forms.
ink
The color attributes for any window can be set by calling one of three Trap #3 routines. They are:
SD.SETPA --- D0=$27 --- paper color
SD.SETST --- D0=$28 --- strip color
SD.SETIN --- D0=$29 --- ink color
Upon entry, the following registers need to be set
accordingly:
D1.B color
D3.W timeout (-1)
A0.L channel ID
Upon returning, the following registers are affected:
D1 preserved A0 preserved
D2 preserved A1 corrupted
D3 preserved A2 preserved
Errors: -1 not complete or -6 invalid channel ID
Channel ID’s in machine code are not quite the same as Channel #’s in SuperBASIC. The Channel Table contains pointers to channel definition blocks within the common heap (or $FF000000 if the channel is closed). The channel ID consists of two words. The low word is a reference to its location in the Channel Table and the high word is the tag number. Every time a channel is opened, its tag number will be one greater than the previously opened channel. When the QL is fired up, 3 default channels are open. $00000000 is SuperBASIC channel #0 (the lower window), $00010001 is SuperBASIC channel #1 (the print window), $00020002 is SuperBASIC channel #2 (the list window). No matter what the SuperBASIC channel # is for the next channel opened (i.e., #32), it will almost certainly have the channel ID of $00030003. The Mandelbrot program uses the default window #2 to display the mandelbrot map, making calculations of the channel ID a snap.
This section of code uses the color data POKEd into memory by the SuperBASIC program (lines 2830 and 4250). The distance point from the mandelbrot set (1 to 255) is used as an index pointer to the appropriate color in this table.
plot
Graphic routines from within machine code are also accessed through Trap #3 functions:
SD.POINT --- D0=$30 --- plot a point SD.LINE --- D0=$31 --- draw a line SD.ARC --- D0=$32 --- draw an arc SD.ELIPS --- D0=$33 --- draw a circle or elipse SD.SCALE --- D0=$34 --- define scale and origin SD.GCUR ---D0=$36 --- define text cursor position Upon entry, the following registers must be prepared: D3.W timeout (-1) A0.L channel ID A1.L maths stack pointer Upon exit, the following registers are affected: D1 corrupted A0 preserved D2 preserved A1 corrupted
Each of the functions require that certain parameters (floating point form) be placed on a maths stack pointed to by A1. This stack is also upside down. To insure successful operations of the functions, there should be 240 bytes free on the stack. See Table 3 for the parameters which must be on the stack (relative to A1) for each of the graphic routines.
start2
Unlike the routine at start, this routine only plots one point at a time, updating the machine code variables for the x and y coordinates before returning to BASIC. It also uses the same subroutines detailed above.
Some of the variables used by this code may have been POKEd into their location from SuperBASIC (array, m_point, n_point and color). This is another round-about method of passing parameters from SuperBASIC to machine code.
I hope this article will be a start for the aspiring 68000 machine codists. There is a great potential lurking in the heart and soul of the QL, and most of it is easily accessible via machine code. I feel that 68K machine code is much more flexible and dynamic than Z80. (Now, now, if any of you Z80 fans have gotten this far, don’t count me as an ex-Z80 buff. One will still find me hacking away at the ole Silver Avenger–TS2068!!) With the availability of a large number of Traps and Vectors, much of the chore of coding in assembly language has been removed. Once again, I would like to apologize to any who may have lost a few nights sleep due to the error in the Snapshot code.
Due to the length of the source code listing of Michael Carver’s Mandelbrot machine code subroutine, this listing will be included next issue, when this series concludes. — editor
Bibliography:
Denning, Adam Advanced QL machine code. Duckworth, 1985.
Gandoff, Martin Machine code programming on the Sinclair QL. Hutchinson, 1985.
Kane, Gerry 68000 microprocessor handbook. Osborne/McGraw Hill, 1986.
King, Tim Progamming the 68000. Addison-Wesley, 1985.
Krantz, Donald 68000 assembly language; techniques for building programs. Addison-Wesley, 1986.
M68000; 8-/16-/32-bit microprocessors programmer’s reference manual. Prentice-Hall, 1986. (Available from Motorola — check your yellow pages for a representative.)
Pennell, Andrew The Sinclair QDOS companion; a guide to the QL operating system. Sunshine, 1985.
Williams, Steve Programming the 68000. Sybex, 1985.
TABLE 1 -- Variable types
word defines the type of the name
$0001 undefined string variable
$0002 undefined floating point number
$0003 undefined integer
$0101 string expression
$0102 floating point expression
$0103 integer expression
$0201 string variable
$0202 floating point number
$0203 integer
$0300 substring (used internally only)
$0301 string array
$0302 floating point array
$0303 integer array
$0400 SuperBASIC procedure
$0501 SuperBASIC string function
$0502 SuperBASIC floating point function
$0503 SuperBASIC integer function
$0602 REPeat loop name
$0702 FOR loop counter (floating point)
$0800 machine code procedure
$0900 machine code function
word pointer to entry in name list (or -1 if expression)
long pointer to value (For variables this is an offset into
the variable area, or if undefined, a negative number).
For SuperBASIC procedures and functions, the high word
is the line number of the DEF statement. For machine
code functions and definitions, the long word is the
absolute address of the routine.
TABLE 2 -- Floating Point functions OPCODE NAME FUNCTION $02 RI.NINT INT floating point into word integer $04 RI.INT truncate floating point into word integer $06 RI.NLINT INT floating point form into long integer $08 RI.LINT convert integer into floating point $0A RI.ADD add TOS to NOS $0C RI.SUB subract TOS from NOS $0E RI.MULT multiply TOS by NOS $10 RI.DIV divide TOS into NOS $12 RI.ABS take absolute value $14 RI.NEG negate $16 RI.DUP duplicate $18 RI.COS cosine $1A RI.SIN sine $1C RI.TAN tangent $1E RI.COT cotangent $20 RI.ASIN arcsine $22 RI.ACOS arcosine $24 RI.ATAN arctangent $26 RI.ACOT arcotangent $28 RI.SQRT square root $2A RI.LN natural logs $2C RI.LOG10 base 10 logs $2E RI.EXP exponential $30 RI.POWFP take NOS ^ TOS
TABLE 3 -- Graphic function parameters
SD.POINT $00(A1) y co-ord
$06(A1) x co-ord
SD.LINE $00(A1) y co-ord of end of line
$06(A1) x co-ord of end of line
$0C(A1) y co-ord of start of line
$12(A1) x co-ord of start of line
SD.ARC $00(A1) angle of the arc
$06(A1) y co-ord of end of arc
$0C(A1) x co-ord of end of arc
$12(A1) y co-ord of start of arc
$18(A1) x co-ord of start of arc
SD.ELIPSE $00(A1) angle of rotation
$06(A1) radius
$0C(A1) eccentricity (1 if a circle)
$12(A1) y co-ord of center
$18(A1) x co-ord of center
SD.SCALE $00(A1) x position of graphics origin
$06(A1) y poistion of graphics origin
$0C(A1) scale factor
SD.GCUR $00(A1) graphics x co-ord
$06(A1) graphics y co-ord
$0C(A1) horiz. pixel offset of cursor
$12(A1) vert. pixel offset of cursor