SPARC Assembly/Control Structures

If you're familiar with any higher level programming language (C, C++, Java, etc.), then you are likely aware of the tremendous capabilities that control structures afford computer programmers. Control structures allow us to have our programs make decisions about which code block to execute, and possibly even how many times to execute that block of code. Though somewhat more cryptic, control structures in SPARC afford us the same capabilities. We will discuss a few of the more common ones below.

If Then
As you might have guessed from the section on branching, an if-then structure is comprised simply of a branch statement that skips the code in the "if" block and branches to a label the marks the beginning of the code to be executed after the if block. For example, if in psuedocode our goal is to have a program that looks like

then the SPARC version of this would be

Note that we have negated the logic of the if statement from "if %l0 is less than zero, then do this" to "if %l0 is not greater than zero, then do not do this". This is necessary because our ability to create control structures to comes from our ability to skip portions of code. So what we are telling the computer is that if this condition is not true, then skip all of this code here and move on the next set of labeled instructions.

If Else
This is similar to the if-then structure but requires more branching. The basic point of if-else is to do the following:

So, if we want to do this in SPARC, we branch to the "else" part just like we would to the "next" label in the if-then code. However, we also need to ensure that if the 'if' block is executed, then the 'else' block is skipped when after th 'if' block finishes executing. So for sake of example, lets say that in the previous example we wanted to set %l0 to zero if the condition was not satisfied. The code is as follows:

Notice now that when the 'if' condition is false we now move to the 'else' statement instead of 'next'. Also notice that we now have a 'branch always' instruction at the end of the if block that allows us to skip the 'else' block when the 'if' block has been executed.