Author Topic: Converting to Cortex M0 ASM  (Read 16917 times)

0 Members and 1 Guest are viewing this topic.

Offline ali_asadzadehTopic starter

  • Super Contributor
  • ***
  • Posts: 2155
  • Country: ca
Converting to Cortex M0 ASM
« on: June 18, 2022, 12:37:35 pm »
Hi,
I want to do this Saturation math in Cortex M0 ASM language to get maximum speed ( and I have very little experience in ASM for ARM Cortex M), it's from this topic,
https://www.eevblog.com/forum/microcontrollers/mp3-decoding-on-stm32g070rbt6/


The code is fine for Cortex M3 upwards, But I need a help to reimplement it for M0.

Code: [Select]
static __inline__ __attribute__((always_inline)) int32_t minimp3_clip_int16_arm(int32_t a)
{
    int32_t x = 0;
    __asm__ ("ssat %0, #16, %1" : "=r"(x) : "r"(a));
    return x;
}
ASiDesigner, Stands for Application specific intelligent devices
I'm a Digital Expert from 8-bits to 64-bits
 

Offline Silenos

  • Regular Contributor
  • *
  • Posts: 85
  • Country: pl
  • Fumbling in ignorance
Re: Converting to Cortex M0 ASM
« Reply #1 on: June 18, 2022, 12:54:22 pm »
No saturation instructions in M0, write it yourself in C.
 

Offline ali_asadzadehTopic starter

  • Super Contributor
  • ***
  • Posts: 2155
  • Country: ca
Re: Converting to Cortex M0 ASM
« Reply #2 on: June 18, 2022, 01:22:39 pm »
I know that, So I wanted a clever fast way of doing it in M0
ASiDesigner, Stands for Application specific intelligent devices
I'm a Digital Expert from 8-bits to 64-bits
 

Offline voltsandjolts

  • Supporter
  • ****
  • Posts: 3952
  • Country: gb
Re: Converting to Cortex M0 ASM
« Reply #3 on: June 18, 2022, 02:03:05 pm »
If you write it in C, what does the assembly listing look like for that?
 
The following users thanked this post: eugene

Offline eugene

  • Frequent Contributor
  • **
  • Posts: 602
  • Country: us
Re: Converting to Cortex M0 ASM
« Reply #4 on: June 18, 2022, 02:17:49 pm »
I'm not even close to expert in assembly, and know almost nothing about Cortex assembly. Having said that, most of what I do know about assembly I learned by studying the output of C compilers. In the rare cases that I felt a need to use asm over C for performance reasons, I started with C and optimized the compiler output.
90% of quoted statistics are fictional
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 6464
  • Country: nz
Re: Converting to Cortex M0 ASM
« Reply #5 on: June 18, 2022, 02:24:09 pm »
I know that, So I wanted a clever fast way of doing it in M0

M0 doesn't do clever.

Code: [Select]
int ssat(int n, int sat){
  int max = 1<<sat;
  if (n < -max)
    n = -max;
  else if (n >= max)
    n = max-1;
  return n;
}

You probably can't do better on M0.
 
The following users thanked this post: ali_asadzadeh

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 8354
  • Country: fi
    • My home page and email address
Re: Converting to Cortex M0 ASM
« Reply #6 on: June 18, 2022, 02:54:59 pm »
The straightforward C implementation,
Code: [Select]
#include <stdint.h>

int_fast16_t int16_clip(int_fast32_t v)
{
    return (v < -32768) ? -32768 :
           (v >  32767) ?  32767 : v;
}
using gcc -Os -march=armv6-m -mtune=cortex-m0 compiles to
Code: [Select]
int16_clip:
  movs  r3, #128
  lsls  r3, r3, #8
  cmp   r0, r3
  blt  .L2
  ldr   r0, .L4
.L2:
  ldr   r3, .L4+4
  cmp   r0, r3
  bge  .L3
  movs  r0, r3
.L3:
  bx    lr
.L4:
  .word  32767
  .word -32768
which seems to be acceptable to me on Cortex-M0.  I am not aware of any tricks related to saturating signed integer math; there are some for saturating unsigned integer math, though, but experimenting with Compiler Explorer indicates that it won't help here – the complexity is greater than above if one first branches depending on the sign, and then does unsigned integer saturation in each branch.
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 6464
  • Country: nz
Re: Converting to Cortex M0 ASM
« Reply #7 on: June 18, 2022, 03:08:34 pm »
which seems to be acceptable to me on Cortex-M0

It's pretty horrid that its loading the result values from memory instead of reusing the values it already has.

I think mine compiles to better code...

https://godbolt.org/z/voqEsGbqe

There's only ever one taken branch, and no memory operations.
 

Offline Jeroen3

  • Super Contributor
  • ***
  • Posts: 4665
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: Converting to Cortex M0 ASM
« Reply #8 on: June 18, 2022, 04:07:37 pm »
« Last Edit: June 18, 2022, 04:11:51 pm by Jeroen3 »
 

Offline hans

  • Super Contributor
  • ***
  • Posts: 2001
  • Country: 00
Re: Converting to Cortex M0 ASM
« Reply #9 on: June 18, 2022, 07:06:46 pm »
That library code looks absolutely horrible. Why the for-loop with multiply-by-2 when you could use an arithmetic shift?

Anyhow, I don't think you can do better than the code from bruce. The m0 is quite a simple CPU, and there isn't anything simpler than an if-else bounds check.
 

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 8354
  • Country: fi
    • My home page and email address
Re: Converting to Cortex M0 ASM
« Reply #10 on: June 18, 2022, 08:23:06 pm »
which seems to be acceptable to me on Cortex-M0

It's pretty horrid that its loading the result values from memory instead of reusing the values it already has.

I think mine compiles to better code...
I agree, although the difference is lost whenever one supplies a compile-time constant sat: https://godbolt.org/z/rvY7bdrcn.

I looked at the Cortex-M0 Instruction Set, and remembered that while it does not have any conditional assignment operators, it does have 16-to-32-bit sign extension instruction (sxth).  This means that ((int32_t)n != (int32_t)(int16_t)n) gets compiled to a pair of instructions, one to sign-extend the parameter, and the other to compare the two; and this comparison is only true if the value does not fit in a signed 16-bit integer.  In other words, https://godbolt.org/z/cYWdPf3zb:
Code: [Select]
#include <stdint.h>

int_fast16_t saturate16(int_fast32_t v)
{
    if ((int32_t)v == (int32_t)(int16_t)v)
        return v;

    const int_fast16_t  m = 32768;  // constexpr int_fast16_t  m = 32768; for C++
    if (v > 0)
        return m-1;
    else
        return -m;
}
which compiles (gcc -Os -mcpu=cortex-m0 -mfloat-abi=soft) to
Code: [Select]
saturate16(int):
        sxth    r3, r0
        cmp     r3, r0
        beq     .L5
        asrs    r3, r0, #31
        subs    r3, r3, r0
        asrs    r3, r3, #31
        uxth    r0, r3
        ldr     r3, .L7
        adds    r0, r0, r3
.L5:
        bx      lr
.L7:
        .word   -32768
Whether this is faster than brucehoults, I dunno; but I do expect it to be in practice.



Edited:  It looks like
Code: [Select]
#include <stdint.h>

static inline int_fast16_t u32767(void)
{
    return 32767;
}

int_fast16_t saturate16(int_fast32_t v)
{
    if ((int32_t)v == (int32_t)(int16_t)v)
        return v;
    else
        return (int16_t)((v >= 0) - 1) ^ u32767();
}
is even faster, as it compiles to (assuming zero wait states, according to ARM Cortex-M0 Technical Reference)
Code: [Select]
saturate16:
        sxth    r3, r0      ; 1 cycle
        cmp     r3, r0      ; 1 cycle
        beq     .L2         ; 2 cycles if taken, 1 cycle if not taken
        ldr     r3, .L3     ; 2 cycles
        asrs    r0, r0, #31 ; 1 cycle
        eors    r0, r3      ; 1 cycle
.L2:
        bx      lr
.L3:
        .word   32767
taking 4 cycles if the value is within int16_t range, and 7 cycles if clamped; but it does get into the obfuscated C code territory...

I did verify it works, of course. (The expression (int16_t)((v >= 0) - 1) evaluates to 0xFFFF if v is negative, and to 0x0000 otherwise.  Exclusive-OR that with 32767, and you'll get 0x8000 = -32768 if v is negative, and 0x7FFF = 32767 otherwise.)

If you want to avoid the memory load, you can replace the constant with inline assembly, e.g.
Code: [Select]
static inline int_fast16_t u32767(void)
{
    int_fast16_t  value;
    asm volatile ( "mov\t%0, #128\n\t"
                   "lsl\t%0, #8\n\t"
                   "sub\t%0, #1\n\t"
                 : "=r" (value));
    return value;
}
in which case you replace the 2-cycle memory load (slower, if you have wait states when running code from e.g. Flash) with three single-cycle instructions, and end up with
Code: [Select]
saturate16(int):
        sxth    r3, r0       ; 1 cycle
        cmp     r3, r0       ; 1 cycle
        beq     .L2          ; 2 cycles if taken, 1 if not taken
        mov     r3, #128     ; 1 cycle
        lsl     r3, #8       ; 1 cycle
        sub     r3, #1       ; 1 cycle
        asrs    r0, r0, #31  ; 1 cycle
        eors    r0, r3       ; 1 cycle
.L2:
        bx      lr
which has no memory accesses and only dirties one register, takes 4 cycles for valid values and 8 cycles for clamped values, when inlined (i.e., ignoring function call overhead).
« Last Edit: June 18, 2022, 11:03:32 pm by Nominal Animal »
 

Offline abyrvalg

  • Frequent Contributor
  • **
  • Posts: 898
  • Country: es
Re: Converting to Cortex M0 ASM
« Reply #11 on: June 18, 2022, 09:34:39 pm »
Code: [Select]
saturate16:
    ASRS R1, R0, #16 ; test if high 16 bits are 0, keeping the sign bit
    BEQ   exit ; are 0 -> return the value
    BMI   ret_min ; are not 0 and value is negative -> return -32768
    ; are not 0 and value is positive -> return 32767
    MOVS R0, #0
    MVNS R0, R0 ; FFFFFFFF
    LSRS R0, #17 ; 7FFF
    BX   LR
ret_min:
    MOVS R0, #1
    LSLS  R0, #15
exit:
    BX LR
Perhaps the 7FFF value generation could be shortened with some better trick
 

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 8354
  • Country: fi
    • My home page and email address
Re: Converting to Cortex M0 ASM
« Reply #12 on: June 19, 2022, 02:23:16 am »
Code: [Select]
saturate16:
    ASRS R1, R0, #16 ; test if high 16 bits are 0, keeping the sign bit
    BEQ   exit ; are 0 -> return the value
    BMI   ret_min ; are not 0 and value is negative -> return -32768
    ; are not 0 and value is positive -> return 32767
    MOVS R0, #0
    MVNS R0, R0 ; FFFFFFFF
    LSRS R0, #17 ; 7FFF
    BX   LR
ret_min:
    MOVS R0, #1
    LSLS  R0, #15
exit:
    BX LR
Perhaps the 7FFF value generation could be shortened with some better trick
Did you check it?  Given R0 = 0xFFFF8888 = -30548, after ASRS R1, R0, #16 we'll have R1=0xFFFFFFFF, Z=0, and N=1, so the BEQ branch is not taken, but the BMI is (because N=1), and your function will return 0x00008000 = -32768 as int16_t; while it should return either 0x8888 (int16_t on Cortex-M0) or 0xFFFF8888 (int_fast16_t and int on Cortex-M0).  Unless I'm interpreting the code wrong, of course.
 

Offline abyrvalg

  • Frequent Contributor
  • **
  • Posts: 898
  • Country: es
Re: Converting to Cortex M0 ASM
« Reply #13 on: June 19, 2022, 08:32:39 am »
You are right, my bad :palm:
 

Offline ali_asadzadehTopic starter

  • Super Contributor
  • ***
  • Posts: 2155
  • Country: ca
Re: Converting to Cortex M0 ASM
« Reply #14 on: June 19, 2022, 09:42:46 am »
Thanks guys for the feedback! ;)
ASiDesigner, Stands for Application specific intelligent devices
I'm a Digital Expert from 8-bits to 64-bits
 

Offline ali_asadzadehTopic starter

  • Super Contributor
  • ***
  • Posts: 2155
  • Country: ca
Re: Converting to Cortex M0 ASM
« Reply #15 on: June 19, 2022, 01:21:49 pm »
I have used it on a simulation project in Keil, decoding a 320K sin wave MP3 file, it's working, and I have used keil states counter in simulation to count the clock cycles for decoding one frame, the results shown that it would impact performance around 1% for M3 and around 5.5% on M4, But surprisingly the decoder would use more clock's for a M7 part, if Keil state counter is working properly!

Check several frame decode times!
Clock" border="0
Keil" border="0
 
ASiDesigner, Stands for Application specific intelligent devices
I'm a Digital Expert from 8-bits to 64-bits
 

Offline Jeroen3

  • Super Contributor
  • ***
  • Posts: 4665
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: Converting to Cortex M0 ASM
« Reply #16 on: June 19, 2022, 02:44:23 pm »
You really have to be careful with these kinds of functions. Especially copied randomly from the internets. The off-by-ones are everywhere.
For example, bruces example doesn't do saturations of negatives given n=31. Instead, it will always output 2147483647.

It's really best to stay with what tested code from libraries in my opinion. It also maintains portability accross the platform.
The old "I can do better" is the best waste of time in the life of the programmer.

Why the for-loop with multiply-by-2 when you could use an arithmetic shift?
Good question...
 

Offline SiliconWizard

  • Super Contributor
  • ***
  • Posts: 17872
  • Country: fr
Re: Converting to Cortex M0 ASM
« Reply #17 on: June 19, 2022, 06:59:13 pm »
Bruce's suggested function yields pretty much an "optimal" solution for RISC-V, incidentally. And as always (and as you can see from the link below), keep in mind modern optimizing compilers will pretty much compile this kind of functions as though they were macros as long as they are in the same compilation unit, inlining them and simplifying them if you pass constants. (And no, the 'inline' qualifier is not required here, it won't make a difference.)

https://godbolt.org/z/a3W3EMx7E

The only "weird" thing from the output of GCC here is the last 'li a0,-32768'. Why not just 'mv a0, a5' ? Since the immediate is wider than 12 bits, the 'li' will yield two instructions instead of just one for the 'mv' solution. If Bruce has any idea why GCC emits that...
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 6464
  • Country: nz
Re: Converting to Cortex M0 ASM
« Reply #18 on: June 19, 2022, 09:21:22 pm »
You really have to be careful with these kinds of functions. Especially copied randomly from the internets. The off-by-ones are everywhere.
For example, bruces example doesn't do saturations of negatives given n=31. Instead, it will always output 2147483647.

For n>=31 the 1<<n overflows, obviously. To negative for n==31 and to 0 for n>31. It's intended for smaller n, and if I was being paid to put this in a library or program it would be documented as such. And have an assert on n. And if the spec said it has to work for n or 31 and 32 then it would have bigger and slower code.

The OP wanted code for n==16.
 

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 8354
  • Country: fi
    • My home page and email address
Re: Converting to Cortex M0 ASM
« Reply #19 on: June 19, 2022, 09:25:43 pm »
Bruce's suggested function yields pretty much an "optimal" solution for RISC-V, incidentally.
Mine compiles to
Code: [Select]
saturate16(int):
    slli  a5, a0, 16
    srai  a5, a5, 16
    beq   a5, a0, .L2
    li    a5, 32768
    srai  a0, a0, 31
    addi  a5, a5, -1
    xor   a0, a0, a5
.L2:
    ret
which is shorter in the common case, input within the allowed range (two instructions and a taken jump, as opposed to two instructions and two taken jumps in Bruce's version), but longer in the clamping case (albeit with just one load of a 16-bit immediate instead of three).

However, I would not like to maintain code that had something like my function (or worse, the equivalent conditional expression, ((int32_t)v==(int32_t)(int16_t)v)?v:(int16_t)((v>=0)-1)^32767) without a good long comment and an alternate version in an #ifndef .. #else .. #endif for verification and testing.  Now, I *have* verified the expression yields the correct result for all 32-bit integers v, so technically it should not need maintenance... but if the clamping limits ever change, mine has to be completely rewritten from scratch.  I'm not sure I like it, but if one is counting cycles already, perhaps it is warranted, perhaps not.

The only "weird" thing from the output of GCC here is the last 'li a0,-32768'. Why not just 'mv a0, a5' ? Since the immediate is wider than 12 bits, the 'li' will yield two instructions instead of just one for the 'mv' solution. If Bruce has any idea why GCC emits that...
The code generated is
Code: [Select]
ssat_16(int):
    li   a5, 32768
    blt  a0, a5, .L7
    addi a0, a5, -1
.L7:
    li   a5, -32768
    bge  a0, a5, .L8
    li   a0, -32768
.L8:
    ret
but it could be better: the first li a5, -32768 could be simply neg a5, a5, and the second mv a0, a5.

This looks to me like a failure to effectively reuse existing register state, something that is kinda-sorta a weak point in GCC; it is known for producing superfluous register moves (especially in earlier versions on register-starved architectures like x86) in similar snippets of code on other architectures, too.
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 6464
  • Country: nz
Re: Converting to Cortex M0 ASM
« Reply #20 on: June 19, 2022, 09:36:37 pm »
The only "weird" thing from the output of GCC here is the last 'li a0,-32768'. Why not just 'mv a0, a5' ? Since the immediate is wider than 12 bits, the 'li' will yield two instructions instead of just one for the 'mv' solution. If Bruce has any idea why GCC emits that...

No one knows the ways of gcc.  And especially not on such a small scale of ±1 instruction, given that optimisation decisions are made using heuristics, not by trying every possible way.

It's entirely possible gcc doesn't know that "li" can expand to more than 1 instruction and just leaves it to the assembler. It doesn't know the C extension exists. Still, you'd think "reuse rather than rematerialise" would be a good heuristic even when the "reload" is a constant.

Clang makes a similar decision here, but the value it generates more than once is +32768, which is a single "lui" (which it shows as such)
 

Offline SiliconWizard

  • Super Contributor
  • ***
  • Posts: 17872
  • Country: fr
Re: Converting to Cortex M0 ASM
« Reply #21 on: June 19, 2022, 09:46:57 pm »
The only "weird" thing from the output of GCC here is the last 'li a0,-32768'. Why not just 'mv a0, a5' ? Since the immediate is wider than 12 bits, the 'li' will yield two instructions instead of just one for the 'mv' solution. If Bruce has any idea why GCC emits that...

No one knows the ways of gcc.

OK. ;D
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 6464
  • Country: nz
Re: Converting to Cortex M0 ASM
« Reply #22 on: June 19, 2022, 09:55:03 pm »
Bruce's suggested function yields pretty much an "optimal" solution for RISC-V, incidentally.
Mine compiles to
Code: [Select]
saturate16(int):
    slli  a5, a0, 16
    srai  a5, a5, 16
    beq   a5, a0, .L2
    li    a5, 32768
    srai  a0, a0, 31
    addi  a5, a5, -1
    xor   a0, a0, a5
.L2:
    ret
which is shorter in the common case, input within the allowed range (two instructions and a taken jump, as opposed to two instructions and two taken jumps in Bruce's version), but longer in the clamping case (albeit with just one load of a 16-bit immediate instead of three).

Yeah, it's a good idea to see if sign-extending keeps the same value.

The slli/srai will work for any number of bits, not only 16 like the ARM sxth instruction (or 8 for sxtb), but it's not a portable thing in C, unlike casting to short and back to int.

Or is casting an out of range int to short undefined too?


If you really care about an instruction plus or minus then you should probably study your CPU and write it in assembly language. Except that puts you between the rock of calling the assembly language function (more overhead than just running 1 or 2 instructions more than optimal in an inline C function) and the hard place of writing a 10 instruction sequence using the inline assembler which is (I think) more than you should do that way.
 

Offline SiliconWizard

  • Super Contributor
  • ***
  • Posts: 17872
  • Country: fr
Re: Converting to Cortex M0 ASM
« Reply #23 on: June 19, 2022, 10:14:42 pm »
If you're going the assembly way, you better write bigger chunks of code than just the saturation function anyway, to get the full benefit of assembly. IMHO.
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 6464
  • Country: nz
Re: Converting to Cortex M0 ASM
« Reply #24 on: June 19, 2022, 11:24:04 pm »
If you're going the assembly way, you better write bigger chunks of code than just the saturation function anyway, to get the full benefit of assembly. IMHO.

Yes and no. If it was super performance-critical then you'd just use a CM3 instead of CM0 anyway -- or you're selling bazillions of them and should be making your own chip to minimise BoM count.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf

 

- - -
-->