cmp
Compare - 7C 00 00 00
cmp
Instruction Syntax
Mnemonic | Format | Flags |
cmp | crfD,L,rA,rB | - |
cmpw | crfD,rA,rB | L = 0 (extended mnemonic) |
Instruction Encoding
0
1
1
1
1
1
c
c
c
0
0
L
A
A
A
A
B
B
B
B
B
0
0
0
0
0
0
0
0
0
0
0
Field | Bits | Description |
Primary Opcode | 0-5 | 011111 (0x1F) |
crfD | 6-8 | Condition register field |
Reserved | 9-10 | Should be zero |
L | 10 | 64-bit comparison (0 = 32-bit) |
rA | 11-15 | Source register A |
rB | 16-20 | Source register B |
Reserved | 21 | Should be zero |
XO | 22-30 | 0 (Extended opcode) |
Reserved | 31 | Should be zero |
Operation
a ← (rA) b ← (rB) if a < b then c ← 0b100 else if a > b then c ← 0b010 else c ← 0b001 CR[4×crfD+32:4×crfD+35] ← c || XER[SO]
The contents of rA are compared with the contents of rB treating the operands as signed integers. The result of the comparison is placed into condition register field crfD.
Note: In 32-bit implementations, if L=1 the instruction form is invalid.
Affected Registers
Condition Register (crfD field)
(always)
- LT (Less Than) - Set if (rA) < (rB)
- GT (Greater Than) - Set if (rA) > (rB)
- EQ (Equal) - Set if (rA) = (rB)
- SO (Summary Overflow) - Copy of XER[SO]
For more information on condition codes see Section 2.1.3, "Condition Register," in the PowerPC Microprocessor Family: The Programming Environments manual.
Examples
Basic Signed Comparison
cmp cr0, r3, r4 # Compare r3 and r4, set CR0 cmpw cr1, r5, r6 # Compare r5 and r6 (32-bit), set CR1
Conditional Branching After Compare
cmp cr0, r3, r4 # Compare r3 and r4 blt positive # Branch if r3 < r4 beq equal # Branch if r3 = r4 bgt greater # Branch if r3 > r4
Range Checking
# Check if r3 is within range [r4, r5] cmp cr0, r3, r4 # Compare with lower bound blt out_of_range # Branch if below range cmp cr0, r3, r5 # Compare with upper bound bgt out_of_range # Branch if above range # r3 is within range
Multiple Comparison Fields
cmp cr0, r3, r4 # First comparison in CR0 cmp cr1, r5, r6 # Second comparison in CR1 cmp cr2, r7, r8 # Third comparison in CR2 # Use different CR fields for different conditions
Array Bounds Checking
# Check array index bounds li r4, 0 # Lower bound (0) cmp cr0, r3, r4 # Compare index with 0 blt bounds_error # Branch if index < 0 li r5, 100 # Upper bound (array size) cmp cr0, r3, r5 # Compare with array size bge bounds_error # Branch if index >= size