< previous page page_34 next page >

Page 34
d87111c01013bcda00bb8640fdff6754.gif
entry: LD.W R1, xCounter     ;get x size from memory
       LD.W R2, xBaseAddress ;get the base value
       LD.W R3, #0           ;initialize sum to 0
loop:  ADD.W R3, [R2]        ;add next element
                             ;in memory to sum
       ADD.W R2, #wordSize   ;point to next element
       SUB.W R1, #1          ;decrement length counter
                             ;and check for end of
       BC.NE loop            ;and continue until done
       ST.W xSumAddress, R3  ;now write out the sum
       END
There are several details to note about the preceding example. First, the instructions are all in two-operand format. Thus, the ADD.W R3, [R2] instruction is equivalent to ADD. W R3, 0[R2]the "0" is understood to be the offset if not specified. This in turn is equivalent to R3= R3 + [R2]. Secondly, the instruction ADD. W R2, #wordSize must manually specify the increment, as the processor does not know the actual word size pointed to by the register, In fact, it does not even know that the value contained in the register is really an address. Finally, we could easily have dropped the .W from the OP since the use of 32-bit words is understood.
A variation of the preceding program using an L/S machine might look like this:
d87111c01013bcda00bb8640fdff6754.gif
entry: LD.W  R1, xCounter        ;get x size from memory
       LD.W  R2, xBaseAddress    ;and get the basevalue
       LD.W  R3, #0              ;initialize sum to 0
loop:  LD.W  R4, [R2]            ;get next word from memory
       ADD.W R3, R3, R4          ;add next element to sum
       ADD.W R2, R2, #wordSize   ;point to next element
       SUB.W R1, R1, #1          ;decrement length counter
                                  and check next for end of list
       BC.NE loop, R1            ;and continue until done
       ST.W xSumAddress, R3      ;now write out the sum
       END
Several points should be noted about this example. First, all operands are three-operand format, with the exception of memory references. Second, there is no dedicated compare instructionthe comparison is actually a simple test of the register contents for "O", and indicated in the condition code. Some machines (such as a VAX) would rewrite the two instructions to add the element and increment the pointer into one instruction such as ADD. W R3, [R2++], which automatically increments the address by one data unit (in this case, one word size). The advantage of this is that it combines two instructions, saving memory and cache space. The entire program could have been rewritten much more succinctly on an R+M machine. Taking advantage of the features of a complex instruction set, consider the following code:

 
< previous page page_34 next page >