0

I'm using an LC3 microarchitecture simulator to write assembly code. I've only been writing assembly for about three weeks, so I am still very new.

My goal is to print all the numbers leading up to a set value, so for example, if the user selects '6' the console prints 012345

My code works, but the unit test says my code is inefficient or has an infinite loop.

I set the value by manually setting R1 in my simulator to any value, the rest is automated with the code. Starting at 0x3000

LD, R0, X3001 ;Load R0 with 0
0 ;I did this b/c I don't know how to load a register with ascii values
AND R2, R2, #0 ; Set R2=0
NOT R3, R1 ;invert R1, store in R3
ADD R3, R3, #1 ;Add 1 to R3, now R3=-R1
ADD R4, R0, R3 ; better way to perform loop? added these to maintain loop
BRz X300b ; if previous math ever produces 0, skip to halt
OUT ; print single char
ADD R0, R0, #1 ; R0++
ADD R1, R1 #-1 ; R1--
BRnzp X3006 ;Always branch back to the above BR instruction
HALT 

Hex:

3000
2000
0030
54a0
967f
16e1
1803
0404
f021
1021
127f
0ffb
f025

So my question is, is there any way to make this more efficient?

  • You should post your question in [StackExchange](https://codereview.stackexchange.com/) – Jeroen Heier Feb 09 '18 at 04:59
  • Alright thanks, didn't realize that would be a better location. Thanks for the suggestion! – shiftybits Feb 09 '18 at 05:21
  • Does your code even print anything when you run it normally? What instruction does `0` represent in the machine code? Keep in mind that as well as loading it, you're executing that CPU word as an instruction. Does your code have an *infinite* loop, or is it just slightly too slow? – Peter Cordes Feb 09 '18 at 06:07
  • I mean it's obviously not efficient (normal for beginner code), but `out` should still dominate the run time unless the simulator pretends it's as cheap as a `BR` or even and `ADD`. You could [optimize the loop to a `do{}while` structure](https://stackoverflow.com/questions/47783926/why-are-loops-always-compiled-like-this) so there's only a normally-taken conditional branch at the bottom, but you still need 2 ALU instructions, either 2 ADD or ADD/CMP if LC3 has a CMP, inside the loop, because you to print ASCII digits so that register doesn't end at integer `0`. – Peter Cordes Feb 09 '18 at 06:11
  • Can the initial value of R1 be 0? That is the only possible way I can see that code infinitely looping. – Brandon Feb 09 '18 at 07:48
  • Brandon, that was the problem. I did not notice that 0 would create an infinite loop. All I had to do was add R1 and R2 since R2 was already 0, and if the result was 0 or negative I branch to HALT. Thank you for the help! – shiftybits Feb 09 '18 at 17:44

0 Answers0