; ARM assembly tutorial for Asmonite, example 14: conditions and IT blocks (Raspberry Pi Pico 2, Arm Cortex-M33).
; Adapted from the ARM-ASM-Tutorial by Niklas Guertler (section "Conditional Execution"); see LICENSE.txt.
;
; "cmp" sets the flags N, Z, C, V; a branch with a condition (beq, bne, blo, bge ...) looks at them. In
; Thumb-2 a few instructions after "it" (if-then) are carried out only if a condition holds: "ite ge"
; = if greater or equal then the next instruction, else the one after it. The conditions of the
; instructions in the block must match the IT ("movge", then "movlt": the opposite).
; Step through with F7 and watch r0 .. r3 and the flags in the register view.
.target pico2
.arch thumb
.imagebase 0x20000000

_start:
    movs r0, #7
    movs r1, #12
    bl   max                    ; r0 = max(7, 12) = 12
    mov  r2, r0

    mvn  r0, #4                 ; r0 = -5 (mvn: all bits inverted, ~4 = -5)
    bl   abs                    ; r0 = 5
    mov  r3, r0

    movs r0, #200
    bl   clamp100               ; r0 = 100
    b    $

; ---- r0 = max(r0, r1), signed ----
max:
    cmp  r0, r1
    it   lt
    movlt r0, r1                ; only if r0 < r1
    bx   lr

; ---- r0 = |r0| ----
abs:
    cmp  r0, #0
    it   lt
    rsblt r0, r0, #0            ; r0 = 0 - r0, only if r0 < 0
    bx   lr

; ---- r0 = r0 if it is below 100, else 100 (unsigned); "ite": then and else ----
clamp100:
    cmp  r0, #100
    ite  hs
    movhs r0, #100              ; r0 >= 100 (unsigned: hs = higher or same)
    addlo r0, r0, #0            ; else: keep r0 (the else part of the example)
    bx   lr
