1 /*
2  * Copyright 2018 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #ifndef SkRasterPipeline_opts_DEFINED
9 #define SkRasterPipeline_opts_DEFINED
10 
11 #include "SkTypes.h"
12 
13 // Every function in this file should be marked static and inline using SI.
14 #if defined(__clang__)
15     #define SI __attribute__((always_inline)) static inline
16 #else
17     #define SI static inline
18 #endif
19 
20 
21 template <typename T, typename P>
unaligned_load(const P * p)22 SI T unaligned_load(const P* p) {  // const void* would work too, but const P* helps ARMv7 codegen.
23     T v;
24     memcpy(&v, p, sizeof(v));
25     return v;
26 }
27 
28 template <typename T, typename P>
unaligned_store(P * p,T v)29 SI void unaligned_store(P* p, T v) {
30     memcpy(p, &v, sizeof(v));
31 }
32 
33 template <typename Dst, typename Src>
bit_cast(const Src & src)34 SI Dst bit_cast(const Src& src) {
35     static_assert(sizeof(Dst) == sizeof(Src), "");
36     return unaligned_load<Dst>(&src);
37 }
38 
39 template <typename Dst, typename Src>
widen_cast(const Src & src)40 SI Dst widen_cast(const Src& src) {
41     static_assert(sizeof(Dst) > sizeof(Src), "");
42     Dst dst;
43     memcpy(&dst, &src, sizeof(Src));
44     return dst;
45 }
46 
47 // Our program is an array of void*, either
48 //   - 1 void* per stage with no context pointer, the next stage;
49 //   - 2 void* per stage with a context pointer, first the context pointer, then the next stage.
50 
51 // load_and_inc() steps the program forward by 1 void*, returning that pointer.
load_and_inc(void ** & program)52 SI void* load_and_inc(void**& program) {
53 #if defined(__GNUC__) && defined(__x86_64__)
54     // If program is in %rsi (we try to make this likely) then this is a single instruction.
55     void* rax;
56     asm("lodsq" : "=a"(rax), "+S"(program));  // Write-only %rax, read-write %rsi.
57     return rax;
58 #else
59     // On ARM *program++ compiles into pretty ideal code without any handholding.
60     return *program++;
61 #endif
62 }
63 
64 // Lazily resolved on first cast.  Does nothing if cast to Ctx::None.
65 struct Ctx {
66     struct None {};
67 
68     void*   ptr;
69     void**& program;
70 
CtxCtx71     explicit Ctx(void**& p) : ptr(nullptr), program(p) {}
72 
73     template <typename T>
74     operator T*() {
75         if (!ptr) { ptr = load_and_inc(program); }
76         return (T*)ptr;
77     }
NoneCtx78     operator None() { return None{}; }
79 };
80 
81 
82 #if !defined(__clang__)
83     #define JUMPER_IS_SCALAR
84 #elif defined(SK_ARM_HAS_NEON)
85     #define JUMPER_IS_NEON
86 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_AVX512
87     #define JUMPER_IS_AVX512
88 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_AVX2
89     #define JUMPER_IS_HSW
90 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_AVX
91     #define JUMPER_IS_AVX
92 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE41
93     #define JUMPER_IS_SSE41
94 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE2
95     #define JUMPER_IS_SSE2
96 #else
97     #define JUMPER_IS_SCALAR
98 #endif
99 
100 // Older Clangs seem to crash when generating non-optimized NEON code for ARMv7.
101 #if defined(__clang__) && !defined(__OPTIMIZE__) && defined(SK_CPU_ARM32)
102     // Apple Clang 9 and vanilla Clang 5 are fine, and may even be conservative.
103     #if defined(__apple_build_version__) && __clang_major__ < 9
104         #define JUMPER_IS_SCALAR
105     #elif __clang_major__ < 5
106         #define JUMPER_IS_SCALAR
107     #endif
108 
109     #if defined(JUMPER_IS_NEON) && defined(JUMPER_IS_SCALAR)
110         #undef  JUMPER_IS_NEON
111     #endif
112 #endif
113 
114 #if defined(JUMPER_IS_SCALAR)
115     #include <math.h>
116 #elif defined(JUMPER_IS_NEON)
117     #include <arm_neon.h>
118 #else
119     #include <immintrin.h>
120 #endif
121 
122 namespace SK_OPTS_NS {
123 
124 #if defined(JUMPER_IS_SCALAR)
125     // This path should lead to portable scalar code.
126     using F   = float   ;
127     using I32 =  int32_t;
128     using U64 = uint64_t;
129     using U32 = uint32_t;
130     using U16 = uint16_t;
131     using U8  = uint8_t ;
132 
mad(F f,F m,F a)133     SI F   mad(F f, F m, F a)   { return f*m+a; }
min(F a,F b)134     SI F   min(F a, F b)        { return fminf(a,b); }
max(F a,F b)135     SI F   max(F a, F b)        { return fmaxf(a,b); }
abs_(F v)136     SI F   abs_  (F v)          { return fabsf(v); }
floor_(F v)137     SI F   floor_(F v)          { return floorf(v); }
rcp(F v)138     SI F   rcp   (F v)          { return 1.0f / v; }
rsqrt(F v)139     SI F   rsqrt (F v)          { return 1.0f / sqrtf(v); }
sqrt_(F v)140     SI F    sqrt_(F v)          { return sqrtf(v); }
round(F v,F scale)141     SI U32 round (F v, F scale) { return (uint32_t)(v*scale + 0.5f); }
pack(U32 v)142     SI U16 pack(U32 v)          { return (U16)v; }
pack(U16 v)143     SI U8  pack(U16 v)          { return  (U8)v; }
144 
if_then_else(I32 c,F t,F e)145     SI F if_then_else(I32 c, F t, F e) { return c ? t : e; }
146 
147     template <typename T>
gather(const T * p,U32 ix)148     SI T gather(const T* p, U32 ix) { return p[ix]; }
149 
load3(const uint16_t * ptr,size_t tail,U16 * r,U16 * g,U16 * b)150     SI void load3(const uint16_t* ptr, size_t tail, U16* r, U16* g, U16* b) {
151         *r = ptr[0];
152         *g = ptr[1];
153         *b = ptr[2];
154     }
load4(const uint16_t * ptr,size_t tail,U16 * r,U16 * g,U16 * b,U16 * a)155     SI void load4(const uint16_t* ptr, size_t tail, U16* r, U16* g, U16* b, U16* a) {
156         *r = ptr[0];
157         *g = ptr[1];
158         *b = ptr[2];
159         *a = ptr[3];
160     }
store4(uint16_t * ptr,size_t tail,U16 r,U16 g,U16 b,U16 a)161     SI void store4(uint16_t* ptr, size_t tail, U16 r, U16 g, U16 b, U16 a) {
162         ptr[0] = r;
163         ptr[1] = g;
164         ptr[2] = b;
165         ptr[3] = a;
166     }
167 
load4(const float * ptr,size_t tail,F * r,F * g,F * b,F * a)168     SI void load4(const float* ptr, size_t tail, F* r, F* g, F* b, F* a) {
169         *r = ptr[0];
170         *g = ptr[1];
171         *b = ptr[2];
172         *a = ptr[3];
173     }
store4(float * ptr,size_t tail,F r,F g,F b,F a)174     SI void store4(float* ptr, size_t tail, F r, F g, F b, F a) {
175         ptr[0] = r;
176         ptr[1] = g;
177         ptr[2] = b;
178         ptr[3] = a;
179     }
180 
181 #elif defined(JUMPER_IS_NEON)
182     // Since we know we're using Clang, we can use its vector extensions.
183     template <typename T> using V = T __attribute__((ext_vector_type(4)));
184     using F   = V<float   >;
185     using I32 = V< int32_t>;
186     using U64 = V<uint64_t>;
187     using U32 = V<uint32_t>;
188     using U16 = V<uint16_t>;
189     using U8  = V<uint8_t >;
190 
191     // We polyfill a few routines that Clang doesn't build into ext_vector_types.
192     SI F   min(F a, F b)                         { return vminq_f32(a,b);          }
193     SI F   max(F a, F b)                         { return vmaxq_f32(a,b);          }
194     SI F   abs_  (F v)                           { return vabsq_f32(v);            }
195     SI F   rcp   (F v) { auto e = vrecpeq_f32 (v); return vrecpsq_f32 (v,e  ) * e; }
196     SI F   rsqrt (F v) { auto e = vrsqrteq_f32(v); return vrsqrtsq_f32(v,e*e) * e; }
197     SI U16 pack(U32 v)                           { return __builtin_convertvector(v, U16); }
198     SI U8  pack(U16 v)                           { return __builtin_convertvector(v,  U8); }
199 
200     SI F if_then_else(I32 c, F t, F e) { return vbslq_f32((U32)c,t,e); }
201 
202     #if defined(SK_CPU_ARM64)
203         SI F     mad(F f, F m, F a) { return vfmaq_f32(a,f,m); }
204         SI F  floor_(F v) { return vrndmq_f32(v); }
205         SI F   sqrt_(F v) { return vsqrtq_f32(v); }
206         SI U32 round(F v, F scale) { return vcvtnq_u32_f32(v*scale); }
207     #else
208         SI F mad(F f, F m, F a) { return vmlaq_f32(a,f,m); }
209         SI F floor_(F v) {
210             F roundtrip = vcvtq_f32_s32(vcvtq_s32_f32(v));
211             return roundtrip - if_then_else(roundtrip > v, 1, 0);
212         }
213 
214         SI F sqrt_(F v) {
215             auto e = vrsqrteq_f32(v);  // Estimate and two refinement steps for e = rsqrt(v).
216             e *= vrsqrtsq_f32(v,e*e);
217             e *= vrsqrtsq_f32(v,e*e);
218             return v*e;                // sqrt(v) == v*rsqrt(v).
219         }
220 
221         SI U32 round(F v, F scale) {
222             return vcvtq_u32_f32(mad(v,scale,0.5f));
223         }
224     #endif
225 
226 
227     template <typename T>
228     SI V<T> gather(const T* p, U32 ix) {
229         return {p[ix[0]], p[ix[1]], p[ix[2]], p[ix[3]]};
230     }
231 
232     SI void load3(const uint16_t* ptr, size_t tail, U16* r, U16* g, U16* b) {
233         uint16x4x3_t rgb;
234         if (__builtin_expect(tail,0)) {
235             if (  true  ) { rgb = vld3_lane_u16(ptr + 0, rgb, 0); }
236             if (tail > 1) { rgb = vld3_lane_u16(ptr + 3, rgb, 1); }
237             if (tail > 2) { rgb = vld3_lane_u16(ptr + 6, rgb, 2); }
238         } else {
239             rgb = vld3_u16(ptr);
240         }
241         *r = rgb.val[0];
242         *g = rgb.val[1];
243         *b = rgb.val[2];
244     }
245     SI void load4(const uint16_t* ptr, size_t tail, U16* r, U16* g, U16* b, U16* a) {
246         uint16x4x4_t rgba;
247         if (__builtin_expect(tail,0)) {
248             if (  true  ) { rgba = vld4_lane_u16(ptr + 0, rgba, 0); }
249             if (tail > 1) { rgba = vld4_lane_u16(ptr + 4, rgba, 1); }
250             if (tail > 2) { rgba = vld4_lane_u16(ptr + 8, rgba, 2); }
251         } else {
252             rgba = vld4_u16(ptr);
253         }
254         *r = rgba.val[0];
255         *g = rgba.val[1];
256         *b = rgba.val[2];
257         *a = rgba.val[3];
258     }
259     SI void store4(uint16_t* ptr, size_t tail, U16 r, U16 g, U16 b, U16 a) {
260         if (__builtin_expect(tail,0)) {
261             if (  true  ) { vst4_lane_u16(ptr + 0, (uint16x4x4_t{{r,g,b,a}}), 0); }
262             if (tail > 1) { vst4_lane_u16(ptr + 4, (uint16x4x4_t{{r,g,b,a}}), 1); }
263             if (tail > 2) { vst4_lane_u16(ptr + 8, (uint16x4x4_t{{r,g,b,a}}), 2); }
264         } else {
265             vst4_u16(ptr, (uint16x4x4_t{{r,g,b,a}}));
266         }
267     }
268     SI void load4(const float* ptr, size_t tail, F* r, F* g, F* b, F* a) {
269         float32x4x4_t rgba;
270         if (__builtin_expect(tail,0)) {
271             if (  true  ) { rgba = vld4q_lane_f32(ptr + 0, rgba, 0); }
272             if (tail > 1) { rgba = vld4q_lane_f32(ptr + 4, rgba, 1); }
273             if (tail > 2) { rgba = vld4q_lane_f32(ptr + 8, rgba, 2); }
274         } else {
275             rgba = vld4q_f32(ptr);
276         }
277         *r = rgba.val[0];
278         *g = rgba.val[1];
279         *b = rgba.val[2];
280         *a = rgba.val[3];
281     }
282     SI void store4(float* ptr, size_t tail, F r, F g, F b, F a) {
283         if (__builtin_expect(tail,0)) {
284             if (  true  ) { vst4q_lane_f32(ptr + 0, (float32x4x4_t{{r,g,b,a}}), 0); }
285             if (tail > 1) { vst4q_lane_f32(ptr + 4, (float32x4x4_t{{r,g,b,a}}), 1); }
286             if (tail > 2) { vst4q_lane_f32(ptr + 8, (float32x4x4_t{{r,g,b,a}}), 2); }
287         } else {
288             vst4q_f32(ptr, (float32x4x4_t{{r,g,b,a}}));
289         }
290     }
291 
292 #elif defined(JUMPER_IS_AVX) || defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
293     // These are __m256 and __m256i, but friendlier and strongly-typed.
294     template <typename T> using V = T __attribute__((ext_vector_type(8)));
295     using F   = V<float   >;
296     using I32 = V< int32_t>;
297     using U64 = V<uint64_t>;
298     using U32 = V<uint32_t>;
299     using U16 = V<uint16_t>;
300     using U8  = V<uint8_t >;
301 
302     SI F mad(F f, F m, F a)  {
303     #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
304         return _mm256_fmadd_ps(f,m,a);
305     #else
306         return f*m+a;
307     #endif
308     }
309 
310     SI F   min(F a, F b)        { return _mm256_min_ps(a,b);    }
311     SI F   max(F a, F b)        { return _mm256_max_ps(a,b);    }
312     SI F   abs_  (F v)          { return _mm256_and_ps(v, 0-v); }
313     SI F   floor_(F v)          { return _mm256_floor_ps(v);    }
314     SI F   rcp   (F v)          { return _mm256_rcp_ps  (v);    }
315     SI F   rsqrt (F v)          { return _mm256_rsqrt_ps(v);    }
316     SI F    sqrt_(F v)          { return _mm256_sqrt_ps (v);    }
317     SI U32 round (F v, F scale) { return _mm256_cvtps_epi32(v*scale); }
318 
319     SI U16 pack(U32 v) {
320         return _mm_packus_epi32(_mm256_extractf128_si256(v, 0),
321                                 _mm256_extractf128_si256(v, 1));
322     }
323     SI U8 pack(U16 v) {
324         auto r = _mm_packus_epi16(v,v);
325         return unaligned_load<U8>(&r);
326     }
327 
328     SI F if_then_else(I32 c, F t, F e) { return _mm256_blendv_ps(e,t,c); }
329 
330     template <typename T>
331     SI V<T> gather(const T* p, U32 ix) {
332         return { p[ix[0]], p[ix[1]], p[ix[2]], p[ix[3]],
333                  p[ix[4]], p[ix[5]], p[ix[6]], p[ix[7]], };
334     }
335     #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
336         SI F   gather(const float*    p, U32 ix) { return _mm256_i32gather_ps   (p, ix, 4); }
337         SI U32 gather(const uint32_t* p, U32 ix) { return _mm256_i32gather_epi32(p, ix, 4); }
338         SI U64 gather(const uint64_t* p, U32 ix) {
339             __m256i parts[] = {
340                 _mm256_i32gather_epi64(p, _mm256_extracti128_si256(ix,0), 8),
341                 _mm256_i32gather_epi64(p, _mm256_extracti128_si256(ix,1), 8),
342             };
343             return bit_cast<U64>(parts);
344         }
345     #endif
346 
347     SI void load3(const uint16_t* ptr, size_t tail, U16* r, U16* g, U16* b) {
348         __m128i _0,_1,_2,_3,_4,_5,_6,_7;
349         if (__builtin_expect(tail,0)) {
350             auto load_rgb = [](const uint16_t* src) {
351                 auto v = _mm_cvtsi32_si128(*(const uint32_t*)src);
352                 return _mm_insert_epi16(v, src[2], 2);
353             };
354             _1 = _2 = _3 = _4 = _5 = _6 = _7 = _mm_setzero_si128();
355             if (  true  ) { _0 = load_rgb(ptr +  0); }
356             if (tail > 1) { _1 = load_rgb(ptr +  3); }
357             if (tail > 2) { _2 = load_rgb(ptr +  6); }
358             if (tail > 3) { _3 = load_rgb(ptr +  9); }
359             if (tail > 4) { _4 = load_rgb(ptr + 12); }
360             if (tail > 5) { _5 = load_rgb(ptr + 15); }
361             if (tail > 6) { _6 = load_rgb(ptr + 18); }
362         } else {
363             // Load 0+1, 2+3, 4+5 normally, and 6+7 backed up 4 bytes so we don't run over.
364             auto _01 =                _mm_loadu_si128((const __m128i*)(ptr +  0))    ;
365             auto _23 =                _mm_loadu_si128((const __m128i*)(ptr +  6))    ;
366             auto _45 =                _mm_loadu_si128((const __m128i*)(ptr + 12))    ;
367             auto _67 = _mm_srli_si128(_mm_loadu_si128((const __m128i*)(ptr + 16)), 4);
368             _0 = _01; _1 = _mm_srli_si128(_01, 6);
369             _2 = _23; _3 = _mm_srli_si128(_23, 6);
370             _4 = _45; _5 = _mm_srli_si128(_45, 6);
371             _6 = _67; _7 = _mm_srli_si128(_67, 6);
372         }
373 
374         auto _02 = _mm_unpacklo_epi16(_0, _2),  // r0 r2 g0 g2 b0 b2 xx xx
375              _13 = _mm_unpacklo_epi16(_1, _3),
376              _46 = _mm_unpacklo_epi16(_4, _6),
377              _57 = _mm_unpacklo_epi16(_5, _7);
378 
379         auto rg0123 = _mm_unpacklo_epi16(_02, _13),  // r0 r1 r2 r3 g0 g1 g2 g3
380              bx0123 = _mm_unpackhi_epi16(_02, _13),  // b0 b1 b2 b3 xx xx xx xx
381              rg4567 = _mm_unpacklo_epi16(_46, _57),
382              bx4567 = _mm_unpackhi_epi16(_46, _57);
383 
384         *r = _mm_unpacklo_epi64(rg0123, rg4567);
385         *g = _mm_unpackhi_epi64(rg0123, rg4567);
386         *b = _mm_unpacklo_epi64(bx0123, bx4567);
387     }
388     SI void load4(const uint16_t* ptr, size_t tail, U16* r, U16* g, U16* b, U16* a) {
389         __m128i _01, _23, _45, _67;
390         if (__builtin_expect(tail,0)) {
391             auto src = (const double*)ptr;
392             _01 = _23 = _45 = _67 = _mm_setzero_si128();
393             if (tail > 0) { _01 = _mm_loadl_pd(_01, src+0); }
394             if (tail > 1) { _01 = _mm_loadh_pd(_01, src+1); }
395             if (tail > 2) { _23 = _mm_loadl_pd(_23, src+2); }
396             if (tail > 3) { _23 = _mm_loadh_pd(_23, src+3); }
397             if (tail > 4) { _45 = _mm_loadl_pd(_45, src+4); }
398             if (tail > 5) { _45 = _mm_loadh_pd(_45, src+5); }
399             if (tail > 6) { _67 = _mm_loadl_pd(_67, src+6); }
400         } else {
401             _01 = _mm_loadu_si128(((__m128i*)ptr) + 0);
402             _23 = _mm_loadu_si128(((__m128i*)ptr) + 1);
403             _45 = _mm_loadu_si128(((__m128i*)ptr) + 2);
404             _67 = _mm_loadu_si128(((__m128i*)ptr) + 3);
405         }
406 
407         auto _02 = _mm_unpacklo_epi16(_01, _23),  // r0 r2 g0 g2 b0 b2 a0 a2
408              _13 = _mm_unpackhi_epi16(_01, _23),  // r1 r3 g1 g3 b1 b3 a1 a3
409              _46 = _mm_unpacklo_epi16(_45, _67),
410              _57 = _mm_unpackhi_epi16(_45, _67);
411 
412         auto rg0123 = _mm_unpacklo_epi16(_02, _13),  // r0 r1 r2 r3 g0 g1 g2 g3
413              ba0123 = _mm_unpackhi_epi16(_02, _13),  // b0 b1 b2 b3 a0 a1 a2 a3
414              rg4567 = _mm_unpacklo_epi16(_46, _57),
415              ba4567 = _mm_unpackhi_epi16(_46, _57);
416 
417         *r = _mm_unpacklo_epi64(rg0123, rg4567);
418         *g = _mm_unpackhi_epi64(rg0123, rg4567);
419         *b = _mm_unpacklo_epi64(ba0123, ba4567);
420         *a = _mm_unpackhi_epi64(ba0123, ba4567);
421     }
422     SI void store4(uint16_t* ptr, size_t tail, U16 r, U16 g, U16 b, U16 a) {
423         auto rg0123 = _mm_unpacklo_epi16(r, g),  // r0 g0 r1 g1 r2 g2 r3 g3
424              rg4567 = _mm_unpackhi_epi16(r, g),  // r4 g4 r5 g5 r6 g6 r7 g7
425              ba0123 = _mm_unpacklo_epi16(b, a),
426              ba4567 = _mm_unpackhi_epi16(b, a);
427 
428         auto _01 = _mm_unpacklo_epi32(rg0123, ba0123),
429              _23 = _mm_unpackhi_epi32(rg0123, ba0123),
430              _45 = _mm_unpacklo_epi32(rg4567, ba4567),
431              _67 = _mm_unpackhi_epi32(rg4567, ba4567);
432 
433         if (__builtin_expect(tail,0)) {
434             auto dst = (double*)ptr;
435             if (tail > 0) { _mm_storel_pd(dst+0, _01); }
436             if (tail > 1) { _mm_storeh_pd(dst+1, _01); }
437             if (tail > 2) { _mm_storel_pd(dst+2, _23); }
438             if (tail > 3) { _mm_storeh_pd(dst+3, _23); }
439             if (tail > 4) { _mm_storel_pd(dst+4, _45); }
440             if (tail > 5) { _mm_storeh_pd(dst+5, _45); }
441             if (tail > 6) { _mm_storel_pd(dst+6, _67); }
442         } else {
443             _mm_storeu_si128((__m128i*)ptr + 0, _01);
444             _mm_storeu_si128((__m128i*)ptr + 1, _23);
445             _mm_storeu_si128((__m128i*)ptr + 2, _45);
446             _mm_storeu_si128((__m128i*)ptr + 3, _67);
447         }
448     }
449 
450     SI void load4(const float* ptr, size_t tail, F* r, F* g, F* b, F* a) {
451         F _04, _15, _26, _37;
452         _04 = _15 = _26 = _37 = 0;
453         switch (tail) {
454             case 0: _37 = _mm256_insertf128_ps(_37, _mm_loadu_ps(ptr+28), 1);
455             case 7: _26 = _mm256_insertf128_ps(_26, _mm_loadu_ps(ptr+24), 1);
456             case 6: _15 = _mm256_insertf128_ps(_15, _mm_loadu_ps(ptr+20), 1);
457             case 5: _04 = _mm256_insertf128_ps(_04, _mm_loadu_ps(ptr+16), 1);
458             case 4: _37 = _mm256_insertf128_ps(_37, _mm_loadu_ps(ptr+12), 0);
459             case 3: _26 = _mm256_insertf128_ps(_26, _mm_loadu_ps(ptr+ 8), 0);
460             case 2: _15 = _mm256_insertf128_ps(_15, _mm_loadu_ps(ptr+ 4), 0);
461             case 1: _04 = _mm256_insertf128_ps(_04, _mm_loadu_ps(ptr+ 0), 0);
462         }
463 
464         F rg0145 = _mm256_unpacklo_ps(_04,_15),  // r0 r1 g0 g1 | r4 r5 g4 g5
465           ba0145 = _mm256_unpackhi_ps(_04,_15),
466           rg2367 = _mm256_unpacklo_ps(_26,_37),
467           ba2367 = _mm256_unpackhi_ps(_26,_37);
468 
469         *r = _mm256_unpacklo_pd(rg0145, rg2367);
470         *g = _mm256_unpackhi_pd(rg0145, rg2367);
471         *b = _mm256_unpacklo_pd(ba0145, ba2367);
472         *a = _mm256_unpackhi_pd(ba0145, ba2367);
473     }
474     SI void store4(float* ptr, size_t tail, F r, F g, F b, F a) {
475         F rg0145 = _mm256_unpacklo_ps(r, g),  // r0 g0 r1 g1 | r4 g4 r5 g5
476           rg2367 = _mm256_unpackhi_ps(r, g),  // r2 ...      | r6 ...
477           ba0145 = _mm256_unpacklo_ps(b, a),  // b0 a0 b1 a1 | b4 a4 b5 a5
478           ba2367 = _mm256_unpackhi_ps(b, a);  // b2 ...      | b6 ...
479 
480         F _04 = _mm256_unpacklo_pd(rg0145, ba0145),  // r0 g0 b0 a0 | r4 g4 b4 a4
481           _15 = _mm256_unpackhi_pd(rg0145, ba0145),  // r1 ...      | r5 ...
482           _26 = _mm256_unpacklo_pd(rg2367, ba2367),  // r2 ...      | r6 ...
483           _37 = _mm256_unpackhi_pd(rg2367, ba2367);  // r3 ...      | r7 ...
484 
485         if (__builtin_expect(tail, 0)) {
486             if (tail > 0) { _mm_storeu_ps(ptr+ 0, _mm256_extractf128_ps(_04, 0)); }
487             if (tail > 1) { _mm_storeu_ps(ptr+ 4, _mm256_extractf128_ps(_15, 0)); }
488             if (tail > 2) { _mm_storeu_ps(ptr+ 8, _mm256_extractf128_ps(_26, 0)); }
489             if (tail > 3) { _mm_storeu_ps(ptr+12, _mm256_extractf128_ps(_37, 0)); }
490             if (tail > 4) { _mm_storeu_ps(ptr+16, _mm256_extractf128_ps(_04, 1)); }
491             if (tail > 5) { _mm_storeu_ps(ptr+20, _mm256_extractf128_ps(_15, 1)); }
492             if (tail > 6) { _mm_storeu_ps(ptr+24, _mm256_extractf128_ps(_26, 1)); }
493         } else {
494             F _01 = _mm256_permute2f128_ps(_04, _15, 32),  // 32 == 0010 0000 == lo, lo
495               _23 = _mm256_permute2f128_ps(_26, _37, 32),
496               _45 = _mm256_permute2f128_ps(_04, _15, 49),  // 49 == 0011 0001 == hi, hi
497               _67 = _mm256_permute2f128_ps(_26, _37, 49);
498             _mm256_storeu_ps(ptr+ 0, _01);
499             _mm256_storeu_ps(ptr+ 8, _23);
500             _mm256_storeu_ps(ptr+16, _45);
501             _mm256_storeu_ps(ptr+24, _67);
502         }
503     }
504 
505 #elif defined(JUMPER_IS_SSE2) || defined(JUMPER_IS_SSE41)
506     template <typename T> using V = T __attribute__((ext_vector_type(4)));
507     using F   = V<float   >;
508     using I32 = V< int32_t>;
509     using U64 = V<uint64_t>;
510     using U32 = V<uint32_t>;
511     using U16 = V<uint16_t>;
512     using U8  = V<uint8_t >;
513 
514     SI F   mad(F f, F m, F a)  { return f*m+a;              }
515     SI F   min(F a, F b)       { return _mm_min_ps(a,b);    }
516     SI F   max(F a, F b)       { return _mm_max_ps(a,b);    }
517     SI F   abs_(F v)           { return _mm_and_ps(v, 0-v); }
518     SI F   rcp   (F v)         { return _mm_rcp_ps  (v);    }
519     SI F   rsqrt (F v)         { return _mm_rsqrt_ps(v);    }
520     SI F    sqrt_(F v)         { return _mm_sqrt_ps (v);    }
521     SI U32 round(F v, F scale) { return _mm_cvtps_epi32(v*scale); }
522 
523     SI U16 pack(U32 v) {
524     #if defined(JUMPER_IS_SSE41)
525         auto p = _mm_packus_epi32(v,v);
526     #else
527         // Sign extend so that _mm_packs_epi32() does the pack we want.
528         auto p = _mm_srai_epi32(_mm_slli_epi32(v, 16), 16);
529         p = _mm_packs_epi32(p,p);
530     #endif
531         return unaligned_load<U16>(&p);  // We have two copies.  Return (the lower) one.
532     }
533     SI U8 pack(U16 v) {
534         auto r = widen_cast<__m128i>(v);
535         r = _mm_packus_epi16(r,r);
536         return unaligned_load<U8>(&r);
537     }
538 
539     SI F if_then_else(I32 c, F t, F e) {
540         return _mm_or_ps(_mm_and_ps(c, t), _mm_andnot_ps(c, e));
541     }
542 
543     SI F floor_(F v) {
544     #if defined(JUMPER_IS_SSE41)
545         return _mm_floor_ps(v);
546     #else
547         F roundtrip = _mm_cvtepi32_ps(_mm_cvttps_epi32(v));
548         return roundtrip - if_then_else(roundtrip > v, 1, 0);
549     #endif
550     }
551 
552     template <typename T>
553     SI V<T> gather(const T* p, U32 ix) {
554         return {p[ix[0]], p[ix[1]], p[ix[2]], p[ix[3]]};
555     }
556 
557     SI void load3(const uint16_t* ptr, size_t tail, U16* r, U16* g, U16* b) {
558         __m128i _0, _1, _2, _3;
559         if (__builtin_expect(tail,0)) {
560             _1 = _2 = _3 = _mm_setzero_si128();
561             auto load_rgb = [](const uint16_t* src) {
562                 auto v = _mm_cvtsi32_si128(*(const uint32_t*)src);
563                 return _mm_insert_epi16(v, src[2], 2);
564             };
565             if (  true  ) { _0 = load_rgb(ptr + 0); }
566             if (tail > 1) { _1 = load_rgb(ptr + 3); }
567             if (tail > 2) { _2 = load_rgb(ptr + 6); }
568         } else {
569             // Load slightly weirdly to make sure we don't load past the end of 4x48 bits.
570             auto _01 =                _mm_loadu_si128((const __m128i*)(ptr + 0))    ,
571                  _23 = _mm_srli_si128(_mm_loadu_si128((const __m128i*)(ptr + 4)), 4);
572 
573             // Each _N holds R,G,B for pixel N in its lower 3 lanes (upper 5 are ignored).
574             _0 = _01;
575             _1 = _mm_srli_si128(_01, 6);
576             _2 = _23;
577             _3 = _mm_srli_si128(_23, 6);
578         }
579 
580         // De-interlace to R,G,B.
581         auto _02 = _mm_unpacklo_epi16(_0, _2),  // r0 r2 g0 g2 b0 b2 xx xx
582              _13 = _mm_unpacklo_epi16(_1, _3);  // r1 r3 g1 g3 b1 b3 xx xx
583 
584         auto R = _mm_unpacklo_epi16(_02, _13),  // r0 r1 r2 r3 g0 g1 g2 g3
585              G = _mm_srli_si128(R, 8),
586              B = _mm_unpackhi_epi16(_02, _13);  // b0 b1 b2 b3 xx xx xx xx
587 
588         *r = unaligned_load<U16>(&R);
589         *g = unaligned_load<U16>(&G);
590         *b = unaligned_load<U16>(&B);
591     }
592 
593     SI void load4(const uint16_t* ptr, size_t tail, U16* r, U16* g, U16* b, U16* a) {
594         __m128i _01, _23;
595         if (__builtin_expect(tail,0)) {
596             _01 = _23 = _mm_setzero_si128();
597             auto src = (const double*)ptr;
598             if (  true  ) { _01 = _mm_loadl_pd(_01, src + 0); } // r0 g0 b0 a0 00 00 00 00
599             if (tail > 1) { _01 = _mm_loadh_pd(_01, src + 1); } // r0 g0 b0 a0 r1 g1 b1 a1
600             if (tail > 2) { _23 = _mm_loadl_pd(_23, src + 2); } // r2 g2 b2 a2 00 00 00 00
601         } else {
602             _01 = _mm_loadu_si128(((__m128i*)ptr) + 0); // r0 g0 b0 a0 r1 g1 b1 a1
603             _23 = _mm_loadu_si128(((__m128i*)ptr) + 1); // r2 g2 b2 a2 r3 g3 b3 a3
604         }
605 
606         auto _02 = _mm_unpacklo_epi16(_01, _23),  // r0 r2 g0 g2 b0 b2 a0 a2
607              _13 = _mm_unpackhi_epi16(_01, _23);  // r1 r3 g1 g3 b1 b3 a1 a3
608 
609         auto rg = _mm_unpacklo_epi16(_02, _13),  // r0 r1 r2 r3 g0 g1 g2 g3
610              ba = _mm_unpackhi_epi16(_02, _13);  // b0 b1 b2 b3 a0 a1 a2 a3
611 
612         *r = unaligned_load<U16>((uint16_t*)&rg + 0);
613         *g = unaligned_load<U16>((uint16_t*)&rg + 4);
614         *b = unaligned_load<U16>((uint16_t*)&ba + 0);
615         *a = unaligned_load<U16>((uint16_t*)&ba + 4);
616     }
617 
618     SI void store4(uint16_t* ptr, size_t tail, U16 r, U16 g, U16 b, U16 a) {
619         auto rg = _mm_unpacklo_epi16(widen_cast<__m128i>(r), widen_cast<__m128i>(g)),
620              ba = _mm_unpacklo_epi16(widen_cast<__m128i>(b), widen_cast<__m128i>(a));
621 
622         if (__builtin_expect(tail, 0)) {
623             auto dst = (double*)ptr;
624             if (  true  ) { _mm_storel_pd(dst + 0, _mm_unpacklo_epi32(rg, ba)); }
625             if (tail > 1) { _mm_storeh_pd(dst + 1, _mm_unpacklo_epi32(rg, ba)); }
626             if (tail > 2) { _mm_storel_pd(dst + 2, _mm_unpackhi_epi32(rg, ba)); }
627         } else {
628             _mm_storeu_si128((__m128i*)ptr + 0, _mm_unpacklo_epi32(rg, ba));
629             _mm_storeu_si128((__m128i*)ptr + 1, _mm_unpackhi_epi32(rg, ba));
630         }
631     }
632 
633     SI void load4(const float* ptr, size_t tail, F* r, F* g, F* b, F* a) {
634         F _0, _1, _2, _3;
635         if (__builtin_expect(tail, 0)) {
636             _1 = _2 = _3 = _mm_setzero_si128();
637             if (  true  ) { _0 = _mm_loadu_ps(ptr + 0); }
638             if (tail > 1) { _1 = _mm_loadu_ps(ptr + 4); }
639             if (tail > 2) { _2 = _mm_loadu_ps(ptr + 8); }
640         } else {
641             _0 = _mm_loadu_ps(ptr + 0);
642             _1 = _mm_loadu_ps(ptr + 4);
643             _2 = _mm_loadu_ps(ptr + 8);
644             _3 = _mm_loadu_ps(ptr +12);
645         }
646         _MM_TRANSPOSE4_PS(_0,_1,_2,_3);
647         *r = _0;
648         *g = _1;
649         *b = _2;
650         *a = _3;
651     }
652 
653     SI void store4(float* ptr, size_t tail, F r, F g, F b, F a) {
654         _MM_TRANSPOSE4_PS(r,g,b,a);
655         if (__builtin_expect(tail, 0)) {
656             if (  true  ) { _mm_storeu_ps(ptr + 0, r); }
657             if (tail > 1) { _mm_storeu_ps(ptr + 4, g); }
658             if (tail > 2) { _mm_storeu_ps(ptr + 8, b); }
659         } else {
660             _mm_storeu_ps(ptr + 0, r);
661             _mm_storeu_ps(ptr + 4, g);
662             _mm_storeu_ps(ptr + 8, b);
663             _mm_storeu_ps(ptr +12, a);
664         }
665     }
666 #endif
667 
668 // We need to be a careful with casts.
669 // (F)x means cast x to float in the portable path, but bit_cast x to float in the others.
670 // These named casts and bit_cast() are always what they seem to be.
671 #if defined(JUMPER_IS_SCALAR)
cast(U32 v)672     SI F   cast  (U32 v) { return   (F)v; }
trunc_(F v)673     SI U32 trunc_(F   v) { return (U32)v; }
expand(U16 v)674     SI U32 expand(U16 v) { return (U32)v; }
expand(U8 v)675     SI U32 expand(U8  v) { return (U32)v; }
676 #else
cast(U32 v)677     SI F   cast  (U32 v) { return      __builtin_convertvector((I32)v,   F); }
trunc_(F v)678     SI U32 trunc_(F   v) { return (U32)__builtin_convertvector(     v, I32); }
expand(U16 v)679     SI U32 expand(U16 v) { return      __builtin_convertvector(     v, U32); }
expand(U8 v)680     SI U32 expand(U8  v) { return      __builtin_convertvector(     v, U32); }
681 #endif
682 
683 template <typename V>
if_then_else(I32 c,V t,V e)684 SI V if_then_else(I32 c, V t, V e) {
685     return bit_cast<V>(if_then_else(c, bit_cast<F>(t), bit_cast<F>(e)));
686 }
687 
bswap(U16 x)688 SI U16 bswap(U16 x) {
689 #if defined(JUMPER_IS_SSE2) || defined(JUMPER_IS_SSE41)
690     // Somewhat inexplicably Clang decides to do (x<<8) | (x>>8) in 32-bit lanes
691     // when generating code for SSE2 and SSE4.1.  We'll do it manually...
692     auto v = widen_cast<__m128i>(x);
693     v = _mm_slli_epi16(v,8) | _mm_srli_epi16(v,8);
694     return unaligned_load<U16>(&v);
695 #else
696     return (x<<8) | (x>>8);
697 #endif
698 }
699 
fract(F v)700 SI F fract(F v) { return v - floor_(v); }
701 
702 // See http://www.machinedlearnings.com/2011/06/fast-approximate-logarithm-exponential.html.
approx_log2(F x)703 SI F approx_log2(F x) {
704     // e - 127 is a fair approximation of log2(x) in its own right...
705     F e = cast(bit_cast<U32>(x)) * (1.0f / (1<<23));
706 
707     // ... but using the mantissa to refine its error is _much_ better.
708     F m = bit_cast<F>((bit_cast<U32>(x) & 0x007fffff) | 0x3f000000);
709     return e
710          - 124.225514990f
711          -   1.498030302f * m
712          -   1.725879990f / (0.3520887068f + m);
713 }
approx_pow2(F x)714 SI F approx_pow2(F x) {
715     F f = fract(x);
716     return bit_cast<F>(round(1.0f * (1<<23),
717                              x + 121.274057500f
718                                -   1.490129070f * f
719                                +  27.728023300f / (4.84252568f - f)));
720 }
721 
approx_powf(F x,F y)722 SI F approx_powf(F x, F y) {
723 #if defined(SK_LEGACY_APPROX_POWF_SPECIALCASE)
724     return if_then_else((x == 0)         , 0
725 #else
726     return if_then_else((x == 0)|(x == 1), x
727 #endif
728                                          , approx_pow2(approx_log2(x) * y));
729 }
730 
from_half(U16 h)731 SI F from_half(U16 h) {
732 #if defined(SK_CPU_ARM64) && !defined(SK_BUILD_FOR_GOOGLE3)  // Temporary workaround for some Google3 builds.
733     return vcvt_f32_f16(h);
734 
735 #elif defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
736     return _mm256_cvtph_ps(h);
737 
738 #else
739     // Remember, a half is 1-5-10 (sign-exponent-mantissa) with 15 exponent bias.
740     U32 sem = expand(h),
741         s   = sem & 0x8000,
742          em = sem ^ s;
743 
744     // Convert to 1-8-23 float with 127 bias, flushing denorm halfs (including zero) to zero.
745     auto denorm = (I32)em < 0x0400;      // I32 comparison is often quicker, and always safe here.
746     return if_then_else(denorm, F(0)
747                               , bit_cast<F>( (s<<16) + (em<<13) + ((127-15)<<23) ));
748 #endif
749 }
750 
to_half(F f)751 SI U16 to_half(F f) {
752 #if defined(SK_CPU_ARM64) && !defined(SK_BUILD_FOR_GOOGLE3)  // Temporary workaround for some Google3 builds.
753     return vcvt_f16_f32(f);
754 
755 #elif defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
756     return _mm256_cvtps_ph(f, _MM_FROUND_CUR_DIRECTION);
757 
758 #else
759     // Remember, a float is 1-8-23 (sign-exponent-mantissa) with 127 exponent bias.
760     U32 sem = bit_cast<U32>(f),
761         s   = sem & 0x80000000,
762          em = sem ^ s;
763 
764     // Convert to 1-5-10 half with 15 bias, flushing denorm halfs (including zero) to zero.
765     auto denorm = (I32)em < 0x38800000;  // I32 comparison is often quicker, and always safe here.
766     return pack(if_then_else(denorm, U32(0)
767                                    , (s>>16) + (em>>13) - ((127-15)<<10)));
768 #endif
769 }
770 
771 // Our fundamental vector depth is our pixel stride.
772 static const size_t N = sizeof(F) / sizeof(float);
773 
774 // We're finally going to get to what a Stage function looks like!
775 //    tail == 0 ~~> work on a full N pixels
776 //    tail != 0 ~~> work on only the first tail pixels
777 // tail is always < N.
778 
779 // Any custom ABI to use for all (non-externally-facing) stage functions?
780 // Also decide here whether to use narrow (compromise) or wide (ideal) stages.
781 #if defined(SK_CPU_ARM32) && defined(JUMPER_IS_NEON)
782     // This lets us pass vectors more efficiently on 32-bit ARM.
783     // We can still only pass 16 floats, so best as 4x {r,g,b,a}.
784     #define ABI __attribute__((pcs("aapcs-vfp")))
785     #define JUMPER_NARROW_STAGES 1
786 #elif 0 && defined(_MSC_VER) && defined(__clang__) && defined(__x86_64__)
787     // SysV ABI makes it very sensible to use wide stages with clang-cl.
788     // TODO: crashes during compilation  :(
789     #define ABI __attribute__((sysv_abi))
790     #define JUMPER_NARROW_STAGES 0
791 #elif defined(_MSC_VER)
792     // Even if not vectorized, this lets us pass {r,g,b,a} as registers,
793     // instead of {b,a} on the stack.  Narrow stages work best for __vectorcall.
794     #define ABI __vectorcall
795     #define JUMPER_NARROW_STAGES 1
796 #elif defined(__x86_64__) || defined(SK_CPU_ARM64)
797     // These platforms are ideal for wider stages, and their default ABI is ideal.
798     #define ABI
799     #define JUMPER_NARROW_STAGES 0
800 #else
801     // 32-bit or unknown... shunt them down the narrow path.
802     // Odds are these have few registers and are better off there.
803     #define ABI
804     #define JUMPER_NARROW_STAGES 1
805 #endif
806 
807 #if JUMPER_NARROW_STAGES
808     struct Params {
809         size_t dx, dy, tail;
810         F dr,dg,db,da;
811     };
812     using Stage = void(ABI*)(Params*, void** program, F r, F g, F b, F a);
813 #else
814     // We keep program the second argument, so that it's passed in rsi for load_and_inc().
815     using Stage = void(ABI*)(size_t tail, void** program, size_t dx, size_t dy, F,F,F,F, F,F,F,F);
816 #endif
817 
818 
start_pipeline(size_t dx,size_t dy,size_t xlimit,size_t ylimit,void ** program)819 static void start_pipeline(size_t dx, size_t dy, size_t xlimit, size_t ylimit, void** program) {
820     auto start = (Stage)load_and_inc(program);
821     const size_t x0 = dx;
822     for (; dy < ylimit; dy++) {
823     #if JUMPER_NARROW_STAGES
824         Params params = { x0,dy,0, 0,0,0,0 };
825         while (params.dx + N <= xlimit) {
826             start(&params,program, 0,0,0,0);
827             params.dx += N;
828         }
829         if (size_t tail = xlimit - params.dx) {
830             params.tail = tail;
831             start(&params,program, 0,0,0,0);
832         }
833     #else
834         dx = x0;
835         while (dx + N <= xlimit) {
836             start(0,program,dx,dy,    0,0,0,0, 0,0,0,0);
837             dx += N;
838         }
839         if (size_t tail = xlimit - dx) {
840             start(tail,program,dx,dy, 0,0,0,0, 0,0,0,0);
841         }
842     #endif
843     }
844 }
845 
846 #if JUMPER_NARROW_STAGES
847     #define STAGE(name, ...)                                                    \
848         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail,        \
849                          F& r, F& g, F& b, F& a, F& dr, F& dg, F& db, F& da);   \
850         static void ABI name(Params* params, void** program,                    \
851                              F r, F g, F b, F a) {                              \
852             name##_k(Ctx{program},params->dx,params->dy,params->tail, r,g,b,a,  \
853                      params->dr, params->dg, params->db, params->da);           \
854             auto next = (Stage)load_and_inc(program);                           \
855             next(params,program, r,g,b,a);                                      \
856         }                                                                       \
857         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail,        \
858                          F& r, F& g, F& b, F& a, F& dr, F& dg, F& db, F& da)
859 #else
860     #define STAGE(name, ...)                                                         \
861         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail,             \
862                          F& r, F& g, F& b, F& a, F& dr, F& dg, F& db, F& da);        \
863         static void ABI name(size_t tail, void** program, size_t dx, size_t dy,      \
864                              F r, F g, F b, F a, F dr, F dg, F db, F da) {           \
865             name##_k(Ctx{program},dx,dy,tail, r,g,b,a, dr,dg,db,da);                 \
866             auto next = (Stage)load_and_inc(program);                                \
867             next(tail,program,dx,dy, r,g,b,a, dr,dg,db,da);                          \
868         }                                                                            \
869         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail,             \
870                          F& r, F& g, F& b, F& a, F& dr, F& dg, F& db, F& da)
871 #endif
872 
873 
874 // just_return() is a simple no-op stage that only exists to end the chain,
875 // returning back up to start_pipeline(), and from there to the caller.
876 #if JUMPER_NARROW_STAGES
just_return(Params *,void **,F,F,F,F)877     static void ABI just_return(Params*, void**, F,F,F,F) {}
878 #else
just_return(size_t,void **,size_t,size_t,F,F,F,F,F,F,F,F)879     static void ABI just_return(size_t, void**, size_t,size_t, F,F,F,F, F,F,F,F) {}
880 #endif
881 
882 
883 // We could start defining normal Stages now.  But first, some helper functions.
884 
885 // These load() and store() methods are tail-aware,
886 // but focus mainly on keeping the at-stride tail==0 case fast.
887 
888 template <typename V, typename T>
load(const T * src,size_t tail)889 SI V load(const T* src, size_t tail) {
890 #if !defined(JUMPER_IS_SCALAR)
891     __builtin_assume(tail < N);
892     if (__builtin_expect(tail, 0)) {
893         V v{};  // Any inactive lanes are zeroed.
894         switch (tail) {
895             case 7: v[6] = src[6];
896             case 6: v[5] = src[5];
897             case 5: v[4] = src[4];
898             case 4: memcpy(&v, src, 4*sizeof(T)); break;
899             case 3: v[2] = src[2];
900             case 2: memcpy(&v, src, 2*sizeof(T)); break;
901             case 1: memcpy(&v, src, 1*sizeof(T)); break;
902         }
903         return v;
904     }
905 #endif
906     return unaligned_load<V>(src);
907 }
908 
909 template <typename V, typename T>
store(T * dst,V v,size_t tail)910 SI void store(T* dst, V v, size_t tail) {
911 #if !defined(JUMPER_IS_SCALAR)
912     __builtin_assume(tail < N);
913     if (__builtin_expect(tail, 0)) {
914         switch (tail) {
915             case 7: dst[6] = v[6];
916             case 6: dst[5] = v[5];
917             case 5: dst[4] = v[4];
918             case 4: memcpy(dst, &v, 4*sizeof(T)); break;
919             case 3: dst[2] = v[2];
920             case 2: memcpy(dst, &v, 2*sizeof(T)); break;
921             case 1: memcpy(dst, &v, 1*sizeof(T)); break;
922         }
923         return;
924     }
925 #endif
926     unaligned_store(dst, v);
927 }
928 
from_byte(U8 b)929 SI F from_byte(U8 b) {
930     return cast(expand(b)) * (1/255.0f);
931 }
from_565(U16 _565,F * r,F * g,F * b)932 SI void from_565(U16 _565, F* r, F* g, F* b) {
933     U32 wide = expand(_565);
934     *r = cast(wide & (31<<11)) * (1.0f / (31<<11));
935     *g = cast(wide & (63<< 5)) * (1.0f / (63<< 5));
936     *b = cast(wide & (31<< 0)) * (1.0f / (31<< 0));
937 }
from_4444(U16 _4444,F * r,F * g,F * b,F * a)938 SI void from_4444(U16 _4444, F* r, F* g, F* b, F* a) {
939     U32 wide = expand(_4444);
940     *r = cast(wide & (15<<12)) * (1.0f / (15<<12));
941     *g = cast(wide & (15<< 8)) * (1.0f / (15<< 8));
942     *b = cast(wide & (15<< 4)) * (1.0f / (15<< 4));
943     *a = cast(wide & (15<< 0)) * (1.0f / (15<< 0));
944 }
from_8888(U32 _8888,F * r,F * g,F * b,F * a)945 SI void from_8888(U32 _8888, F* r, F* g, F* b, F* a) {
946     *r = cast((_8888      ) & 0xff) * (1/255.0f);
947     *g = cast((_8888 >>  8) & 0xff) * (1/255.0f);
948     *b = cast((_8888 >> 16) & 0xff) * (1/255.0f);
949     *a = cast((_8888 >> 24)       ) * (1/255.0f);
950 }
from_1010102(U32 rgba,F * r,F * g,F * b,F * a)951 SI void from_1010102(U32 rgba, F* r, F* g, F* b, F* a) {
952     *r = cast((rgba      ) & 0x3ff) * (1/1023.0f);
953     *g = cast((rgba >> 10) & 0x3ff) * (1/1023.0f);
954     *b = cast((rgba >> 20) & 0x3ff) * (1/1023.0f);
955     *a = cast((rgba >> 30)        ) * (1/   3.0f);
956 }
957 
958 // Used by load_ and store_ stages to get to the right (dx,dy) starting point of contiguous memory.
959 template <typename T>
ptr_at_xy(const SkRasterPipeline_MemoryCtx * ctx,size_t dx,size_t dy)960 SI T* ptr_at_xy(const SkRasterPipeline_MemoryCtx* ctx, size_t dx, size_t dy) {
961     return (T*)ctx->pixels + dy*ctx->stride + dx;
962 }
963 
964 // clamp v to [0,limit).
clamp(F v,F limit)965 SI F clamp(F v, F limit) {
966     F inclusive = bit_cast<F>( bit_cast<U32>(limit) - 1 );  // Exclusive -> inclusive.
967     return min(max(0, v), inclusive);
968 }
969 
970 // Used by gather_ stages to calculate the base pointer and a vector of indices to load.
971 template <typename T>
ix_and_ptr(T ** ptr,const SkRasterPipeline_GatherCtx * ctx,F x,F y)972 SI U32 ix_and_ptr(T** ptr, const SkRasterPipeline_GatherCtx* ctx, F x, F y) {
973     x = clamp(x, ctx->width);
974     y = clamp(y, ctx->height);
975 
976     *ptr = (const T*)ctx->pixels;
977     return trunc_(y)*ctx->stride + trunc_(x);
978 }
979 
980 // We often have a nominally [0,1] float value we need to scale and convert to an integer,
981 // whether for a table lookup or to pack back down into bytes for storage.
982 //
983 // In practice, especially when dealing with interesting color spaces, that notionally
984 // [0,1] float may be out of [0,1] range.  Unorms cannot represent that, so we must clamp.
985 //
986 // You can adjust the expected input to [0,bias] by tweaking that parameter.
987 SI U32 to_unorm(F v, F scale, F bias = 1.0f) {
988     // TODO: platform-specific implementations to to_unorm(), removing round() entirely?
989     // Any time we use round() we probably want to use to_unorm().
990     return round(min(max(0, v), bias), scale);
991 }
992 
cond_to_mask(I32 cond)993 SI I32 cond_to_mask(I32 cond) { return if_then_else(cond, I32(~0), I32(0)); }
994 
995 // Now finally, normal Stages!
996 
STAGE(seed_shader,Ctx::None)997 STAGE(seed_shader, Ctx::None) {
998     static const float iota[] = {
999         0.5f, 1.5f, 2.5f, 3.5f, 4.5f, 5.5f, 6.5f, 7.5f,
1000         8.5f, 9.5f,10.5f,11.5f,12.5f,13.5f,14.5f,15.5f,
1001     };
1002     // It's important for speed to explicitly cast(dx) and cast(dy),
1003     // which has the effect of splatting them to vectors before converting to floats.
1004     // On Intel this breaks a data dependency on previous loop iterations' registers.
1005     r = cast(dx) + unaligned_load<F>(iota);
1006     g = cast(dy) + 0.5f;
1007     b = 1.0f;
1008     a = 0;
1009     dr = dg = db = da = 0;
1010 }
1011 
STAGE(dither,const float * rate)1012 STAGE(dither, const float* rate) {
1013     // Get [(dx,dy), (dx+1,dy), (dx+2,dy), ...] loaded up in integer vectors.
1014     uint32_t iota[] = {0,1,2,3,4,5,6,7};
1015     U32 X = dx + unaligned_load<U32>(iota),
1016         Y = dy;
1017 
1018     // We're doing 8x8 ordered dithering, see https://en.wikipedia.org/wiki/Ordered_dithering.
1019     // In this case n=8 and we're using the matrix that looks like 1/64 x [ 0 48 12 60 ... ].
1020 
1021     // We only need X and X^Y from here on, so it's easier to just think of that as "Y".
1022     Y ^= X;
1023 
1024     // We'll mix the bottom 3 bits of each of X and Y to make 6 bits,
1025     // for 2^6 == 64 == 8x8 matrix values.  If X=abc and Y=def, we make fcebda.
1026     U32 M = (Y & 1) << 5 | (X & 1) << 4
1027           | (Y & 2) << 2 | (X & 2) << 1
1028           | (Y & 4) >> 1 | (X & 4) >> 2;
1029 
1030     // Scale that dither to [0,1), then (-0.5,+0.5), here using 63/128 = 0.4921875 as 0.5-epsilon.
1031     // We want to make sure our dither is less than 0.5 in either direction to keep exact values
1032     // like 0 and 1 unchanged after rounding.
1033     F dither = cast(M) * (2/128.0f) - (63/128.0f);
1034 
1035     r += *rate*dither;
1036     g += *rate*dither;
1037     b += *rate*dither;
1038 
1039     r = max(0, min(r, a));
1040     g = max(0, min(g, a));
1041     b = max(0, min(b, a));
1042 }
1043 
1044 // load 4 floats from memory, and splat them into r,g,b,a
STAGE(uniform_color,const SkRasterPipeline_UniformColorCtx * c)1045 STAGE(uniform_color, const SkRasterPipeline_UniformColorCtx* c) {
1046     r = c->r;
1047     g = c->g;
1048     b = c->b;
1049     a = c->a;
1050 }
STAGE(unbounded_uniform_color,const SkRasterPipeline_UniformColorCtx * c)1051 STAGE(unbounded_uniform_color, const SkRasterPipeline_UniformColorCtx* c) {
1052     r = c->r;
1053     g = c->g;
1054     b = c->b;
1055     a = c->a;
1056 }
1057 
1058 // splats opaque-black into r,g,b,a
STAGE(black_color,Ctx::None)1059 STAGE(black_color, Ctx::None) {
1060     r = g = b = 0.0f;
1061     a = 1.0f;
1062 }
1063 
STAGE(white_color,Ctx::None)1064 STAGE(white_color, Ctx::None) {
1065     r = g = b = a = 1.0f;
1066 }
1067 
1068 // load registers r,g,b,a from context (mirrors store_rgba)
STAGE(load_src,const float * ptr)1069 STAGE(load_src, const float* ptr) {
1070     r = unaligned_load<F>(ptr + 0*N);
1071     g = unaligned_load<F>(ptr + 1*N);
1072     b = unaligned_load<F>(ptr + 2*N);
1073     a = unaligned_load<F>(ptr + 3*N);
1074 }
1075 
1076 // store registers r,g,b,a into context (mirrors load_rgba)
STAGE(store_src,float * ptr)1077 STAGE(store_src, float* ptr) {
1078     unaligned_store(ptr + 0*N, r);
1079     unaligned_store(ptr + 1*N, g);
1080     unaligned_store(ptr + 2*N, b);
1081     unaligned_store(ptr + 3*N, a);
1082 }
1083 
1084 // load registers dr,dg,db,da from context (mirrors store_dst)
STAGE(load_dst,const float * ptr)1085 STAGE(load_dst, const float* ptr) {
1086     dr = unaligned_load<F>(ptr + 0*N);
1087     dg = unaligned_load<F>(ptr + 1*N);
1088     db = unaligned_load<F>(ptr + 2*N);
1089     da = unaligned_load<F>(ptr + 3*N);
1090 }
1091 
1092 // store registers dr,dg,db,da into context (mirrors load_dst)
STAGE(store_dst,float * ptr)1093 STAGE(store_dst, float* ptr) {
1094     unaligned_store(ptr + 0*N, dr);
1095     unaligned_store(ptr + 1*N, dg);
1096     unaligned_store(ptr + 2*N, db);
1097     unaligned_store(ptr + 3*N, da);
1098 }
1099 
1100 // Most blend modes apply the same logic to each channel.
1101 #define BLEND_MODE(name)                       \
1102     SI F name##_channel(F s, F d, F sa, F da); \
1103     STAGE(name, Ctx::None) {                   \
1104         r = name##_channel(r,dr,a,da);         \
1105         g = name##_channel(g,dg,a,da);         \
1106         b = name##_channel(b,db,a,da);         \
1107         a = name##_channel(a,da,a,da);         \
1108     }                                          \
1109     SI F name##_channel(F s, F d, F sa, F da)
1110 
inv(F x)1111 SI F inv(F x) { return 1.0f - x; }
two(F x)1112 SI F two(F x) { return x + x; }
1113 
1114 
BLEND_MODE(clear)1115 BLEND_MODE(clear)    { return 0; }
BLEND_MODE(srcatop)1116 BLEND_MODE(srcatop)  { return s*da + d*inv(sa); }
BLEND_MODE(dstatop)1117 BLEND_MODE(dstatop)  { return d*sa + s*inv(da); }
BLEND_MODE(srcin)1118 BLEND_MODE(srcin)    { return s * da; }
BLEND_MODE(dstin)1119 BLEND_MODE(dstin)    { return d * sa; }
BLEND_MODE(srcout)1120 BLEND_MODE(srcout)   { return s * inv(da); }
BLEND_MODE(dstout)1121 BLEND_MODE(dstout)   { return d * inv(sa); }
BLEND_MODE(srcover)1122 BLEND_MODE(srcover)  { return mad(d, inv(sa), s); }
BLEND_MODE(dstover)1123 BLEND_MODE(dstover)  { return mad(s, inv(da), d); }
1124 
BLEND_MODE(modulate)1125 BLEND_MODE(modulate) { return s*d; }
BLEND_MODE(multiply)1126 BLEND_MODE(multiply) { return s*inv(da) + d*inv(sa) + s*d; }
BLEND_MODE(plus_)1127 BLEND_MODE(plus_)    { return min(s + d, 1.0f); }  // We can clamp to either 1 or sa.
BLEND_MODE(screen)1128 BLEND_MODE(screen)   { return s + d - s*d; }
BLEND_MODE(xor_)1129 BLEND_MODE(xor_)     { return s*inv(da) + d*inv(sa); }
1130 #undef BLEND_MODE
1131 
1132 // Most other blend modes apply the same logic to colors, and srcover to alpha.
1133 #define BLEND_MODE(name)                       \
1134     SI F name##_channel(F s, F d, F sa, F da); \
1135     STAGE(name, Ctx::None) {                   \
1136         r = name##_channel(r,dr,a,da);         \
1137         g = name##_channel(g,dg,a,da);         \
1138         b = name##_channel(b,db,a,da);         \
1139         a = mad(da, inv(a), a);                \
1140     }                                          \
1141     SI F name##_channel(F s, F d, F sa, F da)
1142 
BLEND_MODE(darken)1143 BLEND_MODE(darken)     { return s + d -     max(s*da, d*sa) ; }
BLEND_MODE(lighten)1144 BLEND_MODE(lighten)    { return s + d -     min(s*da, d*sa) ; }
BLEND_MODE(difference)1145 BLEND_MODE(difference) { return s + d - two(min(s*da, d*sa)); }
BLEND_MODE(exclusion)1146 BLEND_MODE(exclusion)  { return s + d - two(s*d); }
1147 
BLEND_MODE(colorburn)1148 BLEND_MODE(colorburn) {
1149     return if_then_else(d == da,    d +    s*inv(da),
1150            if_then_else(s ==  0, /* s + */ d*inv(sa),
1151                                  sa*(da - min(da, (da-d)*sa*rcp(s))) + s*inv(da) + d*inv(sa)));
1152 }
BLEND_MODE(colordodge)1153 BLEND_MODE(colordodge) {
1154     return if_then_else(d ==  0, /* d + */ s*inv(da),
1155            if_then_else(s == sa,    s +    d*inv(sa),
1156                                  sa*min(da, (d*sa)*rcp(sa - s)) + s*inv(da) + d*inv(sa)));
1157 }
BLEND_MODE(hardlight)1158 BLEND_MODE(hardlight) {
1159     return s*inv(da) + d*inv(sa)
1160          + if_then_else(two(s) <= sa, two(s*d), sa*da - two((da-d)*(sa-s)));
1161 }
BLEND_MODE(overlay)1162 BLEND_MODE(overlay) {
1163     return s*inv(da) + d*inv(sa)
1164          + if_then_else(two(d) <= da, two(s*d), sa*da - two((da-d)*(sa-s)));
1165 }
1166 
BLEND_MODE(softlight)1167 BLEND_MODE(softlight) {
1168     F m  = if_then_else(da > 0, d / da, 0),
1169       s2 = two(s),
1170       m4 = two(two(m));
1171 
1172     // The logic forks three ways:
1173     //    1. dark src?
1174     //    2. light src, dark dst?
1175     //    3. light src, light dst?
1176     F darkSrc = d*(sa + (s2 - sa)*(1.0f - m)),     // Used in case 1.
1177       darkDst = (m4*m4 + m4)*(m - 1.0f) + 7.0f*m,  // Used in case 2.
1178       liteDst = rcp(rsqrt(m)) - m,                 // Used in case 3.
1179       liteSrc = d*sa + da*(s2 - sa) * if_then_else(two(two(d)) <= da, darkDst, liteDst); // 2 or 3?
1180     return s*inv(da) + d*inv(sa) + if_then_else(s2 <= sa, darkSrc, liteSrc);      // 1 or (2 or 3)?
1181 }
1182 #undef BLEND_MODE
1183 
1184 // We're basing our implemenation of non-separable blend modes on
1185 //   https://www.w3.org/TR/compositing-1/#blendingnonseparable.
1186 // and
1187 //   https://www.khronos.org/registry/OpenGL/specs/es/3.2/es_spec_3.2.pdf
1188 // They're equivalent, but ES' math has been better simplified.
1189 //
1190 // Anything extra we add beyond that is to make the math work with premul inputs.
1191 
max(F r,F g,F b)1192 SI F max(F r, F g, F b) { return max(r, max(g, b)); }
min(F r,F g,F b)1193 SI F min(F r, F g, F b) { return min(r, min(g, b)); }
1194 
sat(F r,F g,F b)1195 SI F sat(F r, F g, F b) { return max(r,g,b) - min(r,g,b); }
lum(F r,F g,F b)1196 SI F lum(F r, F g, F b) { return r*0.30f + g*0.59f + b*0.11f; }
1197 
set_sat(F * r,F * g,F * b,F s)1198 SI void set_sat(F* r, F* g, F* b, F s) {
1199     F mn  = min(*r,*g,*b),
1200       mx  = max(*r,*g,*b),
1201       sat = mx - mn;
1202 
1203     // Map min channel to 0, max channel to s, and scale the middle proportionally.
1204     auto scale = [=](F c) {
1205         return if_then_else(sat == 0, 0, (c - mn) * s / sat);
1206     };
1207     *r = scale(*r);
1208     *g = scale(*g);
1209     *b = scale(*b);
1210 }
set_lum(F * r,F * g,F * b,F l)1211 SI void set_lum(F* r, F* g, F* b, F l) {
1212     F diff = l - lum(*r, *g, *b);
1213     *r += diff;
1214     *g += diff;
1215     *b += diff;
1216 }
clip_color(F * r,F * g,F * b,F a)1217 SI void clip_color(F* r, F* g, F* b, F a) {
1218     F mn = min(*r, *g, *b),
1219       mx = max(*r, *g, *b),
1220       l  = lum(*r, *g, *b);
1221 
1222     auto clip = [=](F c) {
1223         c = if_then_else(mn >= 0, c, l + (c - l) * (    l) / (l - mn)   );
1224         c = if_then_else(mx >  a,    l + (c - l) * (a - l) / (mx - l), c);
1225         c = max(c, 0);  // Sometimes without this we may dip just a little negative.
1226         return c;
1227     };
1228     *r = clip(*r);
1229     *g = clip(*g);
1230     *b = clip(*b);
1231 }
1232 
STAGE(hue,Ctx::None)1233 STAGE(hue, Ctx::None) {
1234     F R = r*a,
1235       G = g*a,
1236       B = b*a;
1237 
1238     set_sat(&R, &G, &B, sat(dr,dg,db)*a);
1239     set_lum(&R, &G, &B, lum(dr,dg,db)*a);
1240     clip_color(&R,&G,&B, a*da);
1241 
1242     r = r*inv(da) + dr*inv(a) + R;
1243     g = g*inv(da) + dg*inv(a) + G;
1244     b = b*inv(da) + db*inv(a) + B;
1245     a = a + da - a*da;
1246 }
STAGE(saturation,Ctx::None)1247 STAGE(saturation, Ctx::None) {
1248     F R = dr*a,
1249       G = dg*a,
1250       B = db*a;
1251 
1252     set_sat(&R, &G, &B, sat( r, g, b)*da);
1253     set_lum(&R, &G, &B, lum(dr,dg,db)* a);  // (This is not redundant.)
1254     clip_color(&R,&G,&B, a*da);
1255 
1256     r = r*inv(da) + dr*inv(a) + R;
1257     g = g*inv(da) + dg*inv(a) + G;
1258     b = b*inv(da) + db*inv(a) + B;
1259     a = a + da - a*da;
1260 }
STAGE(color,Ctx::None)1261 STAGE(color, Ctx::None) {
1262     F R = r*da,
1263       G = g*da,
1264       B = b*da;
1265 
1266     set_lum(&R, &G, &B, lum(dr,dg,db)*a);
1267     clip_color(&R,&G,&B, a*da);
1268 
1269     r = r*inv(da) + dr*inv(a) + R;
1270     g = g*inv(da) + dg*inv(a) + G;
1271     b = b*inv(da) + db*inv(a) + B;
1272     a = a + da - a*da;
1273 }
STAGE(luminosity,Ctx::None)1274 STAGE(luminosity, Ctx::None) {
1275     F R = dr*a,
1276       G = dg*a,
1277       B = db*a;
1278 
1279     set_lum(&R, &G, &B, lum(r,g,b)*da);
1280     clip_color(&R,&G,&B, a*da);
1281 
1282     r = r*inv(da) + dr*inv(a) + R;
1283     g = g*inv(da) + dg*inv(a) + G;
1284     b = b*inv(da) + db*inv(a) + B;
1285     a = a + da - a*da;
1286 }
1287 
STAGE(srcover_rgba_8888,const SkRasterPipeline_MemoryCtx * ctx)1288 STAGE(srcover_rgba_8888, const SkRasterPipeline_MemoryCtx* ctx) {
1289     auto ptr = ptr_at_xy<uint32_t>(ctx, dx,dy);
1290 
1291     U32 dst = load<U32>(ptr, tail);
1292     dr = cast((dst      ) & 0xff);
1293     dg = cast((dst >>  8) & 0xff);
1294     db = cast((dst >> 16) & 0xff);
1295     da = cast((dst >> 24)       );
1296     // {dr,dg,db,da} are in [0,255]
1297     // { r, g, b, a} are in [0,  1] (but may be out of gamut)
1298 
1299     r = mad(dr, inv(a), r*255.0f);
1300     g = mad(dg, inv(a), g*255.0f);
1301     b = mad(db, inv(a), b*255.0f);
1302     a = mad(da, inv(a), a*255.0f);
1303     // { r, g, b, a} are now in [0,255]  (but may be out of gamut)
1304 
1305     // to_unorm() clamps back to gamut.  Scaling by 1 since we're already 255-biased.
1306     dst = to_unorm(r, 1, 255)
1307         | to_unorm(g, 1, 255) <<  8
1308         | to_unorm(b, 1, 255) << 16
1309         | to_unorm(a, 1, 255) << 24;
1310     store(ptr, dst, tail);
1311 }
1312 
STAGE(clamp_0,Ctx::None)1313 STAGE(clamp_0, Ctx::None) {
1314     r = max(r, 0);
1315     g = max(g, 0);
1316     b = max(b, 0);
1317     a = max(a, 0);
1318 }
1319 
STAGE(clamp_1,Ctx::None)1320 STAGE(clamp_1, Ctx::None) {
1321     r = min(r, 1.0f);
1322     g = min(g, 1.0f);
1323     b = min(b, 1.0f);
1324     a = min(a, 1.0f);
1325 }
1326 
STAGE(clamp_a,Ctx::None)1327 STAGE(clamp_a, Ctx::None) {
1328     a = min(a, 1.0f);
1329     r = min(r, a);
1330     g = min(g, a);
1331     b = min(b, a);
1332 }
1333 
STAGE(clamp_a_dst,Ctx::None)1334 STAGE(clamp_a_dst, Ctx::None) {
1335     da = min(da, 1.0f);
1336     dr = min(dr, da);
1337     dg = min(dg, da);
1338     db = min(db, da);
1339 }
1340 
STAGE(clamp_gamut,Ctx::None)1341 STAGE(clamp_gamut, Ctx::None) {
1342     // If you're using this stage, a should already be in [0,1].
1343     r = min(max(r, 0), a);
1344     g = min(max(g, 0), a);
1345     b = min(max(b, 0), a);
1346 }
1347 
STAGE(set_rgb,const float * rgb)1348 STAGE(set_rgb, const float* rgb) {
1349     r = rgb[0];
1350     g = rgb[1];
1351     b = rgb[2];
1352 }
STAGE(unbounded_set_rgb,const float * rgb)1353 STAGE(unbounded_set_rgb, const float* rgb) {
1354     r = rgb[0];
1355     g = rgb[1];
1356     b = rgb[2];
1357 }
1358 
STAGE(swap_rb,Ctx::None)1359 STAGE(swap_rb, Ctx::None) {
1360     auto tmp = r;
1361     r = b;
1362     b = tmp;
1363 }
STAGE(swap_rb_dst,Ctx::None)1364 STAGE(swap_rb_dst, Ctx::None) {
1365     auto tmp = dr;
1366     dr = db;
1367     db = tmp;
1368 }
1369 
STAGE(move_src_dst,Ctx::None)1370 STAGE(move_src_dst, Ctx::None) {
1371     dr = r;
1372     dg = g;
1373     db = b;
1374     da = a;
1375 }
STAGE(move_dst_src,Ctx::None)1376 STAGE(move_dst_src, Ctx::None) {
1377     r = dr;
1378     g = dg;
1379     b = db;
1380     a = da;
1381 }
1382 
STAGE(premul,Ctx::None)1383 STAGE(premul, Ctx::None) {
1384     r = r * a;
1385     g = g * a;
1386     b = b * a;
1387 }
STAGE(premul_dst,Ctx::None)1388 STAGE(premul_dst, Ctx::None) {
1389     dr = dr * da;
1390     dg = dg * da;
1391     db = db * da;
1392 }
STAGE(unpremul,Ctx::None)1393 STAGE(unpremul, Ctx::None) {
1394     float inf = bit_cast<float>(0x7f800000);
1395     auto scale = if_then_else(1.0f/a < inf, 1.0f/a, 0);
1396     r *= scale;
1397     g *= scale;
1398     b *= scale;
1399 }
1400 
STAGE(force_opaque,Ctx::None)1401 STAGE(force_opaque    , Ctx::None) {  a = 1; }
STAGE(force_opaque_dst,Ctx::None)1402 STAGE(force_opaque_dst, Ctx::None) { da = 1; }
1403 
STAGE(rgb_to_hsl,Ctx::None)1404 STAGE(rgb_to_hsl, Ctx::None) {
1405     F mx = max(r,g,b),
1406       mn = min(r,g,b),
1407       d = mx - mn,
1408       d_rcp = 1.0f / d;
1409 
1410     F h = (1/6.0f) *
1411           if_then_else(mx == mn, 0,
1412           if_then_else(mx ==  r, (g-b)*d_rcp + if_then_else(g < b, 6.0f, 0),
1413           if_then_else(mx ==  g, (b-r)*d_rcp + 2.0f,
1414                                  (r-g)*d_rcp + 4.0f)));
1415 
1416     F l = (mx + mn) * 0.5f;
1417     F s = if_then_else(mx == mn, 0,
1418                        d / if_then_else(l > 0.5f, 2.0f-mx-mn, mx+mn));
1419 
1420     r = h;
1421     g = s;
1422     b = l;
1423 }
STAGE(hsl_to_rgb,Ctx::None)1424 STAGE(hsl_to_rgb, Ctx::None) {
1425     F h = r,
1426       s = g,
1427       l = b;
1428 
1429     F q = l + if_then_else(l >= 0.5f, s - l*s, l*s),
1430       p = 2.0f*l - q;
1431 
1432     auto hue_to_rgb = [&](F t) {
1433         t = fract(t);
1434 
1435         F r = p;
1436         r = if_then_else(t >= 4/6.0f, r, p + (q-p)*(4.0f - 6.0f*t));
1437         r = if_then_else(t >= 3/6.0f, r, q);
1438         r = if_then_else(t >= 1/6.0f, r, p + (q-p)*(       6.0f*t));
1439         return r;
1440     };
1441 
1442     r = if_then_else(s == 0, l, hue_to_rgb(h + (1/3.0f)));
1443     g = if_then_else(s == 0, l, hue_to_rgb(h           ));
1444     b = if_then_else(s == 0, l, hue_to_rgb(h - (1/3.0f)));
1445 }
1446 
1447 // Derive alpha's coverage from rgb coverage and the values of src and dst alpha.
alpha_coverage_from_rgb_coverage(F a,F da,F cr,F cg,F cb)1448 SI F alpha_coverage_from_rgb_coverage(F a, F da, F cr, F cg, F cb) {
1449     return if_then_else(a < da, min(cr,cg,cb)
1450                               , max(cr,cg,cb));
1451 }
1452 
STAGE(scale_1_float,const float * c)1453 STAGE(scale_1_float, const float* c) {
1454     r = r * *c;
1455     g = g * *c;
1456     b = b * *c;
1457     a = a * *c;
1458 }
STAGE(scale_u8,const SkRasterPipeline_MemoryCtx * ctx)1459 STAGE(scale_u8, const SkRasterPipeline_MemoryCtx* ctx) {
1460     auto ptr = ptr_at_xy<const uint8_t>(ctx, dx,dy);
1461 
1462     auto scales = load<U8>(ptr, tail);
1463     auto c = from_byte(scales);
1464 
1465     r = r * c;
1466     g = g * c;
1467     b = b * c;
1468     a = a * c;
1469 }
STAGE(scale_565,const SkRasterPipeline_MemoryCtx * ctx)1470 STAGE(scale_565, const SkRasterPipeline_MemoryCtx* ctx) {
1471     auto ptr = ptr_at_xy<const uint16_t>(ctx, dx,dy);
1472 
1473     F cr,cg,cb;
1474     from_565(load<U16>(ptr, tail), &cr, &cg, &cb);
1475 
1476     F ca = alpha_coverage_from_rgb_coverage(a,da, cr,cg,cb);
1477 
1478     r = r * cr;
1479     g = g * cg;
1480     b = b * cb;
1481     a = a * ca;
1482 }
1483 
lerp(F from,F to,F t)1484 SI F lerp(F from, F to, F t) {
1485     return mad(to-from, t, from);
1486 }
1487 
STAGE(lerp_1_float,const float * c)1488 STAGE(lerp_1_float, const float* c) {
1489     r = lerp(dr, r, *c);
1490     g = lerp(dg, g, *c);
1491     b = lerp(db, b, *c);
1492     a = lerp(da, a, *c);
1493 }
STAGE(lerp_u8,const SkRasterPipeline_MemoryCtx * ctx)1494 STAGE(lerp_u8, const SkRasterPipeline_MemoryCtx* ctx) {
1495     auto ptr = ptr_at_xy<const uint8_t>(ctx, dx,dy);
1496 
1497     auto scales = load<U8>(ptr, tail);
1498     auto c = from_byte(scales);
1499 
1500     r = lerp(dr, r, c);
1501     g = lerp(dg, g, c);
1502     b = lerp(db, b, c);
1503     a = lerp(da, a, c);
1504 }
STAGE(lerp_565,const SkRasterPipeline_MemoryCtx * ctx)1505 STAGE(lerp_565, const SkRasterPipeline_MemoryCtx* ctx) {
1506     auto ptr = ptr_at_xy<const uint16_t>(ctx, dx,dy);
1507 
1508     F cr,cg,cb;
1509     from_565(load<U16>(ptr, tail), &cr, &cg, &cb);
1510 
1511     F ca = alpha_coverage_from_rgb_coverage(a,da, cr,cg,cb);
1512 
1513     r = lerp(dr, r, cr);
1514     g = lerp(dg, g, cg);
1515     b = lerp(db, b, cb);
1516     a = lerp(da, a, ca);
1517 }
1518 
STAGE(emboss,const SkRasterPipeline_EmbossCtx * ctx)1519 STAGE(emboss, const SkRasterPipeline_EmbossCtx* ctx) {
1520     auto mptr = ptr_at_xy<const uint8_t>(&ctx->mul, dx,dy),
1521          aptr = ptr_at_xy<const uint8_t>(&ctx->add, dx,dy);
1522 
1523     F mul = from_byte(load<U8>(mptr, tail)),
1524       add = from_byte(load<U8>(aptr, tail));
1525 
1526     r = mad(r, mul, add);
1527     g = mad(g, mul, add);
1528     b = mad(b, mul, add);
1529 }
1530 
STAGE(byte_tables,const void * ctx)1531 STAGE(byte_tables, const void* ctx) {  // TODO: rename Tables SkRasterPipeline_ByteTablesCtx
1532     struct Tables { const uint8_t *r, *g, *b, *a; };
1533     auto tables = (const Tables*)ctx;
1534 
1535     r = from_byte(gather(tables->r, to_unorm(r, 255)));
1536     g = from_byte(gather(tables->g, to_unorm(g, 255)));
1537     b = from_byte(gather(tables->b, to_unorm(b, 255)));
1538     a = from_byte(gather(tables->a, to_unorm(a, 255)));
1539 }
1540 
strip_sign(F x,U32 * sign)1541 SI F strip_sign(F x, U32* sign) {
1542     U32 bits = bit_cast<U32>(x);
1543     *sign = bits & 0x80000000;
1544     return bit_cast<F>(bits ^ *sign);
1545 }
1546 
apply_sign(F x,U32 sign)1547 SI F apply_sign(F x, U32 sign) {
1548     return bit_cast<F>(sign | bit_cast<U32>(x));
1549 }
1550 
STAGE(parametric,const skcms_TransferFunction * ctx)1551 STAGE(parametric, const skcms_TransferFunction* ctx) {
1552     auto fn = [&](F v) {
1553         U32 sign;
1554         v = strip_sign(v, &sign);
1555 
1556         F r = if_then_else(v <= ctx->d, mad(ctx->c, v, ctx->f)
1557                                       , approx_powf(mad(ctx->a, v, ctx->b), ctx->g) + ctx->e);
1558         return apply_sign(r, sign);
1559     };
1560     r = fn(r);
1561     g = fn(g);
1562     b = fn(b);
1563 }
1564 
STAGE(gamma,const float * G)1565 STAGE(gamma, const float* G) {
1566     auto fn = [&](F v) {
1567         U32 sign;
1568         v = strip_sign(v, &sign);
1569         return apply_sign(approx_powf(v, *G), sign);
1570     };
1571     r = fn(r);
1572     g = fn(g);
1573     b = fn(b);
1574 }
1575 
STAGE(from_srgb,Ctx::None)1576 STAGE(from_srgb, Ctx::None) {
1577     auto fn = [](F s) {
1578         U32 sign;
1579         s = strip_sign(s, &sign);
1580         auto lo = s * (1/12.92f);
1581         auto hi = mad(s*s, mad(s, 0.3000f, 0.6975f), 0.0025f);
1582         return apply_sign(if_then_else(s < 0.055f, lo, hi), sign);
1583     };
1584     r = fn(r);
1585     g = fn(g);
1586     b = fn(b);
1587 }
STAGE(to_srgb,Ctx::None)1588 STAGE(to_srgb, Ctx::None) {
1589     auto fn = [](F l) {
1590         U32 sign;
1591         l = strip_sign(l, &sign);
1592         // We tweak c and d for each instruction set to make sure fn(1) is exactly 1.
1593     #if defined(JUMPER_IS_AVX512)
1594         const float c = 1.130026340485f,
1595                     d = 0.141387879848f;
1596     #elif defined(JUMPER_IS_SSE2) || defined(JUMPER_IS_SSE41) || \
1597           defined(JUMPER_IS_AVX ) || defined(JUMPER_IS_HSW )
1598         const float c = 1.130048394203f,
1599                     d = 0.141357362270f;
1600     #elif defined(JUMPER_IS_NEON)
1601         const float c = 1.129999995232f,
1602                     d = 0.141381442547f;
1603     #else
1604         const float c = 1.129999995232f,
1605                     d = 0.141377761960f;
1606     #endif
1607         F t = rsqrt(l);
1608         auto lo = l * 12.92f;
1609         auto hi = mad(t, mad(t, -0.0024542345f, 0.013832027f), c)
1610                 * rcp(d + t);
1611         return apply_sign(if_then_else(l < 0.00465985f, lo, hi), sign);
1612     };
1613     r = fn(r);
1614     g = fn(g);
1615     b = fn(b);
1616 }
1617 
STAGE(load_a8,const SkRasterPipeline_MemoryCtx * ctx)1618 STAGE(load_a8, const SkRasterPipeline_MemoryCtx* ctx) {
1619     auto ptr = ptr_at_xy<const uint8_t>(ctx, dx,dy);
1620 
1621     r = g = b = 0.0f;
1622     a = from_byte(load<U8>(ptr, tail));
1623 }
STAGE(load_a8_dst,const SkRasterPipeline_MemoryCtx * ctx)1624 STAGE(load_a8_dst, const SkRasterPipeline_MemoryCtx* ctx) {
1625     auto ptr = ptr_at_xy<const uint8_t>(ctx, dx,dy);
1626 
1627     dr = dg = db = 0.0f;
1628     da = from_byte(load<U8>(ptr, tail));
1629 }
STAGE(gather_a8,const SkRasterPipeline_GatherCtx * ctx)1630 STAGE(gather_a8, const SkRasterPipeline_GatherCtx* ctx) {
1631     const uint8_t* ptr;
1632     U32 ix = ix_and_ptr(&ptr, ctx, r,g);
1633     r = g = b = 0.0f;
1634     a = from_byte(gather(ptr, ix));
1635 }
STAGE(store_a8,const SkRasterPipeline_MemoryCtx * ctx)1636 STAGE(store_a8, const SkRasterPipeline_MemoryCtx* ctx) {
1637     auto ptr = ptr_at_xy<uint8_t>(ctx, dx,dy);
1638 
1639     U8 packed = pack(pack(to_unorm(a, 255)));
1640     store(ptr, packed, tail);
1641 }
1642 
STAGE(load_565,const SkRasterPipeline_MemoryCtx * ctx)1643 STAGE(load_565, const SkRasterPipeline_MemoryCtx* ctx) {
1644     auto ptr = ptr_at_xy<const uint16_t>(ctx, dx,dy);
1645 
1646     from_565(load<U16>(ptr, tail), &r,&g,&b);
1647     a = 1.0f;
1648 }
STAGE(load_565_dst,const SkRasterPipeline_MemoryCtx * ctx)1649 STAGE(load_565_dst, const SkRasterPipeline_MemoryCtx* ctx) {
1650     auto ptr = ptr_at_xy<const uint16_t>(ctx, dx,dy);
1651 
1652     from_565(load<U16>(ptr, tail), &dr,&dg,&db);
1653     da = 1.0f;
1654 }
STAGE(gather_565,const SkRasterPipeline_GatherCtx * ctx)1655 STAGE(gather_565, const SkRasterPipeline_GatherCtx* ctx) {
1656     const uint16_t* ptr;
1657     U32 ix = ix_and_ptr(&ptr, ctx, r,g);
1658     from_565(gather(ptr, ix), &r,&g,&b);
1659     a = 1.0f;
1660 }
STAGE(store_565,const SkRasterPipeline_MemoryCtx * ctx)1661 STAGE(store_565, const SkRasterPipeline_MemoryCtx* ctx) {
1662     auto ptr = ptr_at_xy<uint16_t>(ctx, dx,dy);
1663 
1664     U16 px = pack( to_unorm(r, 31) << 11
1665                  | to_unorm(g, 63) <<  5
1666                  | to_unorm(b, 31)      );
1667     store(ptr, px, tail);
1668 }
1669 
STAGE(load_4444,const SkRasterPipeline_MemoryCtx * ctx)1670 STAGE(load_4444, const SkRasterPipeline_MemoryCtx* ctx) {
1671     auto ptr = ptr_at_xy<const uint16_t>(ctx, dx,dy);
1672     from_4444(load<U16>(ptr, tail), &r,&g,&b,&a);
1673 }
STAGE(load_4444_dst,const SkRasterPipeline_MemoryCtx * ctx)1674 STAGE(load_4444_dst, const SkRasterPipeline_MemoryCtx* ctx) {
1675     auto ptr = ptr_at_xy<const uint16_t>(ctx, dx,dy);
1676     from_4444(load<U16>(ptr, tail), &dr,&dg,&db,&da);
1677 }
STAGE(gather_4444,const SkRasterPipeline_GatherCtx * ctx)1678 STAGE(gather_4444, const SkRasterPipeline_GatherCtx* ctx) {
1679     const uint16_t* ptr;
1680     U32 ix = ix_and_ptr(&ptr, ctx, r,g);
1681     from_4444(gather(ptr, ix), &r,&g,&b,&a);
1682 }
STAGE(store_4444,const SkRasterPipeline_MemoryCtx * ctx)1683 STAGE(store_4444, const SkRasterPipeline_MemoryCtx* ctx) {
1684     auto ptr = ptr_at_xy<uint16_t>(ctx, dx,dy);
1685     U16 px = pack( to_unorm(r, 15) << 12
1686                  | to_unorm(g, 15) <<  8
1687                  | to_unorm(b, 15) <<  4
1688                  | to_unorm(a, 15)      );
1689     store(ptr, px, tail);
1690 }
1691 
STAGE(load_8888,const SkRasterPipeline_MemoryCtx * ctx)1692 STAGE(load_8888, const SkRasterPipeline_MemoryCtx* ctx) {
1693     auto ptr = ptr_at_xy<const uint32_t>(ctx, dx,dy);
1694     from_8888(load<U32>(ptr, tail), &r,&g,&b,&a);
1695 }
STAGE(load_8888_dst,const SkRasterPipeline_MemoryCtx * ctx)1696 STAGE(load_8888_dst, const SkRasterPipeline_MemoryCtx* ctx) {
1697     auto ptr = ptr_at_xy<const uint32_t>(ctx, dx,dy);
1698     from_8888(load<U32>(ptr, tail), &dr,&dg,&db,&da);
1699 }
STAGE(gather_8888,const SkRasterPipeline_GatherCtx * ctx)1700 STAGE(gather_8888, const SkRasterPipeline_GatherCtx* ctx) {
1701     const uint32_t* ptr;
1702     U32 ix = ix_and_ptr(&ptr, ctx, r,g);
1703     from_8888(gather(ptr, ix), &r,&g,&b,&a);
1704 }
STAGE(store_8888,const SkRasterPipeline_MemoryCtx * ctx)1705 STAGE(store_8888, const SkRasterPipeline_MemoryCtx* ctx) {
1706     auto ptr = ptr_at_xy<uint32_t>(ctx, dx,dy);
1707 
1708     U32 px = to_unorm(r, 255)
1709            | to_unorm(g, 255) <<  8
1710            | to_unorm(b, 255) << 16
1711            | to_unorm(a, 255) << 24;
1712     store(ptr, px, tail);
1713 }
1714 
STAGE(load_1010102,const SkRasterPipeline_MemoryCtx * ctx)1715 STAGE(load_1010102, const SkRasterPipeline_MemoryCtx* ctx) {
1716     auto ptr = ptr_at_xy<const uint32_t>(ctx, dx,dy);
1717     from_1010102(load<U32>(ptr, tail), &r,&g,&b,&a);
1718 }
STAGE(load_1010102_dst,const SkRasterPipeline_MemoryCtx * ctx)1719 STAGE(load_1010102_dst, const SkRasterPipeline_MemoryCtx* ctx) {
1720     auto ptr = ptr_at_xy<const uint32_t>(ctx, dx,dy);
1721     from_1010102(load<U32>(ptr, tail), &dr,&dg,&db,&da);
1722 }
STAGE(gather_1010102,const SkRasterPipeline_GatherCtx * ctx)1723 STAGE(gather_1010102, const SkRasterPipeline_GatherCtx* ctx) {
1724     const uint32_t* ptr;
1725     U32 ix = ix_and_ptr(&ptr, ctx, r,g);
1726     from_1010102(gather(ptr, ix), &r,&g,&b,&a);
1727 }
STAGE(store_1010102,const SkRasterPipeline_MemoryCtx * ctx)1728 STAGE(store_1010102, const SkRasterPipeline_MemoryCtx* ctx) {
1729     auto ptr = ptr_at_xy<uint32_t>(ctx, dx,dy);
1730 
1731     U32 px = to_unorm(r, 1023)
1732            | to_unorm(g, 1023) << 10
1733            | to_unorm(b, 1023) << 20
1734            | to_unorm(a,    3) << 30;
1735     store(ptr, px, tail);
1736 }
1737 
STAGE(load_f16,const SkRasterPipeline_MemoryCtx * ctx)1738 STAGE(load_f16, const SkRasterPipeline_MemoryCtx* ctx) {
1739     auto ptr = ptr_at_xy<const uint64_t>(ctx, dx,dy);
1740 
1741     U16 R,G,B,A;
1742     load4((const uint16_t*)ptr,tail, &R,&G,&B,&A);
1743     r = from_half(R);
1744     g = from_half(G);
1745     b = from_half(B);
1746     a = from_half(A);
1747 }
STAGE(load_f16_dst,const SkRasterPipeline_MemoryCtx * ctx)1748 STAGE(load_f16_dst, const SkRasterPipeline_MemoryCtx* ctx) {
1749     auto ptr = ptr_at_xy<const uint64_t>(ctx, dx,dy);
1750 
1751     U16 R,G,B,A;
1752     load4((const uint16_t*)ptr,tail, &R,&G,&B,&A);
1753     dr = from_half(R);
1754     dg = from_half(G);
1755     db = from_half(B);
1756     da = from_half(A);
1757 }
STAGE(gather_f16,const SkRasterPipeline_GatherCtx * ctx)1758 STAGE(gather_f16, const SkRasterPipeline_GatherCtx* ctx) {
1759     const uint64_t* ptr;
1760     U32 ix = ix_and_ptr(&ptr, ctx, r,g);
1761     auto px = gather(ptr, ix);
1762 
1763     U16 R,G,B,A;
1764     load4((const uint16_t*)&px,0, &R,&G,&B,&A);
1765     r = from_half(R);
1766     g = from_half(G);
1767     b = from_half(B);
1768     a = from_half(A);
1769 }
STAGE(store_f16,const SkRasterPipeline_MemoryCtx * ctx)1770 STAGE(store_f16, const SkRasterPipeline_MemoryCtx* ctx) {
1771     auto ptr = ptr_at_xy<uint64_t>(ctx, dx,dy);
1772     store4((uint16_t*)ptr,tail, to_half(r)
1773                               , to_half(g)
1774                               , to_half(b)
1775                               , to_half(a));
1776 }
1777 
STAGE(store_u16_be,const SkRasterPipeline_MemoryCtx * ctx)1778 STAGE(store_u16_be, const SkRasterPipeline_MemoryCtx* ctx) {
1779     auto ptr = ptr_at_xy<uint16_t>(ctx, 4*dx,dy);
1780 
1781     U16 R = bswap(pack(to_unorm(r, 65535))),
1782         G = bswap(pack(to_unorm(g, 65535))),
1783         B = bswap(pack(to_unorm(b, 65535))),
1784         A = bswap(pack(to_unorm(a, 65535)));
1785 
1786     store4(ptr,tail, R,G,B,A);
1787 }
1788 
STAGE(load_f32,const SkRasterPipeline_MemoryCtx * ctx)1789 STAGE(load_f32, const SkRasterPipeline_MemoryCtx* ctx) {
1790     auto ptr = ptr_at_xy<const float>(ctx, 4*dx,4*dy);
1791     load4(ptr,tail, &r,&g,&b,&a);
1792 }
STAGE(load_f32_dst,const SkRasterPipeline_MemoryCtx * ctx)1793 STAGE(load_f32_dst, const SkRasterPipeline_MemoryCtx* ctx) {
1794     auto ptr = ptr_at_xy<const float>(ctx, 4*dx,4*dy);
1795     load4(ptr,tail, &dr,&dg,&db,&da);
1796 }
STAGE(gather_f32,const SkRasterPipeline_GatherCtx * ctx)1797 STAGE(gather_f32, const SkRasterPipeline_GatherCtx* ctx) {
1798     const float* ptr;
1799     U32 ix = ix_and_ptr(&ptr, ctx, r,g);
1800     r = gather(ptr, 4*ix + 0);
1801     g = gather(ptr, 4*ix + 1);
1802     b = gather(ptr, 4*ix + 2);
1803     a = gather(ptr, 4*ix + 3);
1804 }
STAGE(store_f32,const SkRasterPipeline_MemoryCtx * ctx)1805 STAGE(store_f32, const SkRasterPipeline_MemoryCtx* ctx) {
1806     auto ptr = ptr_at_xy<float>(ctx, 4*dx,4*dy);
1807     store4(ptr,tail, r,g,b,a);
1808 }
1809 
exclusive_repeat(F v,const SkRasterPipeline_TileCtx * ctx)1810 SI F exclusive_repeat(F v, const SkRasterPipeline_TileCtx* ctx) {
1811     return v - floor_(v*ctx->invScale)*ctx->scale;
1812 }
exclusive_mirror(F v,const SkRasterPipeline_TileCtx * ctx)1813 SI F exclusive_mirror(F v, const SkRasterPipeline_TileCtx* ctx) {
1814     auto limit = ctx->scale;
1815     auto invLimit = ctx->invScale;
1816     return abs_( (v-limit) - (limit+limit)*floor_((v-limit)*(invLimit*0.5f)) - limit );
1817 }
1818 // Tile x or y to [0,limit) == [0,limit - 1 ulp] (think, sampling from images).
1819 // The gather stages will hard clamp the output of these stages to [0,limit)...
1820 // we just need to do the basic repeat or mirroring.
STAGE(repeat_x,const SkRasterPipeline_TileCtx * ctx)1821 STAGE(repeat_x, const SkRasterPipeline_TileCtx* ctx) { r = exclusive_repeat(r, ctx); }
STAGE(repeat_y,const SkRasterPipeline_TileCtx * ctx)1822 STAGE(repeat_y, const SkRasterPipeline_TileCtx* ctx) { g = exclusive_repeat(g, ctx); }
STAGE(mirror_x,const SkRasterPipeline_TileCtx * ctx)1823 STAGE(mirror_x, const SkRasterPipeline_TileCtx* ctx) { r = exclusive_mirror(r, ctx); }
STAGE(mirror_y,const SkRasterPipeline_TileCtx * ctx)1824 STAGE(mirror_y, const SkRasterPipeline_TileCtx* ctx) { g = exclusive_mirror(g, ctx); }
1825 
1826 // Clamp x to [0,1], both sides inclusive (think, gradients).
1827 // Even repeat and mirror funnel through a clamp to handle bad inputs like +Inf, NaN.
clamp_01(F v)1828 SI F clamp_01(F v) { return min(max(0, v), 1); }
1829 
STAGE(clamp_x_1,Ctx::None)1830 STAGE( clamp_x_1, Ctx::None) { r = clamp_01(r); }
STAGE(repeat_x_1,Ctx::None)1831 STAGE(repeat_x_1, Ctx::None) { r = clamp_01(r - floor_(r)); }
STAGE(mirror_x_1,Ctx::None)1832 STAGE(mirror_x_1, Ctx::None) { r = clamp_01(abs_( (r-1.0f) - two(floor_((r-1.0f)*0.5f)) - 1.0f )); }
1833 
1834 // Decal stores a 32bit mask after checking the coordinate (x and/or y) against its domain:
1835 //      mask == 0x00000000 if the coordinate(s) are out of bounds
1836 //      mask == 0xFFFFFFFF if the coordinate(s) are in bounds
1837 // After the gather stage, the r,g,b,a values are AND'd with this mask, setting them to 0
1838 // if either of the coordinates were out of bounds.
1839 
STAGE(decal_x,SkRasterPipeline_DecalTileCtx * ctx)1840 STAGE(decal_x, SkRasterPipeline_DecalTileCtx* ctx) {
1841     auto w = ctx->limit_x;
1842     unaligned_store(ctx->mask, cond_to_mask((0 <= r) & (r < w)));
1843 }
STAGE(decal_y,SkRasterPipeline_DecalTileCtx * ctx)1844 STAGE(decal_y, SkRasterPipeline_DecalTileCtx* ctx) {
1845     auto h = ctx->limit_y;
1846     unaligned_store(ctx->mask, cond_to_mask((0 <= g) & (g < h)));
1847 }
STAGE(decal_x_and_y,SkRasterPipeline_DecalTileCtx * ctx)1848 STAGE(decal_x_and_y, SkRasterPipeline_DecalTileCtx* ctx) {
1849     auto w = ctx->limit_x;
1850     auto h = ctx->limit_y;
1851     unaligned_store(ctx->mask,
1852                     cond_to_mask((0 <= r) & (r < w) & (0 <= g) & (g < h)));
1853 }
STAGE(check_decal_mask,SkRasterPipeline_DecalTileCtx * ctx)1854 STAGE(check_decal_mask, SkRasterPipeline_DecalTileCtx* ctx) {
1855     auto mask = unaligned_load<U32>(ctx->mask);
1856     r = bit_cast<F>( bit_cast<U32>(r) & mask );
1857     g = bit_cast<F>( bit_cast<U32>(g) & mask );
1858     b = bit_cast<F>( bit_cast<U32>(b) & mask );
1859     a = bit_cast<F>( bit_cast<U32>(a) & mask );
1860 }
1861 
STAGE(alpha_to_gray,Ctx::None)1862 STAGE(alpha_to_gray, Ctx::None) {
1863     r = g = b = a;
1864     a = 1;
1865 }
STAGE(alpha_to_gray_dst,Ctx::None)1866 STAGE(alpha_to_gray_dst, Ctx::None) {
1867     dr = dg = db = da;
1868     da = 1;
1869 }
STAGE(luminance_to_alpha,Ctx::None)1870 STAGE(luminance_to_alpha, Ctx::None) {
1871     a = r*0.2126f + g*0.7152f + b*0.0722f;
1872     r = g = b = 0;
1873 }
1874 
STAGE(matrix_translate,const float * m)1875 STAGE(matrix_translate, const float* m) {
1876     r += m[0];
1877     g += m[1];
1878 }
STAGE(matrix_scale_translate,const float * m)1879 STAGE(matrix_scale_translate, const float* m) {
1880     r = mad(r,m[0], m[2]);
1881     g = mad(g,m[1], m[3]);
1882 }
STAGE(matrix_2x3,const float * m)1883 STAGE(matrix_2x3, const float* m) {
1884     auto R = mad(r,m[0], mad(g,m[2], m[4])),
1885          G = mad(r,m[1], mad(g,m[3], m[5]));
1886     r = R;
1887     g = G;
1888 }
STAGE(matrix_3x3,const float * m)1889 STAGE(matrix_3x3, const float* m) {
1890     auto R = mad(r,m[0], mad(g,m[3], b*m[6])),
1891          G = mad(r,m[1], mad(g,m[4], b*m[7])),
1892          B = mad(r,m[2], mad(g,m[5], b*m[8]));
1893     r = R;
1894     g = G;
1895     b = B;
1896 }
STAGE(matrix_3x4,const float * m)1897 STAGE(matrix_3x4, const float* m) {
1898     auto R = mad(r,m[0], mad(g,m[3], mad(b,m[6], m[ 9]))),
1899          G = mad(r,m[1], mad(g,m[4], mad(b,m[7], m[10]))),
1900          B = mad(r,m[2], mad(g,m[5], mad(b,m[8], m[11])));
1901     r = R;
1902     g = G;
1903     b = B;
1904 }
STAGE(matrix_4x5,const float * m)1905 STAGE(matrix_4x5, const float* m) {
1906     auto R = mad(r,m[0], mad(g,m[4], mad(b,m[ 8], mad(a,m[12], m[16])))),
1907          G = mad(r,m[1], mad(g,m[5], mad(b,m[ 9], mad(a,m[13], m[17])))),
1908          B = mad(r,m[2], mad(g,m[6], mad(b,m[10], mad(a,m[14], m[18])))),
1909          A = mad(r,m[3], mad(g,m[7], mad(b,m[11], mad(a,m[15], m[19]))));
1910     r = R;
1911     g = G;
1912     b = B;
1913     a = A;
1914 }
STAGE(matrix_4x3,const float * m)1915 STAGE(matrix_4x3, const float* m) {
1916     auto X = r,
1917          Y = g;
1918 
1919     r = mad(X, m[0], mad(Y, m[4], m[ 8]));
1920     g = mad(X, m[1], mad(Y, m[5], m[ 9]));
1921     b = mad(X, m[2], mad(Y, m[6], m[10]));
1922     a = mad(X, m[3], mad(Y, m[7], m[11]));
1923 }
STAGE(matrix_perspective,const float * m)1924 STAGE(matrix_perspective, const float* m) {
1925     // N.B. Unlike the other matrix_ stages, this matrix is row-major.
1926     auto R = mad(r,m[0], mad(g,m[1], m[2])),
1927          G = mad(r,m[3], mad(g,m[4], m[5])),
1928          Z = mad(r,m[6], mad(g,m[7], m[8]));
1929     r = R * rcp(Z);
1930     g = G * rcp(Z);
1931 }
1932 
gradient_lookup(const SkRasterPipeline_GradientCtx * c,U32 idx,F t,F * r,F * g,F * b,F * a)1933 SI void gradient_lookup(const SkRasterPipeline_GradientCtx* c, U32 idx, F t,
1934                         F* r, F* g, F* b, F* a) {
1935     F fr, br, fg, bg, fb, bb, fa, ba;
1936 #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
1937     if (c->stopCount <=8) {
1938         fr = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[0]), idx);
1939         br = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[0]), idx);
1940         fg = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[1]), idx);
1941         bg = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[1]), idx);
1942         fb = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[2]), idx);
1943         bb = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[2]), idx);
1944         fa = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[3]), idx);
1945         ba = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[3]), idx);
1946     } else
1947 #endif
1948     {
1949         fr = gather(c->fs[0], idx);
1950         br = gather(c->bs[0], idx);
1951         fg = gather(c->fs[1], idx);
1952         bg = gather(c->bs[1], idx);
1953         fb = gather(c->fs[2], idx);
1954         bb = gather(c->bs[2], idx);
1955         fa = gather(c->fs[3], idx);
1956         ba = gather(c->bs[3], idx);
1957     }
1958 
1959     *r = mad(t, fr, br);
1960     *g = mad(t, fg, bg);
1961     *b = mad(t, fb, bb);
1962     *a = mad(t, fa, ba);
1963 }
1964 
STAGE(evenly_spaced_gradient,const SkRasterPipeline_GradientCtx * c)1965 STAGE(evenly_spaced_gradient, const SkRasterPipeline_GradientCtx* c) {
1966     auto t = r;
1967     auto idx = trunc_(t * (c->stopCount-1));
1968     gradient_lookup(c, idx, t, &r, &g, &b, &a);
1969 }
1970 
STAGE(gradient,const SkRasterPipeline_GradientCtx * c)1971 STAGE(gradient, const SkRasterPipeline_GradientCtx* c) {
1972     auto t = r;
1973     U32 idx = 0;
1974 
1975     // N.B. The loop starts at 1 because idx 0 is the color to use before the first stop.
1976     for (size_t i = 1; i < c->stopCount; i++) {
1977         idx += if_then_else(t >= c->ts[i], U32(1), U32(0));
1978     }
1979 
1980     gradient_lookup(c, idx, t, &r, &g, &b, &a);
1981 }
1982 
STAGE(evenly_spaced_2_stop_gradient,const void * ctx)1983 STAGE(evenly_spaced_2_stop_gradient, const void* ctx) {
1984     // TODO: Rename Ctx SkRasterPipeline_EvenlySpaced2StopGradientCtx.
1985     struct Ctx { float f[4], b[4]; };
1986     auto c = (const Ctx*)ctx;
1987 
1988     auto t = r;
1989     r = mad(t, c->f[0], c->b[0]);
1990     g = mad(t, c->f[1], c->b[1]);
1991     b = mad(t, c->f[2], c->b[2]);
1992     a = mad(t, c->f[3], c->b[3]);
1993 }
1994 
STAGE(xy_to_unit_angle,Ctx::None)1995 STAGE(xy_to_unit_angle, Ctx::None) {
1996     F X = r,
1997       Y = g;
1998     F xabs = abs_(X),
1999       yabs = abs_(Y);
2000 
2001     F slope = min(xabs, yabs)/max(xabs, yabs);
2002     F s = slope * slope;
2003 
2004     // Use a 7th degree polynomial to approximate atan.
2005     // This was generated using sollya.gforge.inria.fr.
2006     // A float optimized polynomial was generated using the following command.
2007     // P1 = fpminimax((1/(2*Pi))*atan(x),[|1,3,5,7|],[|24...|],[2^(-40),1],relative);
2008     F phi = slope
2009              * (0.15912117063999176025390625f     + s
2010              * (-5.185396969318389892578125e-2f   + s
2011              * (2.476101927459239959716796875e-2f + s
2012              * (-7.0547382347285747528076171875e-3f))));
2013 
2014     phi = if_then_else(xabs < yabs, 1.0f/4.0f - phi, phi);
2015     phi = if_then_else(X < 0.0f   , 1.0f/2.0f - phi, phi);
2016     phi = if_then_else(Y < 0.0f   , 1.0f - phi     , phi);
2017     phi = if_then_else(phi != phi , 0              , phi);  // Check for NaN.
2018     r = phi;
2019 }
2020 
STAGE(xy_to_radius,Ctx::None)2021 STAGE(xy_to_radius, Ctx::None) {
2022     F X2 = r * r,
2023       Y2 = g * g;
2024     r = sqrt_(X2 + Y2);
2025 }
2026 
2027 // Please see https://skia.org/dev/design/conical for how our 2pt conical shader works.
2028 
STAGE(negate_x,Ctx::None)2029 STAGE(negate_x, Ctx::None) { r = -r; }
2030 
STAGE(xy_to_2pt_conical_strip,const SkRasterPipeline_2PtConicalCtx * ctx)2031 STAGE(xy_to_2pt_conical_strip, const SkRasterPipeline_2PtConicalCtx* ctx) {
2032     F x = r, y = g, &t = r;
2033     t = x + sqrt_(ctx->fP0 - y*y); // ctx->fP0 = r0 * r0
2034 }
2035 
STAGE(xy_to_2pt_conical_focal_on_circle,Ctx::None)2036 STAGE(xy_to_2pt_conical_focal_on_circle, Ctx::None) {
2037     F x = r, y = g, &t = r;
2038     t = x + y*y / x; // (x^2 + y^2) / x
2039 }
2040 
STAGE(xy_to_2pt_conical_well_behaved,const SkRasterPipeline_2PtConicalCtx * ctx)2041 STAGE(xy_to_2pt_conical_well_behaved, const SkRasterPipeline_2PtConicalCtx* ctx) {
2042     F x = r, y = g, &t = r;
2043     t = sqrt_(x*x + y*y) - x * ctx->fP0; // ctx->fP0 = 1/r1
2044 }
2045 
STAGE(xy_to_2pt_conical_greater,const SkRasterPipeline_2PtConicalCtx * ctx)2046 STAGE(xy_to_2pt_conical_greater, const SkRasterPipeline_2PtConicalCtx* ctx) {
2047     F x = r, y = g, &t = r;
2048     t = sqrt_(x*x - y*y) - x * ctx->fP0; // ctx->fP0 = 1/r1
2049 }
2050 
STAGE(xy_to_2pt_conical_smaller,const SkRasterPipeline_2PtConicalCtx * ctx)2051 STAGE(xy_to_2pt_conical_smaller, const SkRasterPipeline_2PtConicalCtx* ctx) {
2052     F x = r, y = g, &t = r;
2053     t = -sqrt_(x*x - y*y) - x * ctx->fP0; // ctx->fP0 = 1/r1
2054 }
2055 
STAGE(alter_2pt_conical_compensate_focal,const SkRasterPipeline_2PtConicalCtx * ctx)2056 STAGE(alter_2pt_conical_compensate_focal, const SkRasterPipeline_2PtConicalCtx* ctx) {
2057     F& t = r;
2058     t = t + ctx->fP1; // ctx->fP1 = f
2059 }
2060 
STAGE(alter_2pt_conical_unswap,Ctx::None)2061 STAGE(alter_2pt_conical_unswap, Ctx::None) {
2062     F& t = r;
2063     t = 1 - t;
2064 }
2065 
STAGE(mask_2pt_conical_nan,SkRasterPipeline_2PtConicalCtx * c)2066 STAGE(mask_2pt_conical_nan, SkRasterPipeline_2PtConicalCtx* c) {
2067     F& t = r;
2068     auto is_degenerate = (t != t); // NaN
2069     t = if_then_else(is_degenerate, F(0), t);
2070     unaligned_store(&c->fMask, cond_to_mask(!is_degenerate));
2071 }
2072 
STAGE(mask_2pt_conical_degenerates,SkRasterPipeline_2PtConicalCtx * c)2073 STAGE(mask_2pt_conical_degenerates, SkRasterPipeline_2PtConicalCtx* c) {
2074     F& t = r;
2075     auto is_degenerate = (t <= 0) | (t != t);
2076     t = if_then_else(is_degenerate, F(0), t);
2077     unaligned_store(&c->fMask, cond_to_mask(!is_degenerate));
2078 }
2079 
STAGE(apply_vector_mask,const uint32_t * ctx)2080 STAGE(apply_vector_mask, const uint32_t* ctx) {
2081     const U32 mask = unaligned_load<U32>(ctx);
2082     r = bit_cast<F>(bit_cast<U32>(r) & mask);
2083     g = bit_cast<F>(bit_cast<U32>(g) & mask);
2084     b = bit_cast<F>(bit_cast<U32>(b) & mask);
2085     a = bit_cast<F>(bit_cast<U32>(a) & mask);
2086 }
2087 
STAGE(save_xy,SkRasterPipeline_SamplerCtx * c)2088 STAGE(save_xy, SkRasterPipeline_SamplerCtx* c) {
2089     // Whether bilinear or bicubic, all sample points are at the same fractional offset (fx,fy).
2090     // They're either the 4 corners of a logical 1x1 pixel or the 16 corners of a 3x3 grid
2091     // surrounding (x,y) at (0.5,0.5) off-center.
2092     F fx = fract(r + 0.5f),
2093       fy = fract(g + 0.5f);
2094 
2095     // Samplers will need to load x and fx, or y and fy.
2096     unaligned_store(c->x,  r);
2097     unaligned_store(c->y,  g);
2098     unaligned_store(c->fx, fx);
2099     unaligned_store(c->fy, fy);
2100 }
2101 
STAGE(accumulate,const SkRasterPipeline_SamplerCtx * c)2102 STAGE(accumulate, const SkRasterPipeline_SamplerCtx* c) {
2103     // Bilinear and bicubic filters are both separable, so we produce independent contributions
2104     // from x and y, multiplying them together here to get each pixel's total scale factor.
2105     auto scale = unaligned_load<F>(c->scalex)
2106                * unaligned_load<F>(c->scaley);
2107     dr = mad(scale, r, dr);
2108     dg = mad(scale, g, dg);
2109     db = mad(scale, b, db);
2110     da = mad(scale, a, da);
2111 }
2112 
2113 // In bilinear interpolation, the 4 pixels at +/- 0.5 offsets from the sample pixel center
2114 // are combined in direct proportion to their area overlapping that logical query pixel.
2115 // At positive offsets, the x-axis contribution to that rectangle is fx, or (1-fx) at negative x.
2116 // The y-axis is symmetric.
2117 
2118 template <int kScale>
bilinear_x(SkRasterPipeline_SamplerCtx * ctx,F * x)2119 SI void bilinear_x(SkRasterPipeline_SamplerCtx* ctx, F* x) {
2120     *x = unaligned_load<F>(ctx->x) + (kScale * 0.5f);
2121     F fx = unaligned_load<F>(ctx->fx);
2122 
2123     F scalex;
2124     if (kScale == -1) { scalex = 1.0f - fx; }
2125     if (kScale == +1) { scalex =        fx; }
2126     unaligned_store(ctx->scalex, scalex);
2127 }
2128 template <int kScale>
bilinear_y(SkRasterPipeline_SamplerCtx * ctx,F * y)2129 SI void bilinear_y(SkRasterPipeline_SamplerCtx* ctx, F* y) {
2130     *y = unaligned_load<F>(ctx->y) + (kScale * 0.5f);
2131     F fy = unaligned_load<F>(ctx->fy);
2132 
2133     F scaley;
2134     if (kScale == -1) { scaley = 1.0f - fy; }
2135     if (kScale == +1) { scaley =        fy; }
2136     unaligned_store(ctx->scaley, scaley);
2137 }
2138 
STAGE(bilinear_nx,SkRasterPipeline_SamplerCtx * ctx)2139 STAGE(bilinear_nx, SkRasterPipeline_SamplerCtx* ctx) { bilinear_x<-1>(ctx, &r); }
STAGE(bilinear_px,SkRasterPipeline_SamplerCtx * ctx)2140 STAGE(bilinear_px, SkRasterPipeline_SamplerCtx* ctx) { bilinear_x<+1>(ctx, &r); }
STAGE(bilinear_ny,SkRasterPipeline_SamplerCtx * ctx)2141 STAGE(bilinear_ny, SkRasterPipeline_SamplerCtx* ctx) { bilinear_y<-1>(ctx, &g); }
STAGE(bilinear_py,SkRasterPipeline_SamplerCtx * ctx)2142 STAGE(bilinear_py, SkRasterPipeline_SamplerCtx* ctx) { bilinear_y<+1>(ctx, &g); }
2143 
2144 
2145 // In bicubic interpolation, the 16 pixels and +/- 0.5 and +/- 1.5 offsets from the sample
2146 // pixel center are combined with a non-uniform cubic filter, with higher values near the center.
2147 //
2148 // We break this function into two parts, one for near 0.5 offsets and one for far 1.5 offsets.
2149 // See GrCubicEffect for details of this particular filter.
2150 
bicubic_near(F t)2151 SI F bicubic_near(F t) {
2152     // 1/18 + 9/18t + 27/18t^2 - 21/18t^3 == t ( t ( -21/18t + 27/18) + 9/18) + 1/18
2153     return mad(t, mad(t, mad((-21/18.0f), t, (27/18.0f)), (9/18.0f)), (1/18.0f));
2154 }
bicubic_far(F t)2155 SI F bicubic_far(F t) {
2156     // 0/18 + 0/18*t - 6/18t^2 + 7/18t^3 == t^2 (7/18t - 6/18)
2157     return (t*t)*mad((7/18.0f), t, (-6/18.0f));
2158 }
2159 
2160 template <int kScale>
bicubic_x(SkRasterPipeline_SamplerCtx * ctx,F * x)2161 SI void bicubic_x(SkRasterPipeline_SamplerCtx* ctx, F* x) {
2162     *x = unaligned_load<F>(ctx->x) + (kScale * 0.5f);
2163     F fx = unaligned_load<F>(ctx->fx);
2164 
2165     F scalex;
2166     if (kScale == -3) { scalex = bicubic_far (1.0f - fx); }
2167     if (kScale == -1) { scalex = bicubic_near(1.0f - fx); }
2168     if (kScale == +1) { scalex = bicubic_near(       fx); }
2169     if (kScale == +3) { scalex = bicubic_far (       fx); }
2170     unaligned_store(ctx->scalex, scalex);
2171 }
2172 template <int kScale>
bicubic_y(SkRasterPipeline_SamplerCtx * ctx,F * y)2173 SI void bicubic_y(SkRasterPipeline_SamplerCtx* ctx, F* y) {
2174     *y = unaligned_load<F>(ctx->y) + (kScale * 0.5f);
2175     F fy = unaligned_load<F>(ctx->fy);
2176 
2177     F scaley;
2178     if (kScale == -3) { scaley = bicubic_far (1.0f - fy); }
2179     if (kScale == -1) { scaley = bicubic_near(1.0f - fy); }
2180     if (kScale == +1) { scaley = bicubic_near(       fy); }
2181     if (kScale == +3) { scaley = bicubic_far (       fy); }
2182     unaligned_store(ctx->scaley, scaley);
2183 }
2184 
STAGE(bicubic_n3x,SkRasterPipeline_SamplerCtx * ctx)2185 STAGE(bicubic_n3x, SkRasterPipeline_SamplerCtx* ctx) { bicubic_x<-3>(ctx, &r); }
STAGE(bicubic_n1x,SkRasterPipeline_SamplerCtx * ctx)2186 STAGE(bicubic_n1x, SkRasterPipeline_SamplerCtx* ctx) { bicubic_x<-1>(ctx, &r); }
STAGE(bicubic_p1x,SkRasterPipeline_SamplerCtx * ctx)2187 STAGE(bicubic_p1x, SkRasterPipeline_SamplerCtx* ctx) { bicubic_x<+1>(ctx, &r); }
STAGE(bicubic_p3x,SkRasterPipeline_SamplerCtx * ctx)2188 STAGE(bicubic_p3x, SkRasterPipeline_SamplerCtx* ctx) { bicubic_x<+3>(ctx, &r); }
2189 
STAGE(bicubic_n3y,SkRasterPipeline_SamplerCtx * ctx)2190 STAGE(bicubic_n3y, SkRasterPipeline_SamplerCtx* ctx) { bicubic_y<-3>(ctx, &g); }
STAGE(bicubic_n1y,SkRasterPipeline_SamplerCtx * ctx)2191 STAGE(bicubic_n1y, SkRasterPipeline_SamplerCtx* ctx) { bicubic_y<-1>(ctx, &g); }
STAGE(bicubic_p1y,SkRasterPipeline_SamplerCtx * ctx)2192 STAGE(bicubic_p1y, SkRasterPipeline_SamplerCtx* ctx) { bicubic_y<+1>(ctx, &g); }
STAGE(bicubic_p3y,SkRasterPipeline_SamplerCtx * ctx)2193 STAGE(bicubic_p3y, SkRasterPipeline_SamplerCtx* ctx) { bicubic_y<+3>(ctx, &g); }
2194 
STAGE(callback,SkRasterPipeline_CallbackCtx * c)2195 STAGE(callback, SkRasterPipeline_CallbackCtx* c) {
2196     store4(c->rgba,0, r,g,b,a);
2197     c->fn(c, tail ? tail : N);
2198     load4(c->read_from,0, &r,&g,&b,&a);
2199 }
2200 
STAGE(gauss_a_to_rgba,Ctx::None)2201 STAGE(gauss_a_to_rgba, Ctx::None) {
2202     // x = 1 - x;
2203     // exp(-x * x * 4) - 0.018f;
2204     // ... now approximate with quartic
2205     //
2206     const float c4 = -2.26661229133605957031f;
2207     const float c3 = 2.89795351028442382812f;
2208     const float c2 = 0.21345567703247070312f;
2209     const float c1 = 0.15489584207534790039f;
2210     const float c0 = 0.00030726194381713867f;
2211     a = mad(a, mad(a, mad(a, mad(a, c4, c3), c2), c1), c0);
2212     r = a;
2213     g = a;
2214     b = a;
2215 }
2216 
2217 // A specialized fused image shader for clamp-x, clamp-y, non-sRGB sampling.
STAGE(bilerp_clamp_8888,const SkRasterPipeline_GatherCtx * ctx)2218 STAGE(bilerp_clamp_8888, const SkRasterPipeline_GatherCtx* ctx) {
2219     // (cx,cy) are the center of our sample.
2220     F cx = r,
2221       cy = g;
2222 
2223     // All sample points are at the same fractional offset (fx,fy).
2224     // They're the 4 corners of a logical 1x1 pixel surrounding (x,y) at (0.5,0.5) offsets.
2225     F fx = fract(cx + 0.5f),
2226       fy = fract(cy + 0.5f);
2227 
2228     // We'll accumulate the color of all four samples into {r,g,b,a} directly.
2229     r = g = b = a = 0;
2230 
2231     for (float dy = -0.5f; dy <= +0.5f; dy += 1.0f)
2232     for (float dx = -0.5f; dx <= +0.5f; dx += 1.0f) {
2233         // (x,y) are the coordinates of this sample point.
2234         F x = cx + dx,
2235           y = cy + dy;
2236 
2237         // ix_and_ptr() will clamp to the image's bounds for us.
2238         const uint32_t* ptr;
2239         U32 ix = ix_and_ptr(&ptr, ctx, x,y);
2240 
2241         F sr,sg,sb,sa;
2242         from_8888(gather(ptr, ix), &sr,&sg,&sb,&sa);
2243 
2244         // In bilinear interpolation, the 4 pixels at +/- 0.5 offsets from the sample pixel center
2245         // are combined in direct proportion to their area overlapping that logical query pixel.
2246         // At positive offsets, the x-axis contribution to that rectangle is fx,
2247         // or (1-fx) at negative x.  Same deal for y.
2248         F sx = (dx > 0) ? fx : 1.0f - fx,
2249           sy = (dy > 0) ? fy : 1.0f - fy,
2250           area = sx * sy;
2251 
2252         r += sr * area;
2253         g += sg * area;
2254         b += sb * area;
2255         a += sa * area;
2256     }
2257 }
2258 
2259 namespace lowp {
2260 #if defined(JUMPER_IS_SCALAR) || defined(SK_DISABLE_LOWP_RASTER_PIPELINE)
2261     // If we're not compiled by Clang, or otherwise switched into scalar mode (old Clang, manually),
2262     // we don't generate lowp stages.  All these nullptrs will tell SkJumper.cpp to always use the
2263     // highp float pipeline.
2264     #define M(st) static void (*st)(void) = nullptr;
2265         SK_RASTER_PIPELINE_STAGES(M)
2266     #undef M
2267     static void (*just_return)(void) = nullptr;
2268 
start_pipeline(size_t,size_t,size_t,size_t,void **)2269     static void start_pipeline(size_t,size_t,size_t,size_t, void**) {}
2270 
2271 #else  // We are compiling vector code with Clang... let's make some lowp stages!
2272 
2273 #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2274     using U8  = uint8_t  __attribute__((ext_vector_type(16)));
2275     using U16 = uint16_t __attribute__((ext_vector_type(16)));
2276     using I16 =  int16_t __attribute__((ext_vector_type(16)));
2277     using I32 =  int32_t __attribute__((ext_vector_type(16)));
2278     using U32 = uint32_t __attribute__((ext_vector_type(16)));
2279     using F   = float    __attribute__((ext_vector_type(16)));
2280 #else
2281     using U8  = uint8_t  __attribute__((ext_vector_type(8)));
2282     using U16 = uint16_t __attribute__((ext_vector_type(8)));
2283     using I16 =  int16_t __attribute__((ext_vector_type(8)));
2284     using I32 =  int32_t __attribute__((ext_vector_type(8)));
2285     using U32 = uint32_t __attribute__((ext_vector_type(8)));
2286     using F   = float    __attribute__((ext_vector_type(8)));
2287 #endif
2288 
2289 static const size_t N = sizeof(U16) / sizeof(uint16_t);
2290 
2291 // Once again, some platforms benefit from a restricted Stage calling convention,
2292 // but others can pass tons and tons of registers and we're happy to exploit that.
2293 // It's exactly the same decision and implementation strategy as the F stages above.
2294 #if JUMPER_NARROW_STAGES
2295     struct Params {
2296         size_t dx, dy, tail;
2297         U16 dr,dg,db,da;
2298     };
2299     using Stage = void(ABI*)(Params*, void** program, U16 r, U16 g, U16 b, U16 a);
2300 #else
2301     // We pass program as the second argument so that load_and_inc() will find it in %rsi on x86-64.
2302     using Stage = void (ABI*)(size_t tail, void** program, size_t dx, size_t dy,
2303                               U16  r, U16  g, U16  b, U16  a,
2304                               U16 dr, U16 dg, U16 db, U16 da);
2305 #endif
2306 
2307 static void start_pipeline(const size_t x0,     const size_t y0,
2308                            const size_t xlimit, const size_t ylimit, void** program) {
2309     auto start = (Stage)load_and_inc(program);
2310     for (size_t dy = y0; dy < ylimit; dy++) {
2311     #if JUMPER_NARROW_STAGES
2312         Params params = { x0,dy,0, 0,0,0,0 };
2313         for (; params.dx + N <= xlimit; params.dx += N) {
2314             start(&params,program, 0,0,0,0);
2315         }
2316         if (size_t tail = xlimit - params.dx) {
2317             params.tail = tail;
2318             start(&params,program, 0,0,0,0);
2319         }
2320     #else
2321         size_t dx = x0;
2322         for (; dx + N <= xlimit; dx += N) {
2323             start(   0,program,dx,dy, 0,0,0,0, 0,0,0,0);
2324         }
2325         if (size_t tail = xlimit - dx) {
2326             start(tail,program,dx,dy, 0,0,0,0, 0,0,0,0);
2327         }
2328     #endif
2329     }
2330 }
2331 
2332 #if JUMPER_NARROW_STAGES
2333     static void ABI just_return(Params*, void**, U16,U16,U16,U16) {}
2334 #else
2335     static void ABI just_return(size_t,void**,size_t,size_t, U16,U16,U16,U16, U16,U16,U16,U16) {}
2336 #endif
2337 
2338 // All stages use the same function call ABI to chain into each other, but there are three types:
2339 //   GG: geometry in, geometry out  -- think, a matrix
2340 //   GP: geometry in, pixels out.   -- think, a memory gather
2341 //   PP: pixels in, pixels out.     -- think, a blend mode
2342 //
2343 // (Some stages ignore their inputs or produce no logical output.  That's perfectly fine.)
2344 //
2345 // These three STAGE_ macros let you define each type of stage,
2346 // and will have (x,y) geometry and/or (r,g,b,a, dr,dg,db,da) pixel arguments as appropriate.
2347 
2348 #if JUMPER_NARROW_STAGES
2349     #define STAGE_GG(name, ...)                                                                \
2350         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F& x, F& y,           \
2351                          U16    , U16    , U16    , U16    ,                                   \
2352                          U16    , U16    , U16    , U16    );                                  \
2353         static void ABI name(Params* params, void** program, U16 r, U16 g, U16 b, U16 a) {     \
2354             auto x = join<F>(r,g),                                                             \
2355                  y = join<F>(b,a);                                                             \
2356             name##_k(Ctx{program}, params->dx,params->dy,params->tail, x,y, 0,0,0,0, 0,0,0,0); \
2357             split(x, &r,&g);                                                                   \
2358             split(y, &b,&a);                                                                   \
2359             auto next = (Stage)load_and_inc(program);                                          \
2360             next(params,program, r,g,b,a);                                                     \
2361         }                                                                                      \
2362         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F& x, F& y,           \
2363                          U16    , U16    , U16    , U16    ,                                   \
2364                          U16    , U16    , U16    , U16    )
2365 
2366     #define STAGE_GP(name, ...)                                                            \
2367         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F x, F y,         \
2368                          U16&  r, U16&  g, U16&  b, U16&  a,                               \
2369                          U16& dr, U16& dg, U16& db, U16& da);                              \
2370         static void ABI name(Params* params, void** program, U16 r, U16 g, U16 b, U16 a) { \
2371             auto x = join<F>(r,g),                                                         \
2372                  y = join<F>(b,a);                                                         \
2373             name##_k(Ctx{program}, params->dx,params->dy,params->tail, x,y, r,g,b,a,       \
2374                      params->dr,params->dg,params->db,params->da);                         \
2375             auto next = (Stage)load_and_inc(program);                                      \
2376             next(params,program, r,g,b,a);                                                 \
2377         }                                                                                  \
2378         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F x, F y,         \
2379                          U16&  r, U16&  g, U16&  b, U16&  a,                               \
2380                          U16& dr, U16& dg, U16& db, U16& da)
2381 
2382     #define STAGE_PP(name, ...)                                                            \
2383         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F  , F  ,         \
2384                          U16&  r, U16&  g, U16&  b, U16&  a,                               \
2385                          U16& dr, U16& dg, U16& db, U16& da);                              \
2386         static void ABI name(Params* params, void** program, U16 r, U16 g, U16 b, U16 a) { \
2387             name##_k(Ctx{program}, params->dx,params->dy,params->tail, 0,0, r,g,b,a,       \
2388                      params->dr,params->dg,params->db,params->da);                         \
2389             auto next = (Stage)load_and_inc(program);                                      \
2390             next(params,program, r,g,b,a);                                                 \
2391         }                                                                                  \
2392         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F  , F  ,         \
2393                          U16&  r, U16&  g, U16&  b, U16&  a,                               \
2394                          U16& dr, U16& dg, U16& db, U16& da)
2395 #else
2396     #define STAGE_GG(name, ...)                                                            \
2397         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F& x, F& y,       \
2398                          U16    , U16    , U16    , U16    ,                               \
2399                          U16    , U16    , U16    , U16    );                              \
2400         static void ABI name(size_t tail, void** program, size_t dx, size_t dy,            \
2401                              U16  r, U16  g, U16  b, U16  a,                               \
2402                              U16 dr, U16 dg, U16 db, U16 da) {                             \
2403             auto x = join<F>(r,g),                                                         \
2404                  y = join<F>(b,a);                                                         \
2405             name##_k(Ctx{program}, dx,dy,tail, x,y, 0,0,0,0, 0,0,0,0);                     \
2406             split(x, &r,&g);                                                               \
2407             split(y, &b,&a);                                                               \
2408             auto next = (Stage)load_and_inc(program);                                      \
2409             next(tail,program,dx,dy, r,g,b,a, dr,dg,db,da);                                \
2410         }                                                                                  \
2411         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F& x, F& y,       \
2412                          U16    , U16    , U16    , U16    ,                               \
2413                          U16    , U16    , U16    , U16    )
2414 
2415     #define STAGE_GP(name, ...)                                                            \
2416         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F x, F y,         \
2417                          U16&  r, U16&  g, U16&  b, U16&  a,                               \
2418                          U16& dr, U16& dg, U16& db, U16& da);                              \
2419         static void ABI name(size_t tail, void** program, size_t dx, size_t dy,            \
2420                              U16  r, U16  g, U16  b, U16  a,                               \
2421                              U16 dr, U16 dg, U16 db, U16 da) {                             \
2422             auto x = join<F>(r,g),                                                         \
2423                  y = join<F>(b,a);                                                         \
2424             name##_k(Ctx{program}, dx,dy,tail, x,y, r,g,b,a, dr,dg,db,da);                 \
2425             auto next = (Stage)load_and_inc(program);                                      \
2426             next(tail,program,dx,dy, r,g,b,a, dr,dg,db,da);                                \
2427         }                                                                                  \
2428         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F x, F y,         \
2429                          U16&  r, U16&  g, U16&  b, U16&  a,                               \
2430                          U16& dr, U16& dg, U16& db, U16& da)
2431 
2432     #define STAGE_PP(name, ...)                                                            \
2433         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F  , F  ,         \
2434                          U16&  r, U16&  g, U16&  b, U16&  a,                               \
2435                          U16& dr, U16& dg, U16& db, U16& da);                              \
2436         static void ABI name(size_t tail, void** program, size_t dx, size_t dy,            \
2437                              U16  r, U16  g, U16  b, U16  a,                               \
2438                              U16 dr, U16 dg, U16 db, U16 da) {                             \
2439             name##_k(Ctx{program}, dx,dy,tail, 0,0, r,g,b,a, dr,dg,db,da);                 \
2440             auto next = (Stage)load_and_inc(program);                                      \
2441             next(tail,program,dx,dy, r,g,b,a, dr,dg,db,da);                                \
2442         }                                                                                  \
2443         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F  , F  ,         \
2444                          U16&  r, U16&  g, U16&  b, U16&  a,                               \
2445                          U16& dr, U16& dg, U16& db, U16& da)
2446 #endif
2447 
2448 // ~~~~~~ Commonly used helper functions ~~~~~~ //
2449 
2450 SI U16 div255(U16 v) {
2451 #if 0
2452     return (v+127)/255;  // The ideal rounding divide by 255.
2453 #elif 1 && defined(JUMPER_IS_NEON)
2454     // With NEON we can compute (v+127)/255 as (v + ((v+128)>>8) + 128)>>8
2455     // just as fast as we can do the approximation below, so might as well be correct!
2456     // First we compute v + ((v+128)>>8), then one more round of (...+128)>>8 to finish up.
2457     return vrshrq_n_u16(vrsraq_n_u16(v, v, 8), 8);
2458 #else
2459     return (v+255)/256;  // A good approximation of (v+127)/255.
2460 #endif
2461 }
2462 
2463 SI U16 inv(U16 v) { return 255-v; }
2464 
2465 SI U16 if_then_else(I16 c, U16 t, U16 e) { return (t & c) | (e & ~c); }
2466 SI U32 if_then_else(I32 c, U32 t, U32 e) { return (t & c) | (e & ~c); }
2467 
2468 SI U16 max(U16 x, U16 y) { return if_then_else(x < y, y, x); }
2469 SI U16 min(U16 x, U16 y) { return if_then_else(x < y, x, y); }
2470 SI U16 max(U16 x, U16 y, U16 z) { return max(x, max(y, z)); }
2471 SI U16 min(U16 x, U16 y, U16 z) { return min(x, min(y, z)); }
2472 
2473 SI U16 from_float(float f) { return f * 255.0f + 0.5f; }
2474 
2475 SI U16 lerp(U16 from, U16 to, U16 t) { return div255( from*inv(t) + to*t ); }
2476 
2477 template <typename D, typename S>
2478 SI D cast(S src) {
2479     return __builtin_convertvector(src, D);
2480 }
2481 
2482 template <typename D, typename S>
2483 SI void split(S v, D* lo, D* hi) {
2484     static_assert(2*sizeof(D) == sizeof(S), "");
2485     memcpy(lo, (const char*)&v + 0*sizeof(D), sizeof(D));
2486     memcpy(hi, (const char*)&v + 1*sizeof(D), sizeof(D));
2487 }
2488 template <typename D, typename S>
2489 SI D join(S lo, S hi) {
2490     static_assert(sizeof(D) == 2*sizeof(S), "");
2491     D v;
2492     memcpy((char*)&v + 0*sizeof(S), &lo, sizeof(S));
2493     memcpy((char*)&v + 1*sizeof(S), &hi, sizeof(S));
2494     return v;
2495 }
2496 
2497 SI F if_then_else(I32 c, F t, F e) {
2498     return bit_cast<F>( (bit_cast<I32>(t) & c) | (bit_cast<I32>(e) & ~c) );
2499 }
2500 SI F max(F x, F y) { return if_then_else(x < y, y, x); }
2501 SI F min(F x, F y) { return if_then_else(x < y, x, y); }
2502 
2503 SI F mad(F f, F m, F a) { return f*m+a; }
2504 SI U32 trunc_(F x) { return (U32)cast<I32>(x); }
2505 
2506 SI F rcp(F x) {
2507 #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2508     __m256 lo,hi;
2509     split(x, &lo,&hi);
2510     return join<F>(_mm256_rcp_ps(lo), _mm256_rcp_ps(hi));
2511 #elif defined(JUMPER_IS_SSE2) || defined(JUMPER_IS_SSE41) || defined(JUMPER_IS_AVX)
2512     __m128 lo,hi;
2513     split(x, &lo,&hi);
2514     return join<F>(_mm_rcp_ps(lo), _mm_rcp_ps(hi));
2515 #elif defined(JUMPER_IS_NEON)
2516     auto rcp = [](float32x4_t v) {
2517         auto est = vrecpeq_f32(v);
2518         return vrecpsq_f32(v,est)*est;
2519     };
2520     float32x4_t lo,hi;
2521     split(x, &lo,&hi);
2522     return join<F>(rcp(lo), rcp(hi));
2523 #else
2524     return 1.0f / x;
2525 #endif
2526 }
2527 SI F sqrt_(F x) {
2528 #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2529     __m256 lo,hi;
2530     split(x, &lo,&hi);
2531     return join<F>(_mm256_sqrt_ps(lo), _mm256_sqrt_ps(hi));
2532 #elif defined(JUMPER_IS_SSE2) || defined(JUMPER_IS_SSE41) || defined(JUMPER_IS_AVX)
2533     __m128 lo,hi;
2534     split(x, &lo,&hi);
2535     return join<F>(_mm_sqrt_ps(lo), _mm_sqrt_ps(hi));
2536 #elif defined(SK_CPU_ARM64)
2537     float32x4_t lo,hi;
2538     split(x, &lo,&hi);
2539     return join<F>(vsqrtq_f32(lo), vsqrtq_f32(hi));
2540 #elif defined(JUMPER_IS_NEON)
2541     auto sqrt = [](float32x4_t v) {
2542         auto est = vrsqrteq_f32(v);  // Estimate and two refinement steps for est = rsqrt(v).
2543         est *= vrsqrtsq_f32(v,est*est);
2544         est *= vrsqrtsq_f32(v,est*est);
2545         return v*est;                // sqrt(v) == v*rsqrt(v).
2546     };
2547     float32x4_t lo,hi;
2548     split(x, &lo,&hi);
2549     return join<F>(sqrt(lo), sqrt(hi));
2550 #else
2551     return F{
2552         sqrtf(x[0]), sqrtf(x[1]), sqrtf(x[2]), sqrtf(x[3]),
2553         sqrtf(x[4]), sqrtf(x[5]), sqrtf(x[6]), sqrtf(x[7]),
2554     };
2555 #endif
2556 }
2557 
2558 SI F floor_(F x) {
2559 #if defined(SK_CPU_ARM64)
2560     float32x4_t lo,hi;
2561     split(x, &lo,&hi);
2562     return join<F>(vrndmq_f32(lo), vrndmq_f32(hi));
2563 #elif defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2564     __m256 lo,hi;
2565     split(x, &lo,&hi);
2566     return join<F>(_mm256_floor_ps(lo), _mm256_floor_ps(hi));
2567 #elif defined(JUMPER_IS_SSE41) || defined(JUMPER_IS_AVX)
2568     __m128 lo,hi;
2569     split(x, &lo,&hi);
2570     return join<F>(_mm_floor_ps(lo), _mm_floor_ps(hi));
2571 #else
2572     F roundtrip = cast<F>(cast<I32>(x));
2573     return roundtrip - if_then_else(roundtrip > x, F(1), F(0));
2574 #endif
2575 }
2576 SI F fract(F x) { return x - floor_(x); }
2577 SI F abs_(F x) { return bit_cast<F>( bit_cast<I32>(x) & 0x7fffffff ); }
2578 
2579 // ~~~~~~ Basic / misc. stages ~~~~~~ //
2580 
2581 STAGE_GG(seed_shader, Ctx::None) {
2582     static const float iota[] = {
2583         0.5f, 1.5f, 2.5f, 3.5f, 4.5f, 5.5f, 6.5f, 7.5f,
2584         8.5f, 9.5f,10.5f,11.5f,12.5f,13.5f,14.5f,15.5f,
2585     };
2586     x = cast<F>(I32(dx)) + unaligned_load<F>(iota);
2587     y = cast<F>(I32(dy)) + 0.5f;
2588 }
2589 
2590 STAGE_GG(matrix_translate, const float* m) {
2591     x += m[0];
2592     y += m[1];
2593 }
2594 STAGE_GG(matrix_scale_translate, const float* m) {
2595     x = mad(x,m[0], m[2]);
2596     y = mad(y,m[1], m[3]);
2597 }
2598 STAGE_GG(matrix_2x3, const float* m) {
2599     auto X = mad(x,m[0], mad(y,m[2], m[4])),
2600          Y = mad(x,m[1], mad(y,m[3], m[5]));
2601     x = X;
2602     y = Y;
2603 }
2604 STAGE_GG(matrix_perspective, const float* m) {
2605     // N.B. Unlike the other matrix_ stages, this matrix is row-major.
2606     auto X = mad(x,m[0], mad(y,m[1], m[2])),
2607          Y = mad(x,m[3], mad(y,m[4], m[5])),
2608          Z = mad(x,m[6], mad(y,m[7], m[8]));
2609     x = X * rcp(Z);
2610     y = Y * rcp(Z);
2611 }
2612 
2613 STAGE_PP(uniform_color, const SkRasterPipeline_UniformColorCtx* c) {
2614     r = c->rgba[0];
2615     g = c->rgba[1];
2616     b = c->rgba[2];
2617     a = c->rgba[3];
2618 }
2619 STAGE_PP(black_color, Ctx::None) { r = g = b =   0; a = 255; }
2620 STAGE_PP(white_color, Ctx::None) { r = g = b = 255; a = 255; }
2621 
2622 STAGE_PP(set_rgb, const float rgb[3]) {
2623     r = from_float(rgb[0]);
2624     g = from_float(rgb[1]);
2625     b = from_float(rgb[2]);
2626 }
2627 
2628 STAGE_PP(clamp_0, Ctx::None) { /*definitely a noop*/ }
2629 STAGE_PP(clamp_1, Ctx::None) { /*_should_ be a noop*/ }
2630 
2631 STAGE_PP(clamp_a, Ctx::None) {
2632     r = min(r, a);
2633     g = min(g, a);
2634     b = min(b, a);
2635 }
2636 STAGE_PP(clamp_a_dst, Ctx::None) {
2637     dr = min(dr, da);
2638     dg = min(dg, da);
2639     db = min(db, da);
2640 }
2641 
2642 STAGE_PP(clamp_gamut, Ctx::None) {
2643     // It shouldn't be possible to get out-of-gamut
2644     // colors when working in lowp.
2645 }
2646 
2647 STAGE_PP(premul, Ctx::None) {
2648     r = div255(r * a);
2649     g = div255(g * a);
2650     b = div255(b * a);
2651 }
2652 STAGE_PP(premul_dst, Ctx::None) {
2653     dr = div255(dr * da);
2654     dg = div255(dg * da);
2655     db = div255(db * da);
2656 }
2657 
2658 STAGE_PP(force_opaque    , Ctx::None) {  a = 255; }
2659 STAGE_PP(force_opaque_dst, Ctx::None) { da = 255; }
2660 
2661 STAGE_PP(swap_rb, Ctx::None) {
2662     auto tmp = r;
2663     r = b;
2664     b = tmp;
2665 }
2666 STAGE_PP(swap_rb_dst, Ctx::None) {
2667     auto tmp = dr;
2668     dr = db;
2669     db = tmp;
2670 }
2671 
2672 STAGE_PP(move_src_dst, Ctx::None) {
2673     dr = r;
2674     dg = g;
2675     db = b;
2676     da = a;
2677 }
2678 
2679 STAGE_PP(move_dst_src, Ctx::None) {
2680     r = dr;
2681     g = dg;
2682     b = db;
2683     a = da;
2684 }
2685 
2686 // ~~~~~~ Blend modes ~~~~~~ //
2687 
2688 // The same logic applied to all 4 channels.
2689 #define BLEND_MODE(name)                                 \
2690     SI U16 name##_channel(U16 s, U16 d, U16 sa, U16 da); \
2691     STAGE_PP(name, Ctx::None) {                          \
2692         r = name##_channel(r,dr,a,da);                   \
2693         g = name##_channel(g,dg,a,da);                   \
2694         b = name##_channel(b,db,a,da);                   \
2695         a = name##_channel(a,da,a,da);                   \
2696     }                                                    \
2697     SI U16 name##_channel(U16 s, U16 d, U16 sa, U16 da)
2698 
2699     BLEND_MODE(clear)    { return 0; }
2700     BLEND_MODE(srcatop)  { return div255( s*da + d*inv(sa) ); }
2701     BLEND_MODE(dstatop)  { return div255( d*sa + s*inv(da) ); }
2702     BLEND_MODE(srcin)    { return div255( s*da ); }
2703     BLEND_MODE(dstin)    { return div255( d*sa ); }
2704     BLEND_MODE(srcout)   { return div255( s*inv(da) ); }
2705     BLEND_MODE(dstout)   { return div255( d*inv(sa) ); }
2706     BLEND_MODE(srcover)  { return s + div255( d*inv(sa) ); }
2707     BLEND_MODE(dstover)  { return d + div255( s*inv(da) ); }
2708     BLEND_MODE(modulate) { return div255( s*d ); }
2709     BLEND_MODE(multiply) { return div255( s*inv(da) + d*inv(sa) + s*d ); }
2710     BLEND_MODE(plus_)    { return min(s+d, 255); }
2711     BLEND_MODE(screen)   { return s + d - div255( s*d ); }
2712     BLEND_MODE(xor_)     { return div255( s*inv(da) + d*inv(sa) ); }
2713 #undef BLEND_MODE
2714 
2715 // The same logic applied to color, and srcover for alpha.
2716 #define BLEND_MODE(name)                                 \
2717     SI U16 name##_channel(U16 s, U16 d, U16 sa, U16 da); \
2718     STAGE_PP(name, Ctx::None) {                          \
2719         r = name##_channel(r,dr,a,da);                   \
2720         g = name##_channel(g,dg,a,da);                   \
2721         b = name##_channel(b,db,a,da);                   \
2722         a = a + div255( da*inv(a) );                     \
2723     }                                                    \
2724     SI U16 name##_channel(U16 s, U16 d, U16 sa, U16 da)
2725 
2726     BLEND_MODE(darken)     { return s + d -   div255( max(s*da, d*sa) ); }
2727     BLEND_MODE(lighten)    { return s + d -   div255( min(s*da, d*sa) ); }
2728     BLEND_MODE(difference) { return s + d - 2*div255( min(s*da, d*sa) ); }
2729     BLEND_MODE(exclusion)  { return s + d - 2*div255( s*d ); }
2730 
2731     BLEND_MODE(hardlight) {
2732         return div255( s*inv(da) + d*inv(sa) +
2733                        if_then_else(2*s <= sa, 2*s*d, sa*da - 2*(sa-s)*(da-d)) );
2734     }
2735     BLEND_MODE(overlay) {
2736         return div255( s*inv(da) + d*inv(sa) +
2737                        if_then_else(2*d <= da, 2*s*d, sa*da - 2*(sa-s)*(da-d)) );
2738     }
2739 #undef BLEND_MODE
2740 
2741 // ~~~~~~ Helpers for interacting with memory ~~~~~~ //
2742 
2743 template <typename T>
2744 SI T* ptr_at_xy(const SkRasterPipeline_MemoryCtx* ctx, size_t dx, size_t dy) {
2745     return (T*)ctx->pixels + dy*ctx->stride + dx;
2746 }
2747 
2748 template <typename T>
2749 SI U32 ix_and_ptr(T** ptr, const SkRasterPipeline_GatherCtx* ctx, F x, F y) {
2750     auto clamp = [](F v, F limit) {
2751         limit = bit_cast<F>( bit_cast<U32>(limit) - 1 );  // Exclusive -> inclusive.
2752         return min(max(0, v), limit);
2753     };
2754     x = clamp(x, ctx->width);
2755     y = clamp(y, ctx->height);
2756 
2757     *ptr = (const T*)ctx->pixels;
2758     return trunc_(y)*ctx->stride + trunc_(x);
2759 }
2760 
2761 template <typename V, typename T>
2762 SI V load(const T* ptr, size_t tail) {
2763     V v = 0;
2764     switch (tail & (N-1)) {
2765         case  0: memcpy(&v, ptr, sizeof(v)); break;
2766     #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2767         case 15: v[14] = ptr[14];
2768         case 14: v[13] = ptr[13];
2769         case 13: v[12] = ptr[12];
2770         case 12: memcpy(&v, ptr, 12*sizeof(T)); break;
2771         case 11: v[10] = ptr[10];
2772         case 10: v[ 9] = ptr[ 9];
2773         case  9: v[ 8] = ptr[ 8];
2774         case  8: memcpy(&v, ptr,  8*sizeof(T)); break;
2775     #endif
2776         case  7: v[ 6] = ptr[ 6];
2777         case  6: v[ 5] = ptr[ 5];
2778         case  5: v[ 4] = ptr[ 4];
2779         case  4: memcpy(&v, ptr,  4*sizeof(T)); break;
2780         case  3: v[ 2] = ptr[ 2];
2781         case  2: memcpy(&v, ptr,  2*sizeof(T)); break;
2782         case  1: v[ 0] = ptr[ 0];
2783     }
2784     return v;
2785 }
2786 template <typename V, typename T>
2787 SI void store(T* ptr, size_t tail, V v) {
2788     switch (tail & (N-1)) {
2789         case  0: memcpy(ptr, &v, sizeof(v)); break;
2790     #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2791         case 15: ptr[14] = v[14];
2792         case 14: ptr[13] = v[13];
2793         case 13: ptr[12] = v[12];
2794         case 12: memcpy(ptr, &v, 12*sizeof(T)); break;
2795         case 11: ptr[10] = v[10];
2796         case 10: ptr[ 9] = v[ 9];
2797         case  9: ptr[ 8] = v[ 8];
2798         case  8: memcpy(ptr, &v,  8*sizeof(T)); break;
2799     #endif
2800         case  7: ptr[ 6] = v[ 6];
2801         case  6: ptr[ 5] = v[ 5];
2802         case  5: ptr[ 4] = v[ 4];
2803         case  4: memcpy(ptr, &v,  4*sizeof(T)); break;
2804         case  3: ptr[ 2] = v[ 2];
2805         case  2: memcpy(ptr, &v,  2*sizeof(T)); break;
2806         case  1: ptr[ 0] = v[ 0];
2807     }
2808 }
2809 
2810 #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2811     template <typename V, typename T>
2812     SI V gather(const T* ptr, U32 ix) {
2813         return V{ ptr[ix[ 0]], ptr[ix[ 1]], ptr[ix[ 2]], ptr[ix[ 3]],
2814                   ptr[ix[ 4]], ptr[ix[ 5]], ptr[ix[ 6]], ptr[ix[ 7]],
2815                   ptr[ix[ 8]], ptr[ix[ 9]], ptr[ix[10]], ptr[ix[11]],
2816                   ptr[ix[12]], ptr[ix[13]], ptr[ix[14]], ptr[ix[15]], };
2817     }
2818 
2819     template<>
2820     F gather(const float* ptr, U32 ix) {
2821         __m256i lo, hi;
2822         split(ix, &lo, &hi);
2823 
2824         return join<F>(_mm256_i32gather_ps(ptr, lo, 4),
2825                        _mm256_i32gather_ps(ptr, hi, 4));
2826     }
2827 
2828     template<>
2829     U32 gather(const uint32_t* ptr, U32 ix) {
2830         __m256i lo, hi;
2831         split(ix, &lo, &hi);
2832 
2833         return join<U32>(_mm256_i32gather_epi32(ptr, lo, 4),
2834                          _mm256_i32gather_epi32(ptr, hi, 4));
2835     }
2836 #else
2837     template <typename V, typename T>
2838     SI V gather(const T* ptr, U32 ix) {
2839         return V{ ptr[ix[ 0]], ptr[ix[ 1]], ptr[ix[ 2]], ptr[ix[ 3]],
2840                   ptr[ix[ 4]], ptr[ix[ 5]], ptr[ix[ 6]], ptr[ix[ 7]], };
2841     }
2842 #endif
2843 
2844 
2845 // ~~~~~~ 32-bit memory loads and stores ~~~~~~ //
2846 
2847 SI void from_8888(U32 rgba, U16* r, U16* g, U16* b, U16* a) {
2848 #if 1 && defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2849     // Swap the middle 128-bit lanes to make _mm256_packus_epi32() in cast_U16() work out nicely.
2850     __m256i _01,_23;
2851     split(rgba, &_01, &_23);
2852     __m256i _02 = _mm256_permute2x128_si256(_01,_23, 0x20),
2853             _13 = _mm256_permute2x128_si256(_01,_23, 0x31);
2854     rgba = join<U32>(_02, _13);
2855 
2856     auto cast_U16 = [](U32 v) -> U16 {
2857         __m256i _02,_13;
2858         split(v, &_02,&_13);
2859         return _mm256_packus_epi32(_02,_13);
2860     };
2861 #else
2862     auto cast_U16 = [](U32 v) -> U16 {
2863         return cast<U16>(v);
2864     };
2865 #endif
2866     *r = cast_U16(rgba & 65535) & 255;
2867     *g = cast_U16(rgba & 65535) >>  8;
2868     *b = cast_U16(rgba >>   16) & 255;
2869     *a = cast_U16(rgba >>   16) >>  8;
2870 }
2871 
2872 SI void load_8888_(const uint32_t* ptr, size_t tail, U16* r, U16* g, U16* b, U16* a) {
2873 #if 1 && defined(JUMPER_IS_NEON)
2874     uint8x8x4_t rgba;
2875     switch (tail & (N-1)) {
2876         case 0: rgba = vld4_u8     ((const uint8_t*)(ptr+0)         ); break;
2877         case 7: rgba = vld4_lane_u8((const uint8_t*)(ptr+6), rgba, 6);
2878         case 6: rgba = vld4_lane_u8((const uint8_t*)(ptr+5), rgba, 5);
2879         case 5: rgba = vld4_lane_u8((const uint8_t*)(ptr+4), rgba, 4);
2880         case 4: rgba = vld4_lane_u8((const uint8_t*)(ptr+3), rgba, 3);
2881         case 3: rgba = vld4_lane_u8((const uint8_t*)(ptr+2), rgba, 2);
2882         case 2: rgba = vld4_lane_u8((const uint8_t*)(ptr+1), rgba, 1);
2883         case 1: rgba = vld4_lane_u8((const uint8_t*)(ptr+0), rgba, 0);
2884     }
2885     *r = cast<U16>(rgba.val[0]);
2886     *g = cast<U16>(rgba.val[1]);
2887     *b = cast<U16>(rgba.val[2]);
2888     *a = cast<U16>(rgba.val[3]);
2889 #else
2890     from_8888(load<U32>(ptr, tail), r,g,b,a);
2891 #endif
2892 }
2893 SI void store_8888_(uint32_t* ptr, size_t tail, U16 r, U16 g, U16 b, U16 a) {
2894 #if 1 && defined(JUMPER_IS_NEON)
2895     uint8x8x4_t rgba = {{
2896         cast<U8>(r),
2897         cast<U8>(g),
2898         cast<U8>(b),
2899         cast<U8>(a),
2900     }};
2901     switch (tail & (N-1)) {
2902         case 0: vst4_u8     ((uint8_t*)(ptr+0), rgba   ); break;
2903         case 7: vst4_lane_u8((uint8_t*)(ptr+6), rgba, 6);
2904         case 6: vst4_lane_u8((uint8_t*)(ptr+5), rgba, 5);
2905         case 5: vst4_lane_u8((uint8_t*)(ptr+4), rgba, 4);
2906         case 4: vst4_lane_u8((uint8_t*)(ptr+3), rgba, 3);
2907         case 3: vst4_lane_u8((uint8_t*)(ptr+2), rgba, 2);
2908         case 2: vst4_lane_u8((uint8_t*)(ptr+1), rgba, 1);
2909         case 1: vst4_lane_u8((uint8_t*)(ptr+0), rgba, 0);
2910     }
2911 #else
2912     store(ptr, tail, cast<U32>(r | (g<<8)) <<  0
2913                    | cast<U32>(b | (a<<8)) << 16);
2914 #endif
2915 }
2916 
2917 STAGE_PP(load_8888, const SkRasterPipeline_MemoryCtx* ctx) {
2918     load_8888_(ptr_at_xy<const uint32_t>(ctx, dx,dy), tail, &r,&g,&b,&a);
2919 }
2920 STAGE_PP(load_8888_dst, const SkRasterPipeline_MemoryCtx* ctx) {
2921     load_8888_(ptr_at_xy<const uint32_t>(ctx, dx,dy), tail, &dr,&dg,&db,&da);
2922 }
2923 STAGE_PP(store_8888, const SkRasterPipeline_MemoryCtx* ctx) {
2924     store_8888_(ptr_at_xy<uint32_t>(ctx, dx,dy), tail, r,g,b,a);
2925 }
2926 STAGE_GP(gather_8888, const SkRasterPipeline_GatherCtx* ctx) {
2927     const uint32_t* ptr;
2928     U32 ix = ix_and_ptr(&ptr, ctx, x,y);
2929     from_8888(gather<U32>(ptr, ix), &r, &g, &b, &a);
2930 }
2931 
2932 // ~~~~~~ 16-bit memory loads and stores ~~~~~~ //
2933 
2934 SI void from_565(U16 rgb, U16* r, U16* g, U16* b) {
2935     // Format for 565 buffers: 15|rrrrr gggggg bbbbb|0
2936     U16 R = (rgb >> 11) & 31,
2937         G = (rgb >>  5) & 63,
2938         B = (rgb >>  0) & 31;
2939 
2940     // These bit replications are the same as multiplying by 255/31 or 255/63 to scale to 8-bit.
2941     *r = (R << 3) | (R >> 2);
2942     *g = (G << 2) | (G >> 4);
2943     *b = (B << 3) | (B >> 2);
2944 }
2945 SI void load_565_(const uint16_t* ptr, size_t tail, U16* r, U16* g, U16* b) {
2946     from_565(load<U16>(ptr, tail), r,g,b);
2947 }
2948 SI void store_565_(uint16_t* ptr, size_t tail, U16 r, U16 g, U16 b) {
2949     // Round from [0,255] to [0,31] or [0,63], as if x * (31/255.0f) + 0.5f.
2950     // (Don't feel like you need to find some fundamental truth in these...
2951     // they were brute-force searched.)
2952     U16 R = (r *  9 + 36) / 74,   //  9/74 ≈ 31/255, plus 36/74, about half.
2953         G = (g * 21 + 42) / 85,   // 21/85 = 63/255 exactly.
2954         B = (b *  9 + 36) / 74;
2955     // Pack them back into 15|rrrrr gggggg bbbbb|0.
2956     store(ptr, tail, R << 11
2957                    | G <<  5
2958                    | B <<  0);
2959 }
2960 
2961 STAGE_PP(load_565, const SkRasterPipeline_MemoryCtx* ctx) {
2962     load_565_(ptr_at_xy<const uint16_t>(ctx, dx,dy), tail, &r,&g,&b);
2963     a = 255;
2964 }
2965 STAGE_PP(load_565_dst, const SkRasterPipeline_MemoryCtx* ctx) {
2966     load_565_(ptr_at_xy<const uint16_t>(ctx, dx,dy), tail, &dr,&dg,&db);
2967     da = 255;
2968 }
2969 STAGE_PP(store_565, const SkRasterPipeline_MemoryCtx* ctx) {
2970     store_565_(ptr_at_xy<uint16_t>(ctx, dx,dy), tail, r,g,b);
2971 }
2972 STAGE_GP(gather_565, const SkRasterPipeline_GatherCtx* ctx) {
2973     const uint16_t* ptr;
2974     U32 ix = ix_and_ptr(&ptr, ctx, x,y);
2975     from_565(gather<U16>(ptr, ix), &r, &g, &b);
2976     a = 255;
2977 }
2978 
2979 SI void from_4444(U16 rgba, U16* r, U16* g, U16* b, U16* a) {
2980     // Format for 4444 buffers: 15|rrrr gggg bbbb aaaa|0.
2981     U16 R = (rgba >> 12) & 15,
2982         G = (rgba >>  8) & 15,
2983         B = (rgba >>  4) & 15,
2984         A = (rgba >>  0) & 15;
2985 
2986     // Scale [0,15] to [0,255].
2987     *r = (R << 4) | R;
2988     *g = (G << 4) | G;
2989     *b = (B << 4) | B;
2990     *a = (A << 4) | A;
2991 }
2992 SI void load_4444_(const uint16_t* ptr, size_t tail, U16* r, U16* g, U16* b, U16* a) {
2993     from_4444(load<U16>(ptr, tail), r,g,b,a);
2994 }
2995 SI void store_4444_(uint16_t* ptr, size_t tail, U16 r, U16 g, U16 b, U16 a) {
2996     // Round from [0,255] to [0,15], producing the same value as (x*(15/255.0f) + 0.5f).
2997     U16 R = (r + 8) / 17,
2998         G = (g + 8) / 17,
2999         B = (b + 8) / 17,
3000         A = (a + 8) / 17;
3001     // Pack them back into 15|rrrr gggg bbbb aaaa|0.
3002     store(ptr, tail, R << 12
3003                    | G <<  8
3004                    | B <<  4
3005                    | A <<  0);
3006 }
3007 
3008 STAGE_PP(load_4444, const SkRasterPipeline_MemoryCtx* ctx) {
3009     load_4444_(ptr_at_xy<const uint16_t>(ctx, dx,dy), tail, &r,&g,&b,&a);
3010 }
3011 STAGE_PP(load_4444_dst, const SkRasterPipeline_MemoryCtx* ctx) {
3012     load_4444_(ptr_at_xy<const uint16_t>(ctx, dx,dy), tail, &dr,&dg,&db,&da);
3013 }
3014 STAGE_PP(store_4444, const SkRasterPipeline_MemoryCtx* ctx) {
3015     store_4444_(ptr_at_xy<uint16_t>(ctx, dx,dy), tail, r,g,b,a);
3016 }
3017 STAGE_GP(gather_4444, const SkRasterPipeline_GatherCtx* ctx) {
3018     const uint16_t* ptr;
3019     U32 ix = ix_and_ptr(&ptr, ctx, x,y);
3020     from_4444(gather<U16>(ptr, ix), &r,&g,&b,&a);
3021 }
3022 
3023 // ~~~~~~ 8-bit memory loads and stores ~~~~~~ //
3024 
3025 SI U16 load_8(const uint8_t* ptr, size_t tail) {
3026     return cast<U16>(load<U8>(ptr, tail));
3027 }
3028 SI void store_8(uint8_t* ptr, size_t tail, U16 v) {
3029     store(ptr, tail, cast<U8>(v));
3030 }
3031 
3032 STAGE_PP(load_a8, const SkRasterPipeline_MemoryCtx* ctx) {
3033     r = g = b = 0;
3034     a = load_8(ptr_at_xy<const uint8_t>(ctx, dx,dy), tail);
3035 }
3036 STAGE_PP(load_a8_dst, const SkRasterPipeline_MemoryCtx* ctx) {
3037     dr = dg = db = 0;
3038     da = load_8(ptr_at_xy<const uint8_t>(ctx, dx,dy), tail);
3039 }
3040 STAGE_PP(store_a8, const SkRasterPipeline_MemoryCtx* ctx) {
3041     store_8(ptr_at_xy<uint8_t>(ctx, dx,dy), tail, a);
3042 }
3043 STAGE_GP(gather_a8, const SkRasterPipeline_GatherCtx* ctx) {
3044     const uint8_t* ptr;
3045     U32 ix = ix_and_ptr(&ptr, ctx, x,y);
3046     r = g = b = 0;
3047     a = cast<U16>(gather<U8>(ptr, ix));
3048 }
3049 
3050 STAGE_PP(alpha_to_gray, Ctx::None) {
3051     r = g = b = a;
3052     a = 255;
3053 }
3054 STAGE_PP(alpha_to_gray_dst, Ctx::None) {
3055     dr = dg = db = da;
3056     da = 255;
3057 }
3058 STAGE_PP(luminance_to_alpha, Ctx::None) {
3059     a = (r*54 + g*183 + b*19)/256;  // 0.2126, 0.7152, 0.0722 with 256 denominator.
3060     r = g = b = 0;
3061 }
3062 
3063 // ~~~~~~ Coverage scales / lerps ~~~~~~ //
3064 
3065 STAGE_PP(scale_1_float, const float* f) {
3066     U16 c = from_float(*f);
3067     r = div255( r * c );
3068     g = div255( g * c );
3069     b = div255( b * c );
3070     a = div255( a * c );
3071 }
3072 STAGE_PP(lerp_1_float, const float* f) {
3073     U16 c = from_float(*f);
3074     r = lerp(dr, r, c);
3075     g = lerp(dg, g, c);
3076     b = lerp(db, b, c);
3077     a = lerp(da, a, c);
3078 }
3079 
3080 STAGE_PP(scale_u8, const SkRasterPipeline_MemoryCtx* ctx) {
3081     U16 c = load_8(ptr_at_xy<const uint8_t>(ctx, dx,dy), tail);
3082     r = div255( r * c );
3083     g = div255( g * c );
3084     b = div255( b * c );
3085     a = div255( a * c );
3086 }
3087 STAGE_PP(lerp_u8, const SkRasterPipeline_MemoryCtx* ctx) {
3088     U16 c = load_8(ptr_at_xy<const uint8_t>(ctx, dx,dy), tail);
3089     r = lerp(dr, r, c);
3090     g = lerp(dg, g, c);
3091     b = lerp(db, b, c);
3092     a = lerp(da, a, c);
3093 }
3094 
3095 // Derive alpha's coverage from rgb coverage and the values of src and dst alpha.
3096 SI U16 alpha_coverage_from_rgb_coverage(U16 a, U16 da, U16 cr, U16 cg, U16 cb) {
3097     return if_then_else(a < da, min(cr,cg,cb)
3098                               , max(cr,cg,cb));
3099 }
3100 STAGE_PP(scale_565, const SkRasterPipeline_MemoryCtx* ctx) {
3101     U16 cr,cg,cb;
3102     load_565_(ptr_at_xy<const uint16_t>(ctx, dx,dy), tail, &cr,&cg,&cb);
3103     U16 ca = alpha_coverage_from_rgb_coverage(a,da, cr,cg,cb);
3104 
3105     r = div255( r * cr );
3106     g = div255( g * cg );
3107     b = div255( b * cb );
3108     a = div255( a * ca );
3109 }
3110 STAGE_PP(lerp_565, const SkRasterPipeline_MemoryCtx* ctx) {
3111     U16 cr,cg,cb;
3112     load_565_(ptr_at_xy<const uint16_t>(ctx, dx,dy), tail, &cr,&cg,&cb);
3113     U16 ca = alpha_coverage_from_rgb_coverage(a,da, cr,cg,cb);
3114 
3115     r = lerp(dr, r, cr);
3116     g = lerp(dg, g, cg);
3117     b = lerp(db, b, cb);
3118     a = lerp(da, a, ca);
3119 }
3120 
3121 STAGE_PP(emboss, const SkRasterPipeline_EmbossCtx* ctx) {
3122     U16 mul = load_8(ptr_at_xy<const uint8_t>(&ctx->mul, dx,dy), tail),
3123         add = load_8(ptr_at_xy<const uint8_t>(&ctx->add, dx,dy), tail);
3124 
3125     r = min(div255(r*mul) + add, a);
3126     g = min(div255(g*mul) + add, a);
3127     b = min(div255(b*mul) + add, a);
3128 }
3129 
3130 
3131 // ~~~~~~ Gradient stages ~~~~~~ //
3132 
3133 // Clamp x to [0,1], both sides inclusive (think, gradients).
3134 // Even repeat and mirror funnel through a clamp to handle bad inputs like +Inf, NaN.
3135 SI F clamp_01(F v) { return min(max(0, v), 1); }
3136 
3137 STAGE_GG(clamp_x_1 , Ctx::None) { x = clamp_01(x); }
3138 STAGE_GG(repeat_x_1, Ctx::None) { x = clamp_01(x - floor_(x)); }
3139 STAGE_GG(mirror_x_1, Ctx::None) {
3140     auto two = [](F x){ return x+x; };
3141     x = clamp_01(abs_( (x-1.0f) - two(floor_((x-1.0f)*0.5f)) - 1.0f ));
3142 }
3143 
3144 SI I16 cond_to_mask_16(I32 cond) { return cast<I16>(cond); }
3145 
3146 STAGE_GG(decal_x, SkRasterPipeline_DecalTileCtx* ctx) {
3147     auto w = ctx->limit_x;
3148     unaligned_store(ctx->mask, cond_to_mask_16((0 <= x) & (x < w)));
3149 }
3150 STAGE_GG(decal_y, SkRasterPipeline_DecalTileCtx* ctx) {
3151     auto h = ctx->limit_y;
3152     unaligned_store(ctx->mask, cond_to_mask_16((0 <= y) & (y < h)));
3153 }
3154 STAGE_GG(decal_x_and_y, SkRasterPipeline_DecalTileCtx* ctx) {
3155     auto w = ctx->limit_x;
3156     auto h = ctx->limit_y;
3157     unaligned_store(ctx->mask, cond_to_mask_16((0 <= x) & (x < w) & (0 <= y) & (y < h)));
3158 }
3159 STAGE_PP(check_decal_mask, SkRasterPipeline_DecalTileCtx* ctx) {
3160     auto mask = unaligned_load<U16>(ctx->mask);
3161     r = r & mask;
3162     g = g & mask;
3163     b = b & mask;
3164     a = a & mask;
3165 }
3166 
3167 SI void round_F_to_U16(F    R, F    G, F    B, F    A, bool interpolatedInPremul,
3168                        U16* r, U16* g, U16* b, U16* a) {
3169     auto round = [](F x) { return cast<U16>(x * 255.0f + 0.5f); };
3170 
3171     F limit = interpolatedInPremul ? A
3172                                    : 1;
3173     *r = round(min(max(0,R), limit));
3174     *g = round(min(max(0,G), limit));
3175     *b = round(min(max(0,B), limit));
3176     *a = round(A);  // we assume alpha is already in [0,1].
3177 }
3178 
3179 SI void gradient_lookup(const SkRasterPipeline_GradientCtx* c, U32 idx, F t,
3180                         U16* r, U16* g, U16* b, U16* a) {
3181 
3182     F fr, fg, fb, fa, br, bg, bb, ba;
3183 #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
3184     if (c->stopCount <=8) {
3185         __m256i lo, hi;
3186         split(idx, &lo, &hi);
3187 
3188         fr = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[0]), lo),
3189                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[0]), hi));
3190         br = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[0]), lo),
3191                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[0]), hi));
3192         fg = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[1]), lo),
3193                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[1]), hi));
3194         bg = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[1]), lo),
3195                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[1]), hi));
3196         fb = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[2]), lo),
3197                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[2]), hi));
3198         bb = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[2]), lo),
3199                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[2]), hi));
3200         fa = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[3]), lo),
3201                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[3]), hi));
3202         ba = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[3]), lo),
3203                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[3]), hi));
3204     } else
3205 #endif
3206     {
3207         fr = gather<F>(c->fs[0], idx);
3208         fg = gather<F>(c->fs[1], idx);
3209         fb = gather<F>(c->fs[2], idx);
3210         fa = gather<F>(c->fs[3], idx);
3211         br = gather<F>(c->bs[0], idx);
3212         bg = gather<F>(c->bs[1], idx);
3213         bb = gather<F>(c->bs[2], idx);
3214         ba = gather<F>(c->bs[3], idx);
3215     }
3216     round_F_to_U16(mad(t, fr, br),
3217                    mad(t, fg, bg),
3218                    mad(t, fb, bb),
3219                    mad(t, fa, ba),
3220                    c->interpolatedInPremul,
3221                    r,g,b,a);
3222 }
3223 
3224 STAGE_GP(gradient, const SkRasterPipeline_GradientCtx* c) {
3225     auto t = x;
3226     U32 idx = 0;
3227 
3228     // N.B. The loop starts at 1 because idx 0 is the color to use before the first stop.
3229     for (size_t i = 1; i < c->stopCount; i++) {
3230         idx += if_then_else(t >= c->ts[i], U32(1), U32(0));
3231     }
3232 
3233     gradient_lookup(c, idx, t, &r, &g, &b, &a);
3234 }
3235 
3236 STAGE_GP(evenly_spaced_gradient, const SkRasterPipeline_GradientCtx* c) {
3237     auto t = x;
3238     auto idx = trunc_(t * (c->stopCount-1));
3239     gradient_lookup(c, idx, t, &r, &g, &b, &a);
3240 }
3241 
3242 STAGE_GP(evenly_spaced_2_stop_gradient, const SkRasterPipeline_EvenlySpaced2StopGradientCtx* c) {
3243     auto t = x;
3244     round_F_to_U16(mad(t, c->f[0], c->b[0]),
3245                    mad(t, c->f[1], c->b[1]),
3246                    mad(t, c->f[2], c->b[2]),
3247                    mad(t, c->f[3], c->b[3]),
3248                    c->interpolatedInPremul,
3249                    &r,&g,&b,&a);
3250 }
3251 
3252 STAGE_GG(xy_to_unit_angle, Ctx::None) {
3253     F xabs = abs_(x),
3254       yabs = abs_(y);
3255 
3256     F slope = min(xabs, yabs)/max(xabs, yabs);
3257     F s = slope * slope;
3258 
3259     // Use a 7th degree polynomial to approximate atan.
3260     // This was generated using sollya.gforge.inria.fr.
3261     // A float optimized polynomial was generated using the following command.
3262     // P1 = fpminimax((1/(2*Pi))*atan(x),[|1,3,5,7|],[|24...|],[2^(-40),1],relative);
3263     F phi = slope
3264              * (0.15912117063999176025390625f     + s
3265              * (-5.185396969318389892578125e-2f   + s
3266              * (2.476101927459239959716796875e-2f + s
3267              * (-7.0547382347285747528076171875e-3f))));
3268 
3269     phi = if_then_else(xabs < yabs, 1.0f/4.0f - phi, phi);
3270     phi = if_then_else(x < 0.0f   , 1.0f/2.0f - phi, phi);
3271     phi = if_then_else(y < 0.0f   , 1.0f - phi     , phi);
3272     phi = if_then_else(phi != phi , 0              , phi);  // Check for NaN.
3273     x = phi;
3274 }
3275 STAGE_GG(xy_to_radius, Ctx::None) {
3276     x = sqrt_(x*x + y*y);
3277 }
3278 
3279 // ~~~~~~ Compound stages ~~~~~~ //
3280 
3281 STAGE_PP(srcover_rgba_8888, const SkRasterPipeline_MemoryCtx* ctx) {
3282     auto ptr = ptr_at_xy<uint32_t>(ctx, dx,dy);
3283 
3284     load_8888_(ptr, tail, &dr,&dg,&db,&da);
3285     r = r + div255( dr*inv(a) );
3286     g = g + div255( dg*inv(a) );
3287     b = b + div255( db*inv(a) );
3288     a = a + div255( da*inv(a) );
3289     store_8888_(ptr, tail, r,g,b,a);
3290 }
3291 
3292 #if defined(SK_DISABLE_LOWP_BILERP_CLAMP_CLAMP_STAGE)
3293     static void(*bilerp_clamp_8888)(void) = nullptr;
3294 #else
3295 STAGE_GP(bilerp_clamp_8888, const SkRasterPipeline_GatherCtx* ctx) {
3296     // (cx,cy) are the center of our sample.
3297     F cx = x,
3298       cy = y;
3299 
3300     // All sample points are at the same fractional offset (fx,fy).
3301     // They're the 4 corners of a logical 1x1 pixel surrounding (x,y) at (0.5,0.5) offsets.
3302     F fx = fract(cx + 0.5f),
3303       fy = fract(cy + 0.5f);
3304 
3305     // We'll accumulate the color of all four samples into {r,g,b,a} directly.
3306     r = g = b = a = 0;
3307 
3308     // The first three sample points will calculate their area using math
3309     // just like in the float code above, but the fourth will take up all the rest.
3310     //
3311     // Logically this is the same as doing the math for the fourth pixel too,
3312     // but rounding error makes this a better strategy, keeping opaque opaque, etc.
3313     //
3314     // We can keep up to 8 bits of fractional precision without overflowing 16-bit,
3315     // so our "1.0" area is 256.
3316     const uint16_t bias = 256;
3317     U16 remaining = bias;
3318 
3319     for (float dy = -0.5f; dy <= +0.5f; dy += 1.0f)
3320     for (float dx = -0.5f; dx <= +0.5f; dx += 1.0f) {
3321         // (x,y) are the coordinates of this sample point.
3322         F x = cx + dx,
3323           y = cy + dy;
3324 
3325         // ix_and_ptr() will clamp to the image's bounds for us.
3326         const uint32_t* ptr;
3327         U32 ix = ix_and_ptr(&ptr, ctx, x,y);
3328 
3329         U16 sr,sg,sb,sa;
3330         from_8888(gather<U32>(ptr, ix), &sr,&sg,&sb,&sa);
3331 
3332         // In bilinear interpolation, the 4 pixels at +/- 0.5 offsets from the sample pixel center
3333         // are combined in direct proportion to their area overlapping that logical query pixel.
3334         // At positive offsets, the x-axis contribution to that rectangle is fx,
3335         // or (1-fx) at negative x.  Same deal for y.
3336         F sx = (dx > 0) ? fx : 1.0f - fx,
3337           sy = (dy > 0) ? fy : 1.0f - fy;
3338 
3339         U16 area = (dy == 0.5f && dx == 0.5f) ? remaining
3340                                               : cast<U16>(sx * sy * bias);
3341         for (size_t i = 0; i < N; i++) {
3342             SkASSERT(remaining[i] >= area[i]);
3343         }
3344         remaining -= area;
3345 
3346         r += sr * area;
3347         g += sg * area;
3348         b += sb * area;
3349         a += sa * area;
3350     }
3351 
3352     r = (r + bias/2) / bias;
3353     g = (g + bias/2) / bias;
3354     b = (b + bias/2) / bias;
3355     a = (a + bias/2) / bias;
3356 }
3357 #endif
3358 
3359 // Now we'll add null stand-ins for stages we haven't implemented in lowp.
3360 // If a pipeline uses these stages, it'll boot it out of lowp into highp.
3361 #define NOT_IMPLEMENTED(st) static void (*st)(void) = nullptr;
3362     NOT_IMPLEMENTED(callback)
3363     NOT_IMPLEMENTED(load_src)
3364     NOT_IMPLEMENTED(store_src)
3365     NOT_IMPLEMENTED(load_dst)
3366     NOT_IMPLEMENTED(store_dst)
3367     NOT_IMPLEMENTED(unbounded_set_rgb)
3368     NOT_IMPLEMENTED(unbounded_uniform_color)
3369     NOT_IMPLEMENTED(unpremul)
3370     NOT_IMPLEMENTED(dither)  // TODO
3371     NOT_IMPLEMENTED(from_srgb)
3372     NOT_IMPLEMENTED(to_srgb)
3373     NOT_IMPLEMENTED(load_f16)
3374     NOT_IMPLEMENTED(load_f16_dst)
3375     NOT_IMPLEMENTED(store_f16)
3376     NOT_IMPLEMENTED(gather_f16)
3377     NOT_IMPLEMENTED(load_f32)
3378     NOT_IMPLEMENTED(load_f32_dst)
3379     NOT_IMPLEMENTED(store_f32)
3380     NOT_IMPLEMENTED(gather_f32)
3381     NOT_IMPLEMENTED(load_1010102)
3382     NOT_IMPLEMENTED(load_1010102_dst)
3383     NOT_IMPLEMENTED(store_1010102)
3384     NOT_IMPLEMENTED(gather_1010102)
3385     NOT_IMPLEMENTED(store_u16_be)
3386     NOT_IMPLEMENTED(byte_tables)  // TODO
3387     NOT_IMPLEMENTED(colorburn)
3388     NOT_IMPLEMENTED(colordodge)
3389     NOT_IMPLEMENTED(softlight)
3390     NOT_IMPLEMENTED(hue)
3391     NOT_IMPLEMENTED(saturation)
3392     NOT_IMPLEMENTED(color)
3393     NOT_IMPLEMENTED(luminosity)
3394     NOT_IMPLEMENTED(matrix_3x3)
3395     NOT_IMPLEMENTED(matrix_3x4)
3396     NOT_IMPLEMENTED(matrix_4x5)  // TODO
3397     NOT_IMPLEMENTED(matrix_4x3)  // TODO
3398     NOT_IMPLEMENTED(parametric)
3399     NOT_IMPLEMENTED(gamma)
3400     NOT_IMPLEMENTED(rgb_to_hsl)
3401     NOT_IMPLEMENTED(hsl_to_rgb)
3402     NOT_IMPLEMENTED(gauss_a_to_rgba)  // TODO
3403     NOT_IMPLEMENTED(mirror_x)         // TODO
3404     NOT_IMPLEMENTED(repeat_x)         // TODO
3405     NOT_IMPLEMENTED(mirror_y)         // TODO
3406     NOT_IMPLEMENTED(repeat_y)         // TODO
3407     NOT_IMPLEMENTED(negate_x)
3408     NOT_IMPLEMENTED(bilinear_nx)      // TODO
3409     NOT_IMPLEMENTED(bilinear_ny)      // TODO
3410     NOT_IMPLEMENTED(bilinear_px)      // TODO
3411     NOT_IMPLEMENTED(bilinear_py)      // TODO
3412     NOT_IMPLEMENTED(bicubic_n3x)      // TODO
3413     NOT_IMPLEMENTED(bicubic_n1x)      // TODO
3414     NOT_IMPLEMENTED(bicubic_p1x)      // TODO
3415     NOT_IMPLEMENTED(bicubic_p3x)      // TODO
3416     NOT_IMPLEMENTED(bicubic_n3y)      // TODO
3417     NOT_IMPLEMENTED(bicubic_n1y)      // TODO
3418     NOT_IMPLEMENTED(bicubic_p1y)      // TODO
3419     NOT_IMPLEMENTED(bicubic_p3y)      // TODO
3420     NOT_IMPLEMENTED(save_xy)          // TODO
3421     NOT_IMPLEMENTED(accumulate)       // TODO
3422     NOT_IMPLEMENTED(xy_to_2pt_conical_well_behaved)
3423     NOT_IMPLEMENTED(xy_to_2pt_conical_strip)
3424     NOT_IMPLEMENTED(xy_to_2pt_conical_focal_on_circle)
3425     NOT_IMPLEMENTED(xy_to_2pt_conical_smaller)
3426     NOT_IMPLEMENTED(xy_to_2pt_conical_greater)
3427     NOT_IMPLEMENTED(alter_2pt_conical_compensate_focal)
3428     NOT_IMPLEMENTED(alter_2pt_conical_unswap)
3429     NOT_IMPLEMENTED(mask_2pt_conical_nan)
3430     NOT_IMPLEMENTED(mask_2pt_conical_degenerates)
3431     NOT_IMPLEMENTED(apply_vector_mask)
3432 #undef NOT_IMPLEMENTED
3433 
3434 #endif//defined(JUMPER_IS_SCALAR) controlling whether we build lowp stages
3435 }  // namespace lowp
3436 
3437 }  // namespace SK_OPTS_NS
3438 
3439 #endif//SkRasterPipeline_opts_DEFINED
3440