Speculative: Rust for base system components

Brian Neal brian at aceshardware.com
Sun Jan 6 16:54:23 UTC 2019


I don't have it anymore, but yours is close enough.  When compiling your 
first example, I get 156 instructions, including map iterators and rust 
result assert/unwrap logic.  Your second example produces 21 lines, 
including a loop iterator:

rustc 1.31.0 with -C opt-level=s:

<I as core::iter::traits::IntoIterator>::into_iter:
         mov     eax, edi
         mov     edx, esi
         ret
example::oddcount2:
         xor     eax, eax
         test    edi, edi
         jle     .LBB1_3
         xor     ecx, ecx
.LBB1_2:
         mov     edx, ecx
         and     edx, 1
         neg     edx
         and     edx, ecx
         lea     esi, [rcx + 1]
         add     eax, edx
         mov     ecx, esi
         cmp     edi, esi
         jne     .LBB1_2
.LBB1_3:
         ret

Converting to C:

int oddcount2(int num) {
     int sum = 0;
     for (int i = 0; i <= num; ++i)
     {
         if (i % 2 > 0)
         {
             sum += i;
         }
     }
     return sum;
}

I get the following with gcc 8.2 using -Os:

oddcount2(int):
         xor     edx, edx
         xor     eax, eax
.L4:
         cmp     edx, edi
         jg      .L1
         test    dl, 1
         je      .L3
         add     eax, edx
.L3:
         inc     edx
         jmp     .L4
.L1:
         ret

Cheers,

-Brian

On 1/6/2019 8:01 AM, Alan Somers wrote:
> I get different results on Godbolt.  I don't know exactly what your
> program was, but I tried to recreate it from your description.  I
> wrote it in two ways.  With opt-level=s, I got 13 instructions for one
> version, and 16 for the other.  With opt-level=3, I got vectorized
> code for both.  Here's my code:
> 
> pub fn oddcount(num: i32) -> i32 {
>      (0..num).map(|i| {
>          if i % 2 > 0 {
>              i
>          } else {
>              0
>          }
>      }).sum()
> }
> 
> pub fn oddcount2(num: i32) -> i32 {
>      let mut sum = 0;
>      for i in 0..num {
>          if i % 2 > 0 {
>              sum += i;
>          }
>      }
>      sum
> }
> 
> -Alan
> _______________________________________________
> freebsd-hackers at freebsd.org mailing list
> https://lists.freebsd.org/mailman/listinfo/freebsd-hackers
> To unsubscribe, send any mail to "freebsd-hackers-unsubscribe at freebsd.org"
> 


More information about the freebsd-hackers mailing list