We already briefly touched the conditions’ topic while discussing the CPSR register. We use conditions for controlling the program’s flow during it’s runtime usually by making jumps (branches) or executing some instruction only when a condition is met. The condition is described as the state of a specific bit in the CPSR register. Those bits change from time to time based on the outcome of some instructions. For example, when we compare two numbers and they turn out to be equal, we trigger the Zero bit (Z = 1), because under the hood the following happens: a – b = 0. In this case we have equal condition. If the first number was bigger, we would have a GreaterThan condition and in the opposite case –LowerThan. There are more conditions, like Lower orEqual (LE),Greater orEqual (GE) and so on.
The following table lists the available condition codes, their meanings, and the status of the flags that are tested.
下表列出了可能的条件指令,他们的含义以及被检测的状态标志位
We can use the following piece of code to look into a practical use case of conditions where we perform conditional addition.
我们使用如下代码来实现条件相加指令:
The first CMP instruction in the code above triggers Negative bit to be set (2 – 3 = -1) indicating that the value in r0 is Lower Than number 3. Subsequently, the ADDLT instruction is executed because LT condition is full filled when V != N (values of overflow and negative bits in the CPSR are different). Before we execute second CMP, our r0 = 3. That’s why second CMP clears out Negative bit (because 3 – 3 = 0, no need to set the negative flag) and sets theZero flag (Z = 1). Now we have V = 0 and N = 0 which results in LT condition to fail. As a result, the second ADDLT is not executed and r0 remains unmodified. The program exits with the result 3.
代码中,第一个CMP比较指令执行后触发了N标志位的置位(2-3=-1),这表明r0的值比数字3要小。随后,由于LT条件满足, 即V != N(在CPSR里溢出标志位和负标志位不是同一个),所以执行了addlt指令。由于第二个cmp指令将N标志位清空(因为3-3=0,不需要置位N标志位),将零标志位置位(Z=0),现在
V = 0且 N = 0,从而导致LT条件不成立,结果就是第二个addlt没有执行,r0也没改变,程序退出并返回结果3
In the Instruction Set chapter we talked about the fact that there are different Thumb versions. Specifically, the Thumb version which allows conditional execution (Thumb-2). Some ARM processor versions support the “IT” instruction that allows up to 4 instructions to be executed conditionally in Thumb state.