XCORE SDK
XCORE Software Development Kit
xs3_util.h
1 // Copyright 2020-2021 XMOS LIMITED.
2 // This Software is subject to the terms of the XMOS Public Licence: Version 1.
3 
4 #pragma once
5 
6 #include "xs3_math_types.h"
7 
8 #include <stdio.h>
9 #include <assert.h>
10 #include <math.h>
11 
40 #define MAX(A,B) (((A) >= (B))? (A) : (B))
41 
42 
55 #define MIN(A,B) (((A) <= (B))? (A) : (B))
56 
57 
67 #define CLS_S16(X) (cls(X) - 16)
68 
69 
79 #define CLS_S32(X) (cls(X))
80 
81 
91 #define CLS_S64(X) ( (cls((int32_t)(((int64_t)(X))>>32)) == 32)? \
92  (cls((int32_t)(((int64_t)(X))>>16)) == 32)? 32 + cls((int32_t)(X)) \
93  : 16 + cls((int32_t)(((int64_t)(X))>>16)) \
94  : cls((int32_t)(((int64_t)(X))>>32)) )
95 
96 
109 #define CLS_C16(X) (MIN(CLS_S16((X).re), CLS_S16((X).im)))
110 
123 #define CLS_C32(X) (MIN(CLS_S32(((int32_t)(X).re)), CLS_S32(((int32_t)(X).im))))
124 
125 
135 #define HR_S64(X) (CLS_S64(X)-1)
136 
146 #define HR_S32(X) (CLS_S32(X)-1)
147 
157 #define HR_S16(X) (CLS_S16(((int16_t)X))-1)
158 
171 #define HR_C32(X) (CLS_C32(X)-1)
172 
185 #define HR_C16(X) (CLS_C16(X)-1)
186 
187 
198 void xs3_memcpy(
199  void* dst,
200  const void* src,
201  unsigned bytes);
202 
203 
217 static inline unsigned cls(
218  const int32_t a)
219 {
220 #ifdef __XS3A__
221 
222  unsigned res;
223  asm( "cls %0, %1" : "=r"(res) : "r"(a) );
224  return res;
225 
226 #else
227 
228  if(a == 0 || a == -1)
229  return 32;
230 
231  if( a > 0 ){
232  for(int i = 30; i >= 0; i--){
233  if(a & (1<<i)) return 31-i;
234  }
235  } else {
236  for(int i = 30; i >= 0; i--){
237  unsigned mask = (1<<i);
238  if((a | mask) != a) return 31-i;
239  }
240  }
241  assert(0);
242  return 0;
243 
244 #endif //__XS3A__
245 }
246 
247 
248 
249 static inline unsigned n_bitrev(
250  const unsigned index,
251  const unsigned bits)
252 {
253  unsigned rev_index = 0;
254 #ifdef __xcore__
255 
256  const unsigned shifted_index = index << (32 - bits);
257  asm( "bitrev %0, %1" : "=r"(rev_index) : "r"(shifted_index) );
258 
259 #else
260  unsigned dex = index;
261 
262  for(int i = 0; i < bits; i++, dex >>= 1){
263  rev_index = ((rev_index<<1) | (dex & 0x1));
264  }
265  return rev_index;
266 #endif
267 
268 
269  return rev_index;
270 }