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_rgba,const float * ptr)1069 STAGE(load_rgba, 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_rgba,float * ptr)1077 STAGE(store_rgba, 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 // Most blend modes apply the same logic to each channel.
1085 #define BLEND_MODE(name)                       \
1086     SI F name##_channel(F s, F d, F sa, F da); \
1087     STAGE(name, Ctx::None) {                   \
1088         r = name##_channel(r,dr,a,da);         \
1089         g = name##_channel(g,dg,a,da);         \
1090         b = name##_channel(b,db,a,da);         \
1091         a = name##_channel(a,da,a,da);         \
1092     }                                          \
1093     SI F name##_channel(F s, F d, F sa, F da)
1094 
inv(F x)1095 SI F inv(F x) { return 1.0f - x; }
two(F x)1096 SI F two(F x) { return x + x; }
1097 
1098 
BLEND_MODE(clear)1099 BLEND_MODE(clear)    { return 0; }
BLEND_MODE(srcatop)1100 BLEND_MODE(srcatop)  { return s*da + d*inv(sa); }
BLEND_MODE(dstatop)1101 BLEND_MODE(dstatop)  { return d*sa + s*inv(da); }
BLEND_MODE(srcin)1102 BLEND_MODE(srcin)    { return s * da; }
BLEND_MODE(dstin)1103 BLEND_MODE(dstin)    { return d * sa; }
BLEND_MODE(srcout)1104 BLEND_MODE(srcout)   { return s * inv(da); }
BLEND_MODE(dstout)1105 BLEND_MODE(dstout)   { return d * inv(sa); }
BLEND_MODE(srcover)1106 BLEND_MODE(srcover)  { return mad(d, inv(sa), s); }
BLEND_MODE(dstover)1107 BLEND_MODE(dstover)  { return mad(s, inv(da), d); }
1108 
BLEND_MODE(modulate)1109 BLEND_MODE(modulate) { return s*d; }
BLEND_MODE(multiply)1110 BLEND_MODE(multiply) { return s*inv(da) + d*inv(sa) + s*d; }
BLEND_MODE(plus_)1111 BLEND_MODE(plus_)    { return min(s + d, 1.0f); }  // We can clamp to either 1 or sa.
BLEND_MODE(screen)1112 BLEND_MODE(screen)   { return s + d - s*d; }
BLEND_MODE(xor_)1113 BLEND_MODE(xor_)     { return s*inv(da) + d*inv(sa); }
1114 #undef BLEND_MODE
1115 
1116 // Most other blend modes apply the same logic to colors, and srcover to alpha.
1117 #define BLEND_MODE(name)                       \
1118     SI F name##_channel(F s, F d, F sa, F da); \
1119     STAGE(name, Ctx::None) {                   \
1120         r = name##_channel(r,dr,a,da);         \
1121         g = name##_channel(g,dg,a,da);         \
1122         b = name##_channel(b,db,a,da);         \
1123         a = mad(da, inv(a), a);                \
1124     }                                          \
1125     SI F name##_channel(F s, F d, F sa, F da)
1126 
BLEND_MODE(darken)1127 BLEND_MODE(darken)     { return s + d -     max(s*da, d*sa) ; }
BLEND_MODE(lighten)1128 BLEND_MODE(lighten)    { return s + d -     min(s*da, d*sa) ; }
BLEND_MODE(difference)1129 BLEND_MODE(difference) { return s + d - two(min(s*da, d*sa)); }
BLEND_MODE(exclusion)1130 BLEND_MODE(exclusion)  { return s + d - two(s*d); }
1131 
BLEND_MODE(colorburn)1132 BLEND_MODE(colorburn) {
1133     return if_then_else(d == da,    d +    s*inv(da),
1134            if_then_else(s ==  0, /* s + */ d*inv(sa),
1135                                  sa*(da - min(da, (da-d)*sa*rcp(s))) + s*inv(da) + d*inv(sa)));
1136 }
BLEND_MODE(colordodge)1137 BLEND_MODE(colordodge) {
1138     return if_then_else(d ==  0, /* d + */ s*inv(da),
1139            if_then_else(s == sa,    s +    d*inv(sa),
1140                                  sa*min(da, (d*sa)*rcp(sa - s)) + s*inv(da) + d*inv(sa)));
1141 }
BLEND_MODE(hardlight)1142 BLEND_MODE(hardlight) {
1143     return s*inv(da) + d*inv(sa)
1144          + if_then_else(two(s) <= sa, two(s*d), sa*da - two((da-d)*(sa-s)));
1145 }
BLEND_MODE(overlay)1146 BLEND_MODE(overlay) {
1147     return s*inv(da) + d*inv(sa)
1148          + if_then_else(two(d) <= da, two(s*d), sa*da - two((da-d)*(sa-s)));
1149 }
1150 
BLEND_MODE(softlight)1151 BLEND_MODE(softlight) {
1152     F m  = if_then_else(da > 0, d / da, 0),
1153       s2 = two(s),
1154       m4 = two(two(m));
1155 
1156     // The logic forks three ways:
1157     //    1. dark src?
1158     //    2. light src, dark dst?
1159     //    3. light src, light dst?
1160     F darkSrc = d*(sa + (s2 - sa)*(1.0f - m)),     // Used in case 1.
1161       darkDst = (m4*m4 + m4)*(m - 1.0f) + 7.0f*m,  // Used in case 2.
1162       liteDst = rcp(rsqrt(m)) - m,                 // Used in case 3.
1163       liteSrc = d*sa + da*(s2 - sa) * if_then_else(two(two(d)) <= da, darkDst, liteDst); // 2 or 3?
1164     return s*inv(da) + d*inv(sa) + if_then_else(s2 <= sa, darkSrc, liteSrc);      // 1 or (2 or 3)?
1165 }
1166 #undef BLEND_MODE
1167 
1168 // We're basing our implemenation of non-separable blend modes on
1169 //   https://www.w3.org/TR/compositing-1/#blendingnonseparable.
1170 // and
1171 //   https://www.khronos.org/registry/OpenGL/specs/es/3.2/es_spec_3.2.pdf
1172 // They're equivalent, but ES' math has been better simplified.
1173 //
1174 // Anything extra we add beyond that is to make the math work with premul inputs.
1175 
max(F r,F g,F b)1176 SI F max(F r, F g, F b) { return max(r, max(g, b)); }
min(F r,F g,F b)1177 SI F min(F r, F g, F b) { return min(r, min(g, b)); }
1178 
sat(F r,F g,F b)1179 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)1180 SI F lum(F r, F g, F b) { return r*0.30f + g*0.59f + b*0.11f; }
1181 
set_sat(F * r,F * g,F * b,F s)1182 SI void set_sat(F* r, F* g, F* b, F s) {
1183     F mn  = min(*r,*g,*b),
1184       mx  = max(*r,*g,*b),
1185       sat = mx - mn;
1186 
1187     // Map min channel to 0, max channel to s, and scale the middle proportionally.
1188     auto scale = [=](F c) {
1189         return if_then_else(sat == 0, 0, (c - mn) * s / sat);
1190     };
1191     *r = scale(*r);
1192     *g = scale(*g);
1193     *b = scale(*b);
1194 }
set_lum(F * r,F * g,F * b,F l)1195 SI void set_lum(F* r, F* g, F* b, F l) {
1196     F diff = l - lum(*r, *g, *b);
1197     *r += diff;
1198     *g += diff;
1199     *b += diff;
1200 }
clip_color(F * r,F * g,F * b,F a)1201 SI void clip_color(F* r, F* g, F* b, F a) {
1202     F mn = min(*r, *g, *b),
1203       mx = max(*r, *g, *b),
1204       l  = lum(*r, *g, *b);
1205 
1206     auto clip = [=](F c) {
1207         c = if_then_else(mn >= 0, c, l + (c - l) * (    l) / (l - mn)   );
1208         c = if_then_else(mx >  a,    l + (c - l) * (a - l) / (mx - l), c);
1209         c = max(c, 0);  // Sometimes without this we may dip just a little negative.
1210         return c;
1211     };
1212     *r = clip(*r);
1213     *g = clip(*g);
1214     *b = clip(*b);
1215 }
1216 
STAGE(hue,Ctx::None)1217 STAGE(hue, Ctx::None) {
1218     F R = r*a,
1219       G = g*a,
1220       B = b*a;
1221 
1222     set_sat(&R, &G, &B, sat(dr,dg,db)*a);
1223     set_lum(&R, &G, &B, lum(dr,dg,db)*a);
1224     clip_color(&R,&G,&B, a*da);
1225 
1226     r = r*inv(da) + dr*inv(a) + R;
1227     g = g*inv(da) + dg*inv(a) + G;
1228     b = b*inv(da) + db*inv(a) + B;
1229     a = a + da - a*da;
1230 }
STAGE(saturation,Ctx::None)1231 STAGE(saturation, Ctx::None) {
1232     F R = dr*a,
1233       G = dg*a,
1234       B = db*a;
1235 
1236     set_sat(&R, &G, &B, sat( r, g, b)*da);
1237     set_lum(&R, &G, &B, lum(dr,dg,db)* a);  // (This is not redundant.)
1238     clip_color(&R,&G,&B, a*da);
1239 
1240     r = r*inv(da) + dr*inv(a) + R;
1241     g = g*inv(da) + dg*inv(a) + G;
1242     b = b*inv(da) + db*inv(a) + B;
1243     a = a + da - a*da;
1244 }
STAGE(color,Ctx::None)1245 STAGE(color, Ctx::None) {
1246     F R = r*da,
1247       G = g*da,
1248       B = b*da;
1249 
1250     set_lum(&R, &G, &B, lum(dr,dg,db)*a);
1251     clip_color(&R,&G,&B, a*da);
1252 
1253     r = r*inv(da) + dr*inv(a) + R;
1254     g = g*inv(da) + dg*inv(a) + G;
1255     b = b*inv(da) + db*inv(a) + B;
1256     a = a + da - a*da;
1257 }
STAGE(luminosity,Ctx::None)1258 STAGE(luminosity, Ctx::None) {
1259     F R = dr*a,
1260       G = dg*a,
1261       B = db*a;
1262 
1263     set_lum(&R, &G, &B, lum(r,g,b)*da);
1264     clip_color(&R,&G,&B, a*da);
1265 
1266     r = r*inv(da) + dr*inv(a) + R;
1267     g = g*inv(da) + dg*inv(a) + G;
1268     b = b*inv(da) + db*inv(a) + B;
1269     a = a + da - a*da;
1270 }
1271 
STAGE(srcover_rgba_8888,const SkRasterPipeline_MemoryCtx * ctx)1272 STAGE(srcover_rgba_8888, const SkRasterPipeline_MemoryCtx* ctx) {
1273     auto ptr = ptr_at_xy<uint32_t>(ctx, dx,dy);
1274 
1275     U32 dst = load<U32>(ptr, tail);
1276     dr = cast((dst      ) & 0xff);
1277     dg = cast((dst >>  8) & 0xff);
1278     db = cast((dst >> 16) & 0xff);
1279     da = cast((dst >> 24)       );
1280     // {dr,dg,db,da} are in [0,255]
1281     // { r, g, b, a} are in [0,  1] (but may be out of gamut)
1282 
1283     r = mad(dr, inv(a), r*255.0f);
1284     g = mad(dg, inv(a), g*255.0f);
1285     b = mad(db, inv(a), b*255.0f);
1286     a = mad(da, inv(a), a*255.0f);
1287     // { r, g, b, a} are now in [0,255]  (but may be out of gamut)
1288 
1289     // to_unorm() clamps back to gamut.  Scaling by 1 since we're already 255-biased.
1290     dst = to_unorm(r, 1, 255)
1291         | to_unorm(g, 1, 255) <<  8
1292         | to_unorm(b, 1, 255) << 16
1293         | to_unorm(a, 1, 255) << 24;
1294     store(ptr, dst, tail);
1295 }
1296 
STAGE(clamp_0,Ctx::None)1297 STAGE(clamp_0, Ctx::None) {
1298     r = max(r, 0);
1299     g = max(g, 0);
1300     b = max(b, 0);
1301     a = max(a, 0);
1302 }
1303 
STAGE(clamp_1,Ctx::None)1304 STAGE(clamp_1, Ctx::None) {
1305     r = min(r, 1.0f);
1306     g = min(g, 1.0f);
1307     b = min(b, 1.0f);
1308     a = min(a, 1.0f);
1309 }
1310 
STAGE(clamp_a,Ctx::None)1311 STAGE(clamp_a, Ctx::None) {
1312     a = min(a, 1.0f);
1313     r = min(r, a);
1314     g = min(g, a);
1315     b = min(b, a);
1316 }
1317 
STAGE(clamp_a_dst,Ctx::None)1318 STAGE(clamp_a_dst, Ctx::None) {
1319     da = min(da, 1.0f);
1320     dr = min(dr, da);
1321     dg = min(dg, da);
1322     db = min(db, da);
1323 }
1324 
STAGE(clamp_gamut,Ctx::None)1325 STAGE(clamp_gamut, Ctx::None) {
1326     // If you're using this stage, a should already be in [0,1].
1327     r = min(max(r, 0), a);
1328     g = min(max(g, 0), a);
1329     b = min(max(b, 0), a);
1330 }
1331 
STAGE(set_rgb,const float * rgb)1332 STAGE(set_rgb, const float* rgb) {
1333     r = rgb[0];
1334     g = rgb[1];
1335     b = rgb[2];
1336 }
STAGE(unbounded_set_rgb,const float * rgb)1337 STAGE(unbounded_set_rgb, const float* rgb) {
1338     r = rgb[0];
1339     g = rgb[1];
1340     b = rgb[2];
1341 }
1342 
STAGE(swap_rb,Ctx::None)1343 STAGE(swap_rb, Ctx::None) {
1344     auto tmp = r;
1345     r = b;
1346     b = tmp;
1347 }
STAGE(swap_rb_dst,Ctx::None)1348 STAGE(swap_rb_dst, Ctx::None) {
1349     auto tmp = dr;
1350     dr = db;
1351     db = tmp;
1352 }
1353 
STAGE(move_src_dst,Ctx::None)1354 STAGE(move_src_dst, Ctx::None) {
1355     dr = r;
1356     dg = g;
1357     db = b;
1358     da = a;
1359 }
STAGE(move_dst_src,Ctx::None)1360 STAGE(move_dst_src, Ctx::None) {
1361     r = dr;
1362     g = dg;
1363     b = db;
1364     a = da;
1365 }
1366 
STAGE(premul,Ctx::None)1367 STAGE(premul, Ctx::None) {
1368     r = r * a;
1369     g = g * a;
1370     b = b * a;
1371 }
STAGE(premul_dst,Ctx::None)1372 STAGE(premul_dst, Ctx::None) {
1373     dr = dr * da;
1374     dg = dg * da;
1375     db = db * da;
1376 }
STAGE(unpremul,Ctx::None)1377 STAGE(unpremul, Ctx::None) {
1378     float inf = bit_cast<float>(0x7f800000);
1379     auto scale = if_then_else(1.0f/a < inf, 1.0f/a, 0);
1380     r *= scale;
1381     g *= scale;
1382     b *= scale;
1383 }
1384 
STAGE(force_opaque,Ctx::None)1385 STAGE(force_opaque    , Ctx::None) {  a = 1; }
STAGE(force_opaque_dst,Ctx::None)1386 STAGE(force_opaque_dst, Ctx::None) { da = 1; }
1387 
STAGE(rgb_to_hsl,Ctx::None)1388 STAGE(rgb_to_hsl, Ctx::None) {
1389     F mx = max(r,g,b),
1390       mn = min(r,g,b),
1391       d = mx - mn,
1392       d_rcp = 1.0f / d;
1393 
1394     F h = (1/6.0f) *
1395           if_then_else(mx == mn, 0,
1396           if_then_else(mx ==  r, (g-b)*d_rcp + if_then_else(g < b, 6.0f, 0),
1397           if_then_else(mx ==  g, (b-r)*d_rcp + 2.0f,
1398                                  (r-g)*d_rcp + 4.0f)));
1399 
1400     F l = (mx + mn) * 0.5f;
1401     F s = if_then_else(mx == mn, 0,
1402                        d / if_then_else(l > 0.5f, 2.0f-mx-mn, mx+mn));
1403 
1404     r = h;
1405     g = s;
1406     b = l;
1407 }
STAGE(hsl_to_rgb,Ctx::None)1408 STAGE(hsl_to_rgb, Ctx::None) {
1409     F h = r,
1410       s = g,
1411       l = b;
1412 
1413     F q = l + if_then_else(l >= 0.5f, s - l*s, l*s),
1414       p = 2.0f*l - q;
1415 
1416     auto hue_to_rgb = [&](F t) {
1417         t = fract(t);
1418 
1419         F r = p;
1420         r = if_then_else(t >= 4/6.0f, r, p + (q-p)*(4.0f - 6.0f*t));
1421         r = if_then_else(t >= 3/6.0f, r, q);
1422         r = if_then_else(t >= 1/6.0f, r, p + (q-p)*(       6.0f*t));
1423         return r;
1424     };
1425 
1426     r = if_then_else(s == 0, l, hue_to_rgb(h + (1/3.0f)));
1427     g = if_then_else(s == 0, l, hue_to_rgb(h           ));
1428     b = if_then_else(s == 0, l, hue_to_rgb(h - (1/3.0f)));
1429 }
1430 
1431 // 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)1432 SI F alpha_coverage_from_rgb_coverage(F a, F da, F cr, F cg, F cb) {
1433     return if_then_else(a < da, min(cr,cg,cb)
1434                               , max(cr,cg,cb));
1435 }
1436 
STAGE(scale_1_float,const float * c)1437 STAGE(scale_1_float, const float* c) {
1438     r = r * *c;
1439     g = g * *c;
1440     b = b * *c;
1441     a = a * *c;
1442 }
STAGE(scale_u8,const SkRasterPipeline_MemoryCtx * ctx)1443 STAGE(scale_u8, const SkRasterPipeline_MemoryCtx* ctx) {
1444     auto ptr = ptr_at_xy<const uint8_t>(ctx, dx,dy);
1445 
1446     auto scales = load<U8>(ptr, tail);
1447     auto c = from_byte(scales);
1448 
1449     r = r * c;
1450     g = g * c;
1451     b = b * c;
1452     a = a * c;
1453 }
STAGE(scale_565,const SkRasterPipeline_MemoryCtx * ctx)1454 STAGE(scale_565, const SkRasterPipeline_MemoryCtx* ctx) {
1455     auto ptr = ptr_at_xy<const uint16_t>(ctx, dx,dy);
1456 
1457     F cr,cg,cb;
1458     from_565(load<U16>(ptr, tail), &cr, &cg, &cb);
1459 
1460     F ca = alpha_coverage_from_rgb_coverage(a,da, cr,cg,cb);
1461 
1462     r = r * cr;
1463     g = g * cg;
1464     b = b * cb;
1465     a = a * ca;
1466 }
1467 
lerp(F from,F to,F t)1468 SI F lerp(F from, F to, F t) {
1469     return mad(to-from, t, from);
1470 }
1471 
STAGE(lerp_1_float,const float * c)1472 STAGE(lerp_1_float, const float* c) {
1473     r = lerp(dr, r, *c);
1474     g = lerp(dg, g, *c);
1475     b = lerp(db, b, *c);
1476     a = lerp(da, a, *c);
1477 }
STAGE(lerp_u8,const SkRasterPipeline_MemoryCtx * ctx)1478 STAGE(lerp_u8, const SkRasterPipeline_MemoryCtx* ctx) {
1479     auto ptr = ptr_at_xy<const uint8_t>(ctx, dx,dy);
1480 
1481     auto scales = load<U8>(ptr, tail);
1482     auto c = from_byte(scales);
1483 
1484     r = lerp(dr, r, c);
1485     g = lerp(dg, g, c);
1486     b = lerp(db, b, c);
1487     a = lerp(da, a, c);
1488 }
STAGE(lerp_565,const SkRasterPipeline_MemoryCtx * ctx)1489 STAGE(lerp_565, const SkRasterPipeline_MemoryCtx* ctx) {
1490     auto ptr = ptr_at_xy<const uint16_t>(ctx, dx,dy);
1491 
1492     F cr,cg,cb;
1493     from_565(load<U16>(ptr, tail), &cr, &cg, &cb);
1494 
1495     F ca = alpha_coverage_from_rgb_coverage(a,da, cr,cg,cb);
1496 
1497     r = lerp(dr, r, cr);
1498     g = lerp(dg, g, cg);
1499     b = lerp(db, b, cb);
1500     a = lerp(da, a, ca);
1501 }
1502 
STAGE(emboss,const SkRasterPipeline_EmbossCtx * ctx)1503 STAGE(emboss, const SkRasterPipeline_EmbossCtx* ctx) {
1504     auto mptr = ptr_at_xy<const uint8_t>(&ctx->mul, dx,dy),
1505          aptr = ptr_at_xy<const uint8_t>(&ctx->add, dx,dy);
1506 
1507     F mul = from_byte(load<U8>(mptr, tail)),
1508       add = from_byte(load<U8>(aptr, tail));
1509 
1510     r = mad(r, mul, add);
1511     g = mad(g, mul, add);
1512     b = mad(b, mul, add);
1513 }
1514 
STAGE(byte_tables,const void * ctx)1515 STAGE(byte_tables, const void* ctx) {  // TODO: rename Tables SkRasterPipeline_ByteTablesCtx
1516     struct Tables { const uint8_t *r, *g, *b, *a; };
1517     auto tables = (const Tables*)ctx;
1518 
1519     r = from_byte(gather(tables->r, to_unorm(r, 255)));
1520     g = from_byte(gather(tables->g, to_unorm(g, 255)));
1521     b = from_byte(gather(tables->b, to_unorm(b, 255)));
1522     a = from_byte(gather(tables->a, to_unorm(a, 255)));
1523 }
1524 
strip_sign(F x,U32 * sign)1525 SI F strip_sign(F x, U32* sign) {
1526     U32 bits = bit_cast<U32>(x);
1527     *sign = bits & 0x80000000;
1528     return bit_cast<F>(bits ^ *sign);
1529 }
1530 
apply_sign(F x,U32 sign)1531 SI F apply_sign(F x, U32 sign) {
1532     return bit_cast<F>(sign | bit_cast<U32>(x));
1533 }
1534 
STAGE(parametric,const skcms_TransferFunction * ctx)1535 STAGE(parametric, const skcms_TransferFunction* ctx) {
1536     auto fn = [&](F v) {
1537         U32 sign;
1538         v = strip_sign(v, &sign);
1539 
1540         F r = if_then_else(v <= ctx->d, mad(ctx->c, v, ctx->f)
1541                                       , approx_powf(mad(ctx->a, v, ctx->b), ctx->g) + ctx->e);
1542         return apply_sign(r, sign);
1543     };
1544     r = fn(r);
1545     g = fn(g);
1546     b = fn(b);
1547 }
1548 
STAGE(gamma,const float * G)1549 STAGE(gamma, const float* G) {
1550     auto fn = [&](F v) {
1551         U32 sign;
1552         v = strip_sign(v, &sign);
1553         return apply_sign(approx_powf(v, *G), sign);
1554     };
1555     r = fn(r);
1556     g = fn(g);
1557     b = fn(b);
1558 }
1559 
STAGE(from_srgb,Ctx::None)1560 STAGE(from_srgb, Ctx::None) {
1561     auto fn = [](F s) {
1562         U32 sign;
1563         s = strip_sign(s, &sign);
1564         auto lo = s * (1/12.92f);
1565         auto hi = mad(s*s, mad(s, 0.3000f, 0.6975f), 0.0025f);
1566         return apply_sign(if_then_else(s < 0.055f, lo, hi), sign);
1567     };
1568     r = fn(r);
1569     g = fn(g);
1570     b = fn(b);
1571 }
STAGE(to_srgb,Ctx::None)1572 STAGE(to_srgb, Ctx::None) {
1573     auto fn = [](F l) {
1574         U32 sign;
1575         l = strip_sign(l, &sign);
1576         // We tweak c and d for each instruction set to make sure fn(1) is exactly 1.
1577     #if defined(JUMPER_IS_AVX512)
1578         const float c = 1.130026340485f,
1579                     d = 0.141387879848f;
1580     #elif defined(JUMPER_IS_SSE2) || defined(JUMPER_IS_SSE41) || \
1581           defined(JUMPER_IS_AVX ) || defined(JUMPER_IS_HSW )
1582         const float c = 1.130048394203f,
1583                     d = 0.141357362270f;
1584     #elif defined(JUMPER_IS_NEON)
1585         const float c = 1.129999995232f,
1586                     d = 0.141381442547f;
1587     #else
1588         const float c = 1.129999995232f,
1589                     d = 0.141377761960f;
1590     #endif
1591         F t = rsqrt(l);
1592         auto lo = l * 12.92f;
1593         auto hi = mad(t, mad(t, -0.0024542345f, 0.013832027f), c)
1594                 * rcp(d + t);
1595         return apply_sign(if_then_else(l < 0.00465985f, lo, hi), sign);
1596     };
1597     r = fn(r);
1598     g = fn(g);
1599     b = fn(b);
1600 }
1601 
STAGE(load_a8,const SkRasterPipeline_MemoryCtx * ctx)1602 STAGE(load_a8, const SkRasterPipeline_MemoryCtx* ctx) {
1603     auto ptr = ptr_at_xy<const uint8_t>(ctx, dx,dy);
1604 
1605     r = g = b = 0.0f;
1606     a = from_byte(load<U8>(ptr, tail));
1607 }
STAGE(load_a8_dst,const SkRasterPipeline_MemoryCtx * ctx)1608 STAGE(load_a8_dst, const SkRasterPipeline_MemoryCtx* ctx) {
1609     auto ptr = ptr_at_xy<const uint8_t>(ctx, dx,dy);
1610 
1611     dr = dg = db = 0.0f;
1612     da = from_byte(load<U8>(ptr, tail));
1613 }
STAGE(gather_a8,const SkRasterPipeline_GatherCtx * ctx)1614 STAGE(gather_a8, const SkRasterPipeline_GatherCtx* ctx) {
1615     const uint8_t* ptr;
1616     U32 ix = ix_and_ptr(&ptr, ctx, r,g);
1617     r = g = b = 0.0f;
1618     a = from_byte(gather(ptr, ix));
1619 }
STAGE(store_a8,const SkRasterPipeline_MemoryCtx * ctx)1620 STAGE(store_a8, const SkRasterPipeline_MemoryCtx* ctx) {
1621     auto ptr = ptr_at_xy<uint8_t>(ctx, dx,dy);
1622 
1623     U8 packed = pack(pack(to_unorm(a, 255)));
1624     store(ptr, packed, tail);
1625 }
1626 
STAGE(load_565,const SkRasterPipeline_MemoryCtx * ctx)1627 STAGE(load_565, const SkRasterPipeline_MemoryCtx* ctx) {
1628     auto ptr = ptr_at_xy<const uint16_t>(ctx, dx,dy);
1629 
1630     from_565(load<U16>(ptr, tail), &r,&g,&b);
1631     a = 1.0f;
1632 }
STAGE(load_565_dst,const SkRasterPipeline_MemoryCtx * ctx)1633 STAGE(load_565_dst, const SkRasterPipeline_MemoryCtx* ctx) {
1634     auto ptr = ptr_at_xy<const uint16_t>(ctx, dx,dy);
1635 
1636     from_565(load<U16>(ptr, tail), &dr,&dg,&db);
1637     da = 1.0f;
1638 }
STAGE(gather_565,const SkRasterPipeline_GatherCtx * ctx)1639 STAGE(gather_565, const SkRasterPipeline_GatherCtx* ctx) {
1640     const uint16_t* ptr;
1641     U32 ix = ix_and_ptr(&ptr, ctx, r,g);
1642     from_565(gather(ptr, ix), &r,&g,&b);
1643     a = 1.0f;
1644 }
STAGE(store_565,const SkRasterPipeline_MemoryCtx * ctx)1645 STAGE(store_565, const SkRasterPipeline_MemoryCtx* ctx) {
1646     auto ptr = ptr_at_xy<uint16_t>(ctx, dx,dy);
1647 
1648     U16 px = pack( to_unorm(r, 31) << 11
1649                  | to_unorm(g, 63) <<  5
1650                  | to_unorm(b, 31)      );
1651     store(ptr, px, tail);
1652 }
1653 
STAGE(load_4444,const SkRasterPipeline_MemoryCtx * ctx)1654 STAGE(load_4444, const SkRasterPipeline_MemoryCtx* ctx) {
1655     auto ptr = ptr_at_xy<const uint16_t>(ctx, dx,dy);
1656     from_4444(load<U16>(ptr, tail), &r,&g,&b,&a);
1657 }
STAGE(load_4444_dst,const SkRasterPipeline_MemoryCtx * ctx)1658 STAGE(load_4444_dst, const SkRasterPipeline_MemoryCtx* ctx) {
1659     auto ptr = ptr_at_xy<const uint16_t>(ctx, dx,dy);
1660     from_4444(load<U16>(ptr, tail), &dr,&dg,&db,&da);
1661 }
STAGE(gather_4444,const SkRasterPipeline_GatherCtx * ctx)1662 STAGE(gather_4444, const SkRasterPipeline_GatherCtx* ctx) {
1663     const uint16_t* ptr;
1664     U32 ix = ix_and_ptr(&ptr, ctx, r,g);
1665     from_4444(gather(ptr, ix), &r,&g,&b,&a);
1666 }
STAGE(store_4444,const SkRasterPipeline_MemoryCtx * ctx)1667 STAGE(store_4444, const SkRasterPipeline_MemoryCtx* ctx) {
1668     auto ptr = ptr_at_xy<uint16_t>(ctx, dx,dy);
1669     U16 px = pack( to_unorm(r, 15) << 12
1670                  | to_unorm(g, 15) <<  8
1671                  | to_unorm(b, 15) <<  4
1672                  | to_unorm(a, 15)      );
1673     store(ptr, px, tail);
1674 }
1675 
STAGE(load_8888,const SkRasterPipeline_MemoryCtx * ctx)1676 STAGE(load_8888, const SkRasterPipeline_MemoryCtx* ctx) {
1677     auto ptr = ptr_at_xy<const uint32_t>(ctx, dx,dy);
1678     from_8888(load<U32>(ptr, tail), &r,&g,&b,&a);
1679 }
STAGE(load_8888_dst,const SkRasterPipeline_MemoryCtx * ctx)1680 STAGE(load_8888_dst, const SkRasterPipeline_MemoryCtx* ctx) {
1681     auto ptr = ptr_at_xy<const uint32_t>(ctx, dx,dy);
1682     from_8888(load<U32>(ptr, tail), &dr,&dg,&db,&da);
1683 }
STAGE(gather_8888,const SkRasterPipeline_GatherCtx * ctx)1684 STAGE(gather_8888, const SkRasterPipeline_GatherCtx* ctx) {
1685     const uint32_t* ptr;
1686     U32 ix = ix_and_ptr(&ptr, ctx, r,g);
1687     from_8888(gather(ptr, ix), &r,&g,&b,&a);
1688 }
STAGE(store_8888,const SkRasterPipeline_MemoryCtx * ctx)1689 STAGE(store_8888, const SkRasterPipeline_MemoryCtx* ctx) {
1690     auto ptr = ptr_at_xy<uint32_t>(ctx, dx,dy);
1691 
1692     U32 px = to_unorm(r, 255)
1693            | to_unorm(g, 255) <<  8
1694            | to_unorm(b, 255) << 16
1695            | to_unorm(a, 255) << 24;
1696     store(ptr, px, tail);
1697 }
1698 
STAGE(load_1010102,const SkRasterPipeline_MemoryCtx * ctx)1699 STAGE(load_1010102, const SkRasterPipeline_MemoryCtx* ctx) {
1700     auto ptr = ptr_at_xy<const uint32_t>(ctx, dx,dy);
1701     from_1010102(load<U32>(ptr, tail), &r,&g,&b,&a);
1702 }
STAGE(load_1010102_dst,const SkRasterPipeline_MemoryCtx * ctx)1703 STAGE(load_1010102_dst, const SkRasterPipeline_MemoryCtx* ctx) {
1704     auto ptr = ptr_at_xy<const uint32_t>(ctx, dx,dy);
1705     from_1010102(load<U32>(ptr, tail), &dr,&dg,&db,&da);
1706 }
STAGE(gather_1010102,const SkRasterPipeline_GatherCtx * ctx)1707 STAGE(gather_1010102, const SkRasterPipeline_GatherCtx* ctx) {
1708     const uint32_t* ptr;
1709     U32 ix = ix_and_ptr(&ptr, ctx, r,g);
1710     from_1010102(gather(ptr, ix), &r,&g,&b,&a);
1711 }
STAGE(store_1010102,const SkRasterPipeline_MemoryCtx * ctx)1712 STAGE(store_1010102, const SkRasterPipeline_MemoryCtx* ctx) {
1713     auto ptr = ptr_at_xy<uint32_t>(ctx, dx,dy);
1714 
1715     U32 px = to_unorm(r, 1023)
1716            | to_unorm(g, 1023) << 10
1717            | to_unorm(b, 1023) << 20
1718            | to_unorm(a,    3) << 30;
1719     store(ptr, px, tail);
1720 }
1721 
STAGE(load_f16,const SkRasterPipeline_MemoryCtx * ctx)1722 STAGE(load_f16, const SkRasterPipeline_MemoryCtx* ctx) {
1723     auto ptr = ptr_at_xy<const uint64_t>(ctx, dx,dy);
1724 
1725     U16 R,G,B,A;
1726     load4((const uint16_t*)ptr,tail, &R,&G,&B,&A);
1727     r = from_half(R);
1728     g = from_half(G);
1729     b = from_half(B);
1730     a = from_half(A);
1731 }
STAGE(load_f16_dst,const SkRasterPipeline_MemoryCtx * ctx)1732 STAGE(load_f16_dst, const SkRasterPipeline_MemoryCtx* ctx) {
1733     auto ptr = ptr_at_xy<const uint64_t>(ctx, dx,dy);
1734 
1735     U16 R,G,B,A;
1736     load4((const uint16_t*)ptr,tail, &R,&G,&B,&A);
1737     dr = from_half(R);
1738     dg = from_half(G);
1739     db = from_half(B);
1740     da = from_half(A);
1741 }
STAGE(gather_f16,const SkRasterPipeline_GatherCtx * ctx)1742 STAGE(gather_f16, const SkRasterPipeline_GatherCtx* ctx) {
1743     const uint64_t* ptr;
1744     U32 ix = ix_and_ptr(&ptr, ctx, r,g);
1745     auto px = gather(ptr, ix);
1746 
1747     U16 R,G,B,A;
1748     load4((const uint16_t*)&px,0, &R,&G,&B,&A);
1749     r = from_half(R);
1750     g = from_half(G);
1751     b = from_half(B);
1752     a = from_half(A);
1753 }
STAGE(store_f16,const SkRasterPipeline_MemoryCtx * ctx)1754 STAGE(store_f16, const SkRasterPipeline_MemoryCtx* ctx) {
1755     auto ptr = ptr_at_xy<uint64_t>(ctx, dx,dy);
1756     store4((uint16_t*)ptr,tail, to_half(r)
1757                               , to_half(g)
1758                               , to_half(b)
1759                               , to_half(a));
1760 }
1761 
STAGE(store_u16_be,const SkRasterPipeline_MemoryCtx * ctx)1762 STAGE(store_u16_be, const SkRasterPipeline_MemoryCtx* ctx) {
1763     auto ptr = ptr_at_xy<uint16_t>(ctx, 4*dx,dy);
1764 
1765     U16 R = bswap(pack(to_unorm(r, 65535))),
1766         G = bswap(pack(to_unorm(g, 65535))),
1767         B = bswap(pack(to_unorm(b, 65535))),
1768         A = bswap(pack(to_unorm(a, 65535)));
1769 
1770     store4(ptr,tail, R,G,B,A);
1771 }
1772 
STAGE(load_f32,const SkRasterPipeline_MemoryCtx * ctx)1773 STAGE(load_f32, const SkRasterPipeline_MemoryCtx* ctx) {
1774     auto ptr = ptr_at_xy<const float>(ctx, 4*dx,4*dy);
1775     load4(ptr,tail, &r,&g,&b,&a);
1776 }
STAGE(load_f32_dst,const SkRasterPipeline_MemoryCtx * ctx)1777 STAGE(load_f32_dst, const SkRasterPipeline_MemoryCtx* ctx) {
1778     auto ptr = ptr_at_xy<const float>(ctx, 4*dx,4*dy);
1779     load4(ptr,tail, &dr,&dg,&db,&da);
1780 }
STAGE(gather_f32,const SkRasterPipeline_GatherCtx * ctx)1781 STAGE(gather_f32, const SkRasterPipeline_GatherCtx* ctx) {
1782     const float* ptr;
1783     U32 ix = ix_and_ptr(&ptr, ctx, r,g);
1784     r = gather(ptr, 4*ix + 0);
1785     g = gather(ptr, 4*ix + 1);
1786     b = gather(ptr, 4*ix + 2);
1787     a = gather(ptr, 4*ix + 3);
1788 }
STAGE(store_f32,const SkRasterPipeline_MemoryCtx * ctx)1789 STAGE(store_f32, const SkRasterPipeline_MemoryCtx* ctx) {
1790     auto ptr = ptr_at_xy<float>(ctx, 4*dx,4*dy);
1791     store4(ptr,tail, r,g,b,a);
1792 }
1793 
exclusive_repeat(F v,const SkRasterPipeline_TileCtx * ctx)1794 SI F exclusive_repeat(F v, const SkRasterPipeline_TileCtx* ctx) {
1795     return v - floor_(v*ctx->invScale)*ctx->scale;
1796 }
exclusive_mirror(F v,const SkRasterPipeline_TileCtx * ctx)1797 SI F exclusive_mirror(F v, const SkRasterPipeline_TileCtx* ctx) {
1798     auto limit = ctx->scale;
1799     auto invLimit = ctx->invScale;
1800     return abs_( (v-limit) - (limit+limit)*floor_((v-limit)*(invLimit*0.5f)) - limit );
1801 }
1802 // Tile x or y to [0,limit) == [0,limit - 1 ulp] (think, sampling from images).
1803 // The gather stages will hard clamp the output of these stages to [0,limit)...
1804 // we just need to do the basic repeat or mirroring.
STAGE(repeat_x,const SkRasterPipeline_TileCtx * ctx)1805 STAGE(repeat_x, const SkRasterPipeline_TileCtx* ctx) { r = exclusive_repeat(r, ctx); }
STAGE(repeat_y,const SkRasterPipeline_TileCtx * ctx)1806 STAGE(repeat_y, const SkRasterPipeline_TileCtx* ctx) { g = exclusive_repeat(g, ctx); }
STAGE(mirror_x,const SkRasterPipeline_TileCtx * ctx)1807 STAGE(mirror_x, const SkRasterPipeline_TileCtx* ctx) { r = exclusive_mirror(r, ctx); }
STAGE(mirror_y,const SkRasterPipeline_TileCtx * ctx)1808 STAGE(mirror_y, const SkRasterPipeline_TileCtx* ctx) { g = exclusive_mirror(g, ctx); }
1809 
1810 // Clamp x to [0,1], both sides inclusive (think, gradients).
1811 // Even repeat and mirror funnel through a clamp to handle bad inputs like +Inf, NaN.
clamp_01(F v)1812 SI F clamp_01(F v) { return min(max(0, v), 1); }
1813 
STAGE(clamp_x_1,Ctx::None)1814 STAGE( clamp_x_1, Ctx::None) { r = clamp_01(r); }
STAGE(repeat_x_1,Ctx::None)1815 STAGE(repeat_x_1, Ctx::None) { r = clamp_01(r - floor_(r)); }
STAGE(mirror_x_1,Ctx::None)1816 STAGE(mirror_x_1, Ctx::None) { r = clamp_01(abs_( (r-1.0f) - two(floor_((r-1.0f)*0.5f)) - 1.0f )); }
1817 
1818 // Decal stores a 32bit mask after checking the coordinate (x and/or y) against its domain:
1819 //      mask == 0x00000000 if the coordinate(s) are out of bounds
1820 //      mask == 0xFFFFFFFF if the coordinate(s) are in bounds
1821 // After the gather stage, the r,g,b,a values are AND'd with this mask, setting them to 0
1822 // if either of the coordinates were out of bounds.
1823 
STAGE(decal_x,SkRasterPipeline_DecalTileCtx * ctx)1824 STAGE(decal_x, SkRasterPipeline_DecalTileCtx* ctx) {
1825     auto w = ctx->limit_x;
1826     unaligned_store(ctx->mask, cond_to_mask((0 <= r) & (r < w)));
1827 }
STAGE(decal_y,SkRasterPipeline_DecalTileCtx * ctx)1828 STAGE(decal_y, SkRasterPipeline_DecalTileCtx* ctx) {
1829     auto h = ctx->limit_y;
1830     unaligned_store(ctx->mask, cond_to_mask((0 <= g) & (g < h)));
1831 }
STAGE(decal_x_and_y,SkRasterPipeline_DecalTileCtx * ctx)1832 STAGE(decal_x_and_y, SkRasterPipeline_DecalTileCtx* ctx) {
1833     auto w = ctx->limit_x;
1834     auto h = ctx->limit_y;
1835     unaligned_store(ctx->mask,
1836                     cond_to_mask((0 <= r) & (r < w) & (0 <= g) & (g < h)));
1837 }
STAGE(check_decal_mask,SkRasterPipeline_DecalTileCtx * ctx)1838 STAGE(check_decal_mask, SkRasterPipeline_DecalTileCtx* ctx) {
1839     auto mask = unaligned_load<U32>(ctx->mask);
1840     r = bit_cast<F>( bit_cast<U32>(r) & mask );
1841     g = bit_cast<F>( bit_cast<U32>(g) & mask );
1842     b = bit_cast<F>( bit_cast<U32>(b) & mask );
1843     a = bit_cast<F>( bit_cast<U32>(a) & mask );
1844 }
1845 
STAGE(alpha_to_gray,Ctx::None)1846 STAGE(alpha_to_gray, Ctx::None) {
1847     r = g = b = a;
1848     a = 1;
1849 }
STAGE(alpha_to_gray_dst,Ctx::None)1850 STAGE(alpha_to_gray_dst, Ctx::None) {
1851     dr = dg = db = da;
1852     da = 1;
1853 }
STAGE(luminance_to_alpha,Ctx::None)1854 STAGE(luminance_to_alpha, Ctx::None) {
1855     a = r*0.2126f + g*0.7152f + b*0.0722f;
1856     r = g = b = 0;
1857 }
1858 
STAGE(matrix_translate,const float * m)1859 STAGE(matrix_translate, const float* m) {
1860     r += m[0];
1861     g += m[1];
1862 }
STAGE(matrix_scale_translate,const float * m)1863 STAGE(matrix_scale_translate, const float* m) {
1864     r = mad(r,m[0], m[2]);
1865     g = mad(g,m[1], m[3]);
1866 }
STAGE(matrix_2x3,const float * m)1867 STAGE(matrix_2x3, const float* m) {
1868     auto R = mad(r,m[0], mad(g,m[2], m[4])),
1869          G = mad(r,m[1], mad(g,m[3], m[5]));
1870     r = R;
1871     g = G;
1872 }
STAGE(matrix_3x3,const float * m)1873 STAGE(matrix_3x3, const float* m) {
1874     auto R = mad(r,m[0], mad(g,m[3], b*m[6])),
1875          G = mad(r,m[1], mad(g,m[4], b*m[7])),
1876          B = mad(r,m[2], mad(g,m[5], b*m[8]));
1877     r = R;
1878     g = G;
1879     b = B;
1880 }
STAGE(matrix_3x4,const float * m)1881 STAGE(matrix_3x4, const float* m) {
1882     auto R = mad(r,m[0], mad(g,m[3], mad(b,m[6], m[ 9]))),
1883          G = mad(r,m[1], mad(g,m[4], mad(b,m[7], m[10]))),
1884          B = mad(r,m[2], mad(g,m[5], mad(b,m[8], m[11])));
1885     r = R;
1886     g = G;
1887     b = B;
1888 }
STAGE(matrix_4x5,const float * m)1889 STAGE(matrix_4x5, const float* m) {
1890     auto R = mad(r,m[0], mad(g,m[4], mad(b,m[ 8], mad(a,m[12], m[16])))),
1891          G = mad(r,m[1], mad(g,m[5], mad(b,m[ 9], mad(a,m[13], m[17])))),
1892          B = mad(r,m[2], mad(g,m[6], mad(b,m[10], mad(a,m[14], m[18])))),
1893          A = mad(r,m[3], mad(g,m[7], mad(b,m[11], mad(a,m[15], m[19]))));
1894     r = R;
1895     g = G;
1896     b = B;
1897     a = A;
1898 }
STAGE(matrix_4x3,const float * m)1899 STAGE(matrix_4x3, const float* m) {
1900     auto X = r,
1901          Y = g;
1902 
1903     r = mad(X, m[0], mad(Y, m[4], m[ 8]));
1904     g = mad(X, m[1], mad(Y, m[5], m[ 9]));
1905     b = mad(X, m[2], mad(Y, m[6], m[10]));
1906     a = mad(X, m[3], mad(Y, m[7], m[11]));
1907 }
STAGE(matrix_perspective,const float * m)1908 STAGE(matrix_perspective, const float* m) {
1909     // N.B. Unlike the other matrix_ stages, this matrix is row-major.
1910     auto R = mad(r,m[0], mad(g,m[1], m[2])),
1911          G = mad(r,m[3], mad(g,m[4], m[5])),
1912          Z = mad(r,m[6], mad(g,m[7], m[8]));
1913     r = R * rcp(Z);
1914     g = G * rcp(Z);
1915 }
1916 
gradient_lookup(const SkRasterPipeline_GradientCtx * c,U32 idx,F t,F * r,F * g,F * b,F * a)1917 SI void gradient_lookup(const SkRasterPipeline_GradientCtx* c, U32 idx, F t,
1918                         F* r, F* g, F* b, F* a) {
1919     F fr, br, fg, bg, fb, bb, fa, ba;
1920 #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
1921     if (c->stopCount <=8) {
1922         fr = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[0]), idx);
1923         br = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[0]), idx);
1924         fg = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[1]), idx);
1925         bg = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[1]), idx);
1926         fb = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[2]), idx);
1927         bb = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[2]), idx);
1928         fa = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[3]), idx);
1929         ba = _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[3]), idx);
1930     } else
1931 #endif
1932     {
1933         fr = gather(c->fs[0], idx);
1934         br = gather(c->bs[0], idx);
1935         fg = gather(c->fs[1], idx);
1936         bg = gather(c->bs[1], idx);
1937         fb = gather(c->fs[2], idx);
1938         bb = gather(c->bs[2], idx);
1939         fa = gather(c->fs[3], idx);
1940         ba = gather(c->bs[3], idx);
1941     }
1942 
1943     *r = mad(t, fr, br);
1944     *g = mad(t, fg, bg);
1945     *b = mad(t, fb, bb);
1946     *a = mad(t, fa, ba);
1947 }
1948 
STAGE(evenly_spaced_gradient,const SkRasterPipeline_GradientCtx * c)1949 STAGE(evenly_spaced_gradient, const SkRasterPipeline_GradientCtx* c) {
1950     auto t = r;
1951     auto idx = trunc_(t * (c->stopCount-1));
1952     gradient_lookup(c, idx, t, &r, &g, &b, &a);
1953 }
1954 
STAGE(gradient,const SkRasterPipeline_GradientCtx * c)1955 STAGE(gradient, const SkRasterPipeline_GradientCtx* c) {
1956     auto t = r;
1957     U32 idx = 0;
1958 
1959     // N.B. The loop starts at 1 because idx 0 is the color to use before the first stop.
1960     for (size_t i = 1; i < c->stopCount; i++) {
1961         idx += if_then_else(t >= c->ts[i], U32(1), U32(0));
1962     }
1963 
1964     gradient_lookup(c, idx, t, &r, &g, &b, &a);
1965 }
1966 
STAGE(evenly_spaced_2_stop_gradient,const void * ctx)1967 STAGE(evenly_spaced_2_stop_gradient, const void* ctx) {
1968     // TODO: Rename Ctx SkRasterPipeline_EvenlySpaced2StopGradientCtx.
1969     struct Ctx { float f[4], b[4]; };
1970     auto c = (const Ctx*)ctx;
1971 
1972     auto t = r;
1973     r = mad(t, c->f[0], c->b[0]);
1974     g = mad(t, c->f[1], c->b[1]);
1975     b = mad(t, c->f[2], c->b[2]);
1976     a = mad(t, c->f[3], c->b[3]);
1977 }
1978 
STAGE(xy_to_unit_angle,Ctx::None)1979 STAGE(xy_to_unit_angle, Ctx::None) {
1980     F X = r,
1981       Y = g;
1982     F xabs = abs_(X),
1983       yabs = abs_(Y);
1984 
1985     F slope = min(xabs, yabs)/max(xabs, yabs);
1986     F s = slope * slope;
1987 
1988     // Use a 7th degree polynomial to approximate atan.
1989     // This was generated using sollya.gforge.inria.fr.
1990     // A float optimized polynomial was generated using the following command.
1991     // P1 = fpminimax((1/(2*Pi))*atan(x),[|1,3,5,7|],[|24...|],[2^(-40),1],relative);
1992     F phi = slope
1993              * (0.15912117063999176025390625f     + s
1994              * (-5.185396969318389892578125e-2f   + s
1995              * (2.476101927459239959716796875e-2f + s
1996              * (-7.0547382347285747528076171875e-3f))));
1997 
1998     phi = if_then_else(xabs < yabs, 1.0f/4.0f - phi, phi);
1999     phi = if_then_else(X < 0.0f   , 1.0f/2.0f - phi, phi);
2000     phi = if_then_else(Y < 0.0f   , 1.0f - phi     , phi);
2001     phi = if_then_else(phi != phi , 0              , phi);  // Check for NaN.
2002     r = phi;
2003 }
2004 
STAGE(xy_to_radius,Ctx::None)2005 STAGE(xy_to_radius, Ctx::None) {
2006     F X2 = r * r,
2007       Y2 = g * g;
2008     r = sqrt_(X2 + Y2);
2009 }
2010 
2011 // Please see https://skia.org/dev/design/conical for how our 2pt conical shader works.
2012 
STAGE(negate_x,Ctx::None)2013 STAGE(negate_x, Ctx::None) { r = -r; }
2014 
STAGE(xy_to_2pt_conical_strip,const SkRasterPipeline_2PtConicalCtx * ctx)2015 STAGE(xy_to_2pt_conical_strip, const SkRasterPipeline_2PtConicalCtx* ctx) {
2016     F x = r, y = g, &t = r;
2017     t = x + sqrt_(ctx->fP0 - y*y); // ctx->fP0 = r0 * r0
2018 }
2019 
STAGE(xy_to_2pt_conical_focal_on_circle,Ctx::None)2020 STAGE(xy_to_2pt_conical_focal_on_circle, Ctx::None) {
2021     F x = r, y = g, &t = r;
2022     t = x + y*y / x; // (x^2 + y^2) / x
2023 }
2024 
STAGE(xy_to_2pt_conical_well_behaved,const SkRasterPipeline_2PtConicalCtx * ctx)2025 STAGE(xy_to_2pt_conical_well_behaved, const SkRasterPipeline_2PtConicalCtx* ctx) {
2026     F x = r, y = g, &t = r;
2027     t = sqrt_(x*x + y*y) - x * ctx->fP0; // ctx->fP0 = 1/r1
2028 }
2029 
STAGE(xy_to_2pt_conical_greater,const SkRasterPipeline_2PtConicalCtx * ctx)2030 STAGE(xy_to_2pt_conical_greater, const SkRasterPipeline_2PtConicalCtx* ctx) {
2031     F x = r, y = g, &t = r;
2032     t = sqrt_(x*x - y*y) - x * ctx->fP0; // ctx->fP0 = 1/r1
2033 }
2034 
STAGE(xy_to_2pt_conical_smaller,const SkRasterPipeline_2PtConicalCtx * ctx)2035 STAGE(xy_to_2pt_conical_smaller, const SkRasterPipeline_2PtConicalCtx* ctx) {
2036     F x = r, y = g, &t = r;
2037     t = -sqrt_(x*x - y*y) - x * ctx->fP0; // ctx->fP0 = 1/r1
2038 }
2039 
STAGE(alter_2pt_conical_compensate_focal,const SkRasterPipeline_2PtConicalCtx * ctx)2040 STAGE(alter_2pt_conical_compensate_focal, const SkRasterPipeline_2PtConicalCtx* ctx) {
2041     F& t = r;
2042     t = t + ctx->fP1; // ctx->fP1 = f
2043 }
2044 
STAGE(alter_2pt_conical_unswap,Ctx::None)2045 STAGE(alter_2pt_conical_unswap, Ctx::None) {
2046     F& t = r;
2047     t = 1 - t;
2048 }
2049 
STAGE(mask_2pt_conical_nan,SkRasterPipeline_2PtConicalCtx * c)2050 STAGE(mask_2pt_conical_nan, SkRasterPipeline_2PtConicalCtx* c) {
2051     F& t = r;
2052     auto is_degenerate = (t != t); // NaN
2053     t = if_then_else(is_degenerate, F(0), t);
2054     unaligned_store(&c->fMask, cond_to_mask(!is_degenerate));
2055 }
2056 
STAGE(mask_2pt_conical_degenerates,SkRasterPipeline_2PtConicalCtx * c)2057 STAGE(mask_2pt_conical_degenerates, SkRasterPipeline_2PtConicalCtx* c) {
2058     F& t = r;
2059     auto is_degenerate = (t <= 0) | (t != t);
2060     t = if_then_else(is_degenerate, F(0), t);
2061     unaligned_store(&c->fMask, cond_to_mask(!is_degenerate));
2062 }
2063 
STAGE(apply_vector_mask,const uint32_t * ctx)2064 STAGE(apply_vector_mask, const uint32_t* ctx) {
2065     const U32 mask = unaligned_load<U32>(ctx);
2066     r = bit_cast<F>(bit_cast<U32>(r) & mask);
2067     g = bit_cast<F>(bit_cast<U32>(g) & mask);
2068     b = bit_cast<F>(bit_cast<U32>(b) & mask);
2069     a = bit_cast<F>(bit_cast<U32>(a) & mask);
2070 }
2071 
STAGE(save_xy,SkRasterPipeline_SamplerCtx * c)2072 STAGE(save_xy, SkRasterPipeline_SamplerCtx* c) {
2073     // Whether bilinear or bicubic, all sample points are at the same fractional offset (fx,fy).
2074     // They're either the 4 corners of a logical 1x1 pixel or the 16 corners of a 3x3 grid
2075     // surrounding (x,y) at (0.5,0.5) off-center.
2076     F fx = fract(r + 0.5f),
2077       fy = fract(g + 0.5f);
2078 
2079     // Samplers will need to load x and fx, or y and fy.
2080     unaligned_store(c->x,  r);
2081     unaligned_store(c->y,  g);
2082     unaligned_store(c->fx, fx);
2083     unaligned_store(c->fy, fy);
2084 }
2085 
STAGE(accumulate,const SkRasterPipeline_SamplerCtx * c)2086 STAGE(accumulate, const SkRasterPipeline_SamplerCtx* c) {
2087     // Bilinear and bicubic filters are both separable, so we produce independent contributions
2088     // from x and y, multiplying them together here to get each pixel's total scale factor.
2089     auto scale = unaligned_load<F>(c->scalex)
2090                * unaligned_load<F>(c->scaley);
2091     dr = mad(scale, r, dr);
2092     dg = mad(scale, g, dg);
2093     db = mad(scale, b, db);
2094     da = mad(scale, a, da);
2095 }
2096 
2097 // In bilinear interpolation, the 4 pixels at +/- 0.5 offsets from the sample pixel center
2098 // are combined in direct proportion to their area overlapping that logical query pixel.
2099 // At positive offsets, the x-axis contribution to that rectangle is fx, or (1-fx) at negative x.
2100 // The y-axis is symmetric.
2101 
2102 template <int kScale>
bilinear_x(SkRasterPipeline_SamplerCtx * ctx,F * x)2103 SI void bilinear_x(SkRasterPipeline_SamplerCtx* ctx, F* x) {
2104     *x = unaligned_load<F>(ctx->x) + (kScale * 0.5f);
2105     F fx = unaligned_load<F>(ctx->fx);
2106 
2107     F scalex;
2108     if (kScale == -1) { scalex = 1.0f - fx; }
2109     if (kScale == +1) { scalex =        fx; }
2110     unaligned_store(ctx->scalex, scalex);
2111 }
2112 template <int kScale>
bilinear_y(SkRasterPipeline_SamplerCtx * ctx,F * y)2113 SI void bilinear_y(SkRasterPipeline_SamplerCtx* ctx, F* y) {
2114     *y = unaligned_load<F>(ctx->y) + (kScale * 0.5f);
2115     F fy = unaligned_load<F>(ctx->fy);
2116 
2117     F scaley;
2118     if (kScale == -1) { scaley = 1.0f - fy; }
2119     if (kScale == +1) { scaley =        fy; }
2120     unaligned_store(ctx->scaley, scaley);
2121 }
2122 
STAGE(bilinear_nx,SkRasterPipeline_SamplerCtx * ctx)2123 STAGE(bilinear_nx, SkRasterPipeline_SamplerCtx* ctx) { bilinear_x<-1>(ctx, &r); }
STAGE(bilinear_px,SkRasterPipeline_SamplerCtx * ctx)2124 STAGE(bilinear_px, SkRasterPipeline_SamplerCtx* ctx) { bilinear_x<+1>(ctx, &r); }
STAGE(bilinear_ny,SkRasterPipeline_SamplerCtx * ctx)2125 STAGE(bilinear_ny, SkRasterPipeline_SamplerCtx* ctx) { bilinear_y<-1>(ctx, &g); }
STAGE(bilinear_py,SkRasterPipeline_SamplerCtx * ctx)2126 STAGE(bilinear_py, SkRasterPipeline_SamplerCtx* ctx) { bilinear_y<+1>(ctx, &g); }
2127 
2128 
2129 // In bicubic interpolation, the 16 pixels and +/- 0.5 and +/- 1.5 offsets from the sample
2130 // pixel center are combined with a non-uniform cubic filter, with higher values near the center.
2131 //
2132 // We break this function into two parts, one for near 0.5 offsets and one for far 1.5 offsets.
2133 // See GrCubicEffect for details of this particular filter.
2134 
bicubic_near(F t)2135 SI F bicubic_near(F t) {
2136     // 1/18 + 9/18t + 27/18t^2 - 21/18t^3 == t ( t ( -21/18t + 27/18) + 9/18) + 1/18
2137     return mad(t, mad(t, mad((-21/18.0f), t, (27/18.0f)), (9/18.0f)), (1/18.0f));
2138 }
bicubic_far(F t)2139 SI F bicubic_far(F t) {
2140     // 0/18 + 0/18*t - 6/18t^2 + 7/18t^3 == t^2 (7/18t - 6/18)
2141     return (t*t)*mad((7/18.0f), t, (-6/18.0f));
2142 }
2143 
2144 template <int kScale>
bicubic_x(SkRasterPipeline_SamplerCtx * ctx,F * x)2145 SI void bicubic_x(SkRasterPipeline_SamplerCtx* ctx, F* x) {
2146     *x = unaligned_load<F>(ctx->x) + (kScale * 0.5f);
2147     F fx = unaligned_load<F>(ctx->fx);
2148 
2149     F scalex;
2150     if (kScale == -3) { scalex = bicubic_far (1.0f - fx); }
2151     if (kScale == -1) { scalex = bicubic_near(1.0f - fx); }
2152     if (kScale == +1) { scalex = bicubic_near(       fx); }
2153     if (kScale == +3) { scalex = bicubic_far (       fx); }
2154     unaligned_store(ctx->scalex, scalex);
2155 }
2156 template <int kScale>
bicubic_y(SkRasterPipeline_SamplerCtx * ctx,F * y)2157 SI void bicubic_y(SkRasterPipeline_SamplerCtx* ctx, F* y) {
2158     *y = unaligned_load<F>(ctx->y) + (kScale * 0.5f);
2159     F fy = unaligned_load<F>(ctx->fy);
2160 
2161     F scaley;
2162     if (kScale == -3) { scaley = bicubic_far (1.0f - fy); }
2163     if (kScale == -1) { scaley = bicubic_near(1.0f - fy); }
2164     if (kScale == +1) { scaley = bicubic_near(       fy); }
2165     if (kScale == +3) { scaley = bicubic_far (       fy); }
2166     unaligned_store(ctx->scaley, scaley);
2167 }
2168 
STAGE(bicubic_n3x,SkRasterPipeline_SamplerCtx * ctx)2169 STAGE(bicubic_n3x, SkRasterPipeline_SamplerCtx* ctx) { bicubic_x<-3>(ctx, &r); }
STAGE(bicubic_n1x,SkRasterPipeline_SamplerCtx * ctx)2170 STAGE(bicubic_n1x, SkRasterPipeline_SamplerCtx* ctx) { bicubic_x<-1>(ctx, &r); }
STAGE(bicubic_p1x,SkRasterPipeline_SamplerCtx * ctx)2171 STAGE(bicubic_p1x, SkRasterPipeline_SamplerCtx* ctx) { bicubic_x<+1>(ctx, &r); }
STAGE(bicubic_p3x,SkRasterPipeline_SamplerCtx * ctx)2172 STAGE(bicubic_p3x, SkRasterPipeline_SamplerCtx* ctx) { bicubic_x<+3>(ctx, &r); }
2173 
STAGE(bicubic_n3y,SkRasterPipeline_SamplerCtx * ctx)2174 STAGE(bicubic_n3y, SkRasterPipeline_SamplerCtx* ctx) { bicubic_y<-3>(ctx, &g); }
STAGE(bicubic_n1y,SkRasterPipeline_SamplerCtx * ctx)2175 STAGE(bicubic_n1y, SkRasterPipeline_SamplerCtx* ctx) { bicubic_y<-1>(ctx, &g); }
STAGE(bicubic_p1y,SkRasterPipeline_SamplerCtx * ctx)2176 STAGE(bicubic_p1y, SkRasterPipeline_SamplerCtx* ctx) { bicubic_y<+1>(ctx, &g); }
STAGE(bicubic_p3y,SkRasterPipeline_SamplerCtx * ctx)2177 STAGE(bicubic_p3y, SkRasterPipeline_SamplerCtx* ctx) { bicubic_y<+3>(ctx, &g); }
2178 
STAGE(callback,SkRasterPipeline_CallbackCtx * c)2179 STAGE(callback, SkRasterPipeline_CallbackCtx* c) {
2180     store4(c->rgba,0, r,g,b,a);
2181     c->fn(c, tail ? tail : N);
2182     load4(c->read_from,0, &r,&g,&b,&a);
2183 }
2184 
STAGE(gauss_a_to_rgba,Ctx::None)2185 STAGE(gauss_a_to_rgba, Ctx::None) {
2186     // x = 1 - x;
2187     // exp(-x * x * 4) - 0.018f;
2188     // ... now approximate with quartic
2189     //
2190     const float c4 = -2.26661229133605957031f;
2191     const float c3 = 2.89795351028442382812f;
2192     const float c2 = 0.21345567703247070312f;
2193     const float c1 = 0.15489584207534790039f;
2194     const float c0 = 0.00030726194381713867f;
2195     a = mad(a, mad(a, mad(a, mad(a, c4, c3), c2), c1), c0);
2196     r = a;
2197     g = a;
2198     b = a;
2199 }
2200 
2201 // A specialized fused image shader for clamp-x, clamp-y, non-sRGB sampling.
STAGE(bilerp_clamp_8888,const SkRasterPipeline_GatherCtx * ctx)2202 STAGE(bilerp_clamp_8888, const SkRasterPipeline_GatherCtx* ctx) {
2203     // (cx,cy) are the center of our sample.
2204     F cx = r,
2205       cy = g;
2206 
2207     // All sample points are at the same fractional offset (fx,fy).
2208     // They're the 4 corners of a logical 1x1 pixel surrounding (x,y) at (0.5,0.5) offsets.
2209     F fx = fract(cx + 0.5f),
2210       fy = fract(cy + 0.5f);
2211 
2212     // We'll accumulate the color of all four samples into {r,g,b,a} directly.
2213     r = g = b = a = 0;
2214 
2215     for (float dy = -0.5f; dy <= +0.5f; dy += 1.0f)
2216     for (float dx = -0.5f; dx <= +0.5f; dx += 1.0f) {
2217         // (x,y) are the coordinates of this sample point.
2218         F x = cx + dx,
2219           y = cy + dy;
2220 
2221         // ix_and_ptr() will clamp to the image's bounds for us.
2222         const uint32_t* ptr;
2223         U32 ix = ix_and_ptr(&ptr, ctx, x,y);
2224 
2225         F sr,sg,sb,sa;
2226         from_8888(gather(ptr, ix), &sr,&sg,&sb,&sa);
2227 
2228         // In bilinear interpolation, the 4 pixels at +/- 0.5 offsets from the sample pixel center
2229         // are combined in direct proportion to their area overlapping that logical query pixel.
2230         // At positive offsets, the x-axis contribution to that rectangle is fx,
2231         // or (1-fx) at negative x.  Same deal for y.
2232         F sx = (dx > 0) ? fx : 1.0f - fx,
2233           sy = (dy > 0) ? fy : 1.0f - fy,
2234           area = sx * sy;
2235 
2236         r += sr * area;
2237         g += sg * area;
2238         b += sb * area;
2239         a += sa * area;
2240     }
2241 }
2242 
2243 namespace lowp {
2244 #if defined(JUMPER_IS_SCALAR) || defined(SK_DISABLE_LOWP_RASTER_PIPELINE)
2245     // If we're not compiled by Clang, or otherwise switched into scalar mode (old Clang, manually),
2246     // we don't generate lowp stages.  All these nullptrs will tell SkJumper.cpp to always use the
2247     // highp float pipeline.
2248     #define M(st) static void (*st)(void) = nullptr;
2249         SK_RASTER_PIPELINE_STAGES(M)
2250     #undef M
2251     static void (*just_return)(void) = nullptr;
2252 
start_pipeline(size_t,size_t,size_t,size_t,void **)2253     static void start_pipeline(size_t,size_t,size_t,size_t, void**) {}
2254 
2255 #else  // We are compiling vector code with Clang... let's make some lowp stages!
2256 
2257 #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2258     using U8  = uint8_t  __attribute__((ext_vector_type(16)));
2259     using U16 = uint16_t __attribute__((ext_vector_type(16)));
2260     using I16 =  int16_t __attribute__((ext_vector_type(16)));
2261     using I32 =  int32_t __attribute__((ext_vector_type(16)));
2262     using U32 = uint32_t __attribute__((ext_vector_type(16)));
2263     using F   = float    __attribute__((ext_vector_type(16)));
2264 #else
2265     using U8  = uint8_t  __attribute__((ext_vector_type(8)));
2266     using U16 = uint16_t __attribute__((ext_vector_type(8)));
2267     using I16 =  int16_t __attribute__((ext_vector_type(8)));
2268     using I32 =  int32_t __attribute__((ext_vector_type(8)));
2269     using U32 = uint32_t __attribute__((ext_vector_type(8)));
2270     using F   = float    __attribute__((ext_vector_type(8)));
2271 #endif
2272 
2273 static const size_t N = sizeof(U16) / sizeof(uint16_t);
2274 
2275 // Once again, some platforms benefit from a restricted Stage calling convention,
2276 // but others can pass tons and tons of registers and we're happy to exploit that.
2277 // It's exactly the same decision and implementation strategy as the F stages above.
2278 #if JUMPER_NARROW_STAGES
2279     struct Params {
2280         size_t dx, dy, tail;
2281         U16 dr,dg,db,da;
2282     };
2283     using Stage = void(ABI*)(Params*, void** program, U16 r, U16 g, U16 b, U16 a);
2284 #else
2285     // We pass program as the second argument so that load_and_inc() will find it in %rsi on x86-64.
2286     using Stage = void (ABI*)(size_t tail, void** program, size_t dx, size_t dy,
2287                               U16  r, U16  g, U16  b, U16  a,
2288                               U16 dr, U16 dg, U16 db, U16 da);
2289 #endif
2290 
2291 static void start_pipeline(const size_t x0,     const size_t y0,
2292                            const size_t xlimit, const size_t ylimit, void** program) {
2293     auto start = (Stage)load_and_inc(program);
2294     for (size_t dy = y0; dy < ylimit; dy++) {
2295     #if JUMPER_NARROW_STAGES
2296         Params params = { x0,dy,0, 0,0,0,0 };
2297         for (; params.dx + N <= xlimit; params.dx += N) {
2298             start(&params,program, 0,0,0,0);
2299         }
2300         if (size_t tail = xlimit - params.dx) {
2301             params.tail = tail;
2302             start(&params,program, 0,0,0,0);
2303         }
2304     #else
2305         size_t dx = x0;
2306         for (; dx + N <= xlimit; dx += N) {
2307             start(   0,program,dx,dy, 0,0,0,0, 0,0,0,0);
2308         }
2309         if (size_t tail = xlimit - dx) {
2310             start(tail,program,dx,dy, 0,0,0,0, 0,0,0,0);
2311         }
2312     #endif
2313     }
2314 }
2315 
2316 #if JUMPER_NARROW_STAGES
2317     static void ABI just_return(Params*, void**, U16,U16,U16,U16) {}
2318 #else
2319     static void ABI just_return(size_t,void**,size_t,size_t, U16,U16,U16,U16, U16,U16,U16,U16) {}
2320 #endif
2321 
2322 // All stages use the same function call ABI to chain into each other, but there are three types:
2323 //   GG: geometry in, geometry out  -- think, a matrix
2324 //   GP: geometry in, pixels out.   -- think, a memory gather
2325 //   PP: pixels in, pixels out.     -- think, a blend mode
2326 //
2327 // (Some stages ignore their inputs or produce no logical output.  That's perfectly fine.)
2328 //
2329 // These three STAGE_ macros let you define each type of stage,
2330 // and will have (x,y) geometry and/or (r,g,b,a, dr,dg,db,da) pixel arguments as appropriate.
2331 
2332 #if JUMPER_NARROW_STAGES
2333     #define STAGE_GG(name, ...)                                                                \
2334         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F& x, F& y,           \
2335                          U16    , U16    , U16    , U16    ,                                   \
2336                          U16    , U16    , U16    , U16    );                                  \
2337         static void ABI name(Params* params, void** program, U16 r, U16 g, U16 b, U16 a) {     \
2338             auto x = join<F>(r,g),                                                             \
2339                  y = join<F>(b,a);                                                             \
2340             name##_k(Ctx{program}, params->dx,params->dy,params->tail, x,y, 0,0,0,0, 0,0,0,0); \
2341             split(x, &r,&g);                                                                   \
2342             split(y, &b,&a);                                                                   \
2343             auto next = (Stage)load_and_inc(program);                                          \
2344             next(params,program, r,g,b,a);                                                     \
2345         }                                                                                      \
2346         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F& x, F& y,           \
2347                          U16    , U16    , U16    , U16    ,                                   \
2348                          U16    , U16    , U16    , U16    )
2349 
2350     #define STAGE_GP(name, ...)                                                            \
2351         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F x, F y,         \
2352                          U16&  r, U16&  g, U16&  b, U16&  a,                               \
2353                          U16& dr, U16& dg, U16& db, U16& da);                              \
2354         static void ABI name(Params* params, void** program, U16 r, U16 g, U16 b, U16 a) { \
2355             auto x = join<F>(r,g),                                                         \
2356                  y = join<F>(b,a);                                                         \
2357             name##_k(Ctx{program}, params->dx,params->dy,params->tail, x,y, r,g,b,a,       \
2358                      params->dr,params->dg,params->db,params->da);                         \
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&  r, U16&  g, U16&  b, U16&  a,                               \
2364                          U16& dr, U16& dg, U16& db, U16& da)
2365 
2366     #define STAGE_PP(name, ...)                                                            \
2367         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F  , F  ,         \
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             name##_k(Ctx{program}, params->dx,params->dy,params->tail, 0,0, r,g,b,a,       \
2372                      params->dr,params->dg,params->db,params->da);                         \
2373             auto next = (Stage)load_and_inc(program);                                      \
2374             next(params,program, r,g,b,a);                                                 \
2375         }                                                                                  \
2376         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F  , F  ,         \
2377                          U16&  r, U16&  g, U16&  b, U16&  a,                               \
2378                          U16& dr, U16& dg, U16& db, U16& da)
2379 #else
2380     #define STAGE_GG(name, ...)                                                            \
2381         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F& x, F& y,       \
2382                          U16    , U16    , U16    , U16    ,                               \
2383                          U16    , U16    , U16    , U16    );                              \
2384         static void ABI name(size_t tail, void** program, size_t dx, size_t dy,            \
2385                              U16  r, U16  g, U16  b, U16  a,                               \
2386                              U16 dr, U16 dg, U16 db, U16 da) {                             \
2387             auto x = join<F>(r,g),                                                         \
2388                  y = join<F>(b,a);                                                         \
2389             name##_k(Ctx{program}, dx,dy,tail, x,y, 0,0,0,0, 0,0,0,0);                     \
2390             split(x, &r,&g);                                                               \
2391             split(y, &b,&a);                                                               \
2392             auto next = (Stage)load_and_inc(program);                                      \
2393             next(tail,program,dx,dy, r,g,b,a, dr,dg,db,da);                                \
2394         }                                                                                  \
2395         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F& x, F& y,       \
2396                          U16    , U16    , U16    , U16    ,                               \
2397                          U16    , U16    , U16    , U16    )
2398 
2399     #define STAGE_GP(name, ...)                                                            \
2400         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F x, F y,         \
2401                          U16&  r, U16&  g, U16&  b, U16&  a,                               \
2402                          U16& dr, U16& dg, U16& db, U16& da);                              \
2403         static void ABI name(size_t tail, void** program, size_t dx, size_t dy,            \
2404                              U16  r, U16  g, U16  b, U16  a,                               \
2405                              U16 dr, U16 dg, U16 db, U16 da) {                             \
2406             auto x = join<F>(r,g),                                                         \
2407                  y = join<F>(b,a);                                                         \
2408             name##_k(Ctx{program}, dx,dy,tail, x,y, r,g,b,a, dr,dg,db,da);                 \
2409             auto next = (Stage)load_and_inc(program);                                      \
2410             next(tail,program,dx,dy, r,g,b,a, dr,dg,db,da);                                \
2411         }                                                                                  \
2412         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F x, F y,         \
2413                          U16&  r, U16&  g, U16&  b, U16&  a,                               \
2414                          U16& dr, U16& dg, U16& db, U16& da)
2415 
2416     #define STAGE_PP(name, ...)                                                            \
2417         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F  , F  ,         \
2418                          U16&  r, U16&  g, U16&  b, U16&  a,                               \
2419                          U16& dr, U16& dg, U16& db, U16& da);                              \
2420         static void ABI name(size_t tail, void** program, size_t dx, size_t dy,            \
2421                              U16  r, U16  g, U16  b, U16  a,                               \
2422                              U16 dr, U16 dg, U16 db, U16 da) {                             \
2423             name##_k(Ctx{program}, dx,dy,tail, 0,0, r,g,b,a, dr,dg,db,da);                 \
2424             auto next = (Stage)load_and_inc(program);                                      \
2425             next(tail,program,dx,dy, r,g,b,a, dr,dg,db,da);                                \
2426         }                                                                                  \
2427         SI void name##_k(__VA_ARGS__, size_t dx, size_t dy, size_t tail, F  , F  ,         \
2428                          U16&  r, U16&  g, U16&  b, U16&  a,                               \
2429                          U16& dr, U16& dg, U16& db, U16& da)
2430 #endif
2431 
2432 // ~~~~~~ Commonly used helper functions ~~~~~~ //
2433 
2434 SI U16 div255(U16 v) {
2435 #if 0
2436     return (v+127)/255;  // The ideal rounding divide by 255.
2437 #elif 1 && defined(JUMPER_IS_NEON)
2438     // With NEON we can compute (v+127)/255 as (v + ((v+128)>>8) + 128)>>8
2439     // just as fast as we can do the approximation below, so might as well be correct!
2440     // First we compute v + ((v+128)>>8), then one more round of (...+128)>>8 to finish up.
2441     return vrshrq_n_u16(vrsraq_n_u16(v, v, 8), 8);
2442 #else
2443     return (v+255)/256;  // A good approximation of (v+127)/255.
2444 #endif
2445 }
2446 
2447 SI U16 inv(U16 v) { return 255-v; }
2448 
2449 SI U16 if_then_else(I16 c, U16 t, U16 e) { return (t & c) | (e & ~c); }
2450 SI U32 if_then_else(I32 c, U32 t, U32 e) { return (t & c) | (e & ~c); }
2451 
2452 SI U16 max(U16 x, U16 y) { return if_then_else(x < y, y, x); }
2453 SI U16 min(U16 x, U16 y) { return if_then_else(x < y, x, y); }
2454 SI U16 max(U16 x, U16 y, U16 z) { return max(x, max(y, z)); }
2455 SI U16 min(U16 x, U16 y, U16 z) { return min(x, min(y, z)); }
2456 
2457 SI U16 from_float(float f) { return f * 255.0f + 0.5f; }
2458 
2459 SI U16 lerp(U16 from, U16 to, U16 t) { return div255( from*inv(t) + to*t ); }
2460 
2461 template <typename D, typename S>
2462 SI D cast(S src) {
2463     return __builtin_convertvector(src, D);
2464 }
2465 
2466 template <typename D, typename S>
2467 SI void split(S v, D* lo, D* hi) {
2468     static_assert(2*sizeof(D) == sizeof(S), "");
2469     memcpy(lo, (const char*)&v + 0*sizeof(D), sizeof(D));
2470     memcpy(hi, (const char*)&v + 1*sizeof(D), sizeof(D));
2471 }
2472 template <typename D, typename S>
2473 SI D join(S lo, S hi) {
2474     static_assert(sizeof(D) == 2*sizeof(S), "");
2475     D v;
2476     memcpy((char*)&v + 0*sizeof(S), &lo, sizeof(S));
2477     memcpy((char*)&v + 1*sizeof(S), &hi, sizeof(S));
2478     return v;
2479 }
2480 
2481 SI F if_then_else(I32 c, F t, F e) {
2482     return bit_cast<F>( (bit_cast<I32>(t) & c) | (bit_cast<I32>(e) & ~c) );
2483 }
2484 SI F max(F x, F y) { return if_then_else(x < y, y, x); }
2485 SI F min(F x, F y) { return if_then_else(x < y, x, y); }
2486 
2487 SI F mad(F f, F m, F a) { return f*m+a; }
2488 SI U32 trunc_(F x) { return (U32)cast<I32>(x); }
2489 
2490 SI F rcp(F x) {
2491 #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2492     __m256 lo,hi;
2493     split(x, &lo,&hi);
2494     return join<F>(_mm256_rcp_ps(lo), _mm256_rcp_ps(hi));
2495 #elif defined(JUMPER_IS_SSE2) || defined(JUMPER_IS_SSE41) || defined(JUMPER_IS_AVX)
2496     __m128 lo,hi;
2497     split(x, &lo,&hi);
2498     return join<F>(_mm_rcp_ps(lo), _mm_rcp_ps(hi));
2499 #elif defined(JUMPER_IS_NEON)
2500     auto rcp = [](float32x4_t v) {
2501         auto est = vrecpeq_f32(v);
2502         return vrecpsq_f32(v,est)*est;
2503     };
2504     float32x4_t lo,hi;
2505     split(x, &lo,&hi);
2506     return join<F>(rcp(lo), rcp(hi));
2507 #else
2508     return 1.0f / x;
2509 #endif
2510 }
2511 SI F sqrt_(F x) {
2512 #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2513     __m256 lo,hi;
2514     split(x, &lo,&hi);
2515     return join<F>(_mm256_sqrt_ps(lo), _mm256_sqrt_ps(hi));
2516 #elif defined(JUMPER_IS_SSE2) || defined(JUMPER_IS_SSE41) || defined(JUMPER_IS_AVX)
2517     __m128 lo,hi;
2518     split(x, &lo,&hi);
2519     return join<F>(_mm_sqrt_ps(lo), _mm_sqrt_ps(hi));
2520 #elif defined(SK_CPU_ARM64)
2521     float32x4_t lo,hi;
2522     split(x, &lo,&hi);
2523     return join<F>(vsqrtq_f32(lo), vsqrtq_f32(hi));
2524 #elif defined(JUMPER_IS_NEON)
2525     auto sqrt = [](float32x4_t v) {
2526         auto est = vrsqrteq_f32(v);  // Estimate and two refinement steps for est = rsqrt(v).
2527         est *= vrsqrtsq_f32(v,est*est);
2528         est *= vrsqrtsq_f32(v,est*est);
2529         return v*est;                // sqrt(v) == v*rsqrt(v).
2530     };
2531     float32x4_t lo,hi;
2532     split(x, &lo,&hi);
2533     return join<F>(sqrt(lo), sqrt(hi));
2534 #else
2535     return F{
2536         sqrtf(x[0]), sqrtf(x[1]), sqrtf(x[2]), sqrtf(x[3]),
2537         sqrtf(x[4]), sqrtf(x[5]), sqrtf(x[6]), sqrtf(x[7]),
2538     };
2539 #endif
2540 }
2541 
2542 SI F floor_(F x) {
2543 #if defined(SK_CPU_ARM64)
2544     float32x4_t lo,hi;
2545     split(x, &lo,&hi);
2546     return join<F>(vrndmq_f32(lo), vrndmq_f32(hi));
2547 #elif defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2548     __m256 lo,hi;
2549     split(x, &lo,&hi);
2550     return join<F>(_mm256_floor_ps(lo), _mm256_floor_ps(hi));
2551 #elif defined(JUMPER_IS_SSE41) || defined(JUMPER_IS_AVX)
2552     __m128 lo,hi;
2553     split(x, &lo,&hi);
2554     return join<F>(_mm_floor_ps(lo), _mm_floor_ps(hi));
2555 #else
2556     F roundtrip = cast<F>(cast<I32>(x));
2557     return roundtrip - if_then_else(roundtrip > x, F(1), F(0));
2558 #endif
2559 }
2560 SI F fract(F x) { return x - floor_(x); }
2561 SI F abs_(F x) { return bit_cast<F>( bit_cast<I32>(x) & 0x7fffffff ); }
2562 
2563 // ~~~~~~ Basic / misc. stages ~~~~~~ //
2564 
2565 STAGE_GG(seed_shader, Ctx::None) {
2566     static const float iota[] = {
2567         0.5f, 1.5f, 2.5f, 3.5f, 4.5f, 5.5f, 6.5f, 7.5f,
2568         8.5f, 9.5f,10.5f,11.5f,12.5f,13.5f,14.5f,15.5f,
2569     };
2570     x = cast<F>(I32(dx)) + unaligned_load<F>(iota);
2571     y = cast<F>(I32(dy)) + 0.5f;
2572 }
2573 
2574 STAGE_GG(matrix_translate, const float* m) {
2575     x += m[0];
2576     y += m[1];
2577 }
2578 STAGE_GG(matrix_scale_translate, const float* m) {
2579     x = mad(x,m[0], m[2]);
2580     y = mad(y,m[1], m[3]);
2581 }
2582 STAGE_GG(matrix_2x3, const float* m) {
2583     auto X = mad(x,m[0], mad(y,m[2], m[4])),
2584          Y = mad(x,m[1], mad(y,m[3], m[5]));
2585     x = X;
2586     y = Y;
2587 }
2588 STAGE_GG(matrix_perspective, const float* m) {
2589     // N.B. Unlike the other matrix_ stages, this matrix is row-major.
2590     auto X = mad(x,m[0], mad(y,m[1], m[2])),
2591          Y = mad(x,m[3], mad(y,m[4], m[5])),
2592          Z = mad(x,m[6], mad(y,m[7], m[8]));
2593     x = X * rcp(Z);
2594     y = Y * rcp(Z);
2595 }
2596 
2597 STAGE_PP(uniform_color, const SkRasterPipeline_UniformColorCtx* c) {
2598     r = c->rgba[0];
2599     g = c->rgba[1];
2600     b = c->rgba[2];
2601     a = c->rgba[3];
2602 }
2603 STAGE_PP(black_color, Ctx::None) { r = g = b =   0; a = 255; }
2604 STAGE_PP(white_color, Ctx::None) { r = g = b = 255; a = 255; }
2605 
2606 STAGE_PP(set_rgb, const float rgb[3]) {
2607     r = from_float(rgb[0]);
2608     g = from_float(rgb[1]);
2609     b = from_float(rgb[2]);
2610 }
2611 
2612 STAGE_PP(clamp_0, Ctx::None) { /*definitely a noop*/ }
2613 STAGE_PP(clamp_1, Ctx::None) { /*_should_ be a noop*/ }
2614 
2615 STAGE_PP(clamp_a, Ctx::None) {
2616     r = min(r, a);
2617     g = min(g, a);
2618     b = min(b, a);
2619 }
2620 STAGE_PP(clamp_a_dst, Ctx::None) {
2621     dr = min(dr, da);
2622     dg = min(dg, da);
2623     db = min(db, da);
2624 }
2625 
2626 STAGE_PP(clamp_gamut, Ctx::None) {
2627     // It shouldn't be possible to get out-of-gamut
2628     // colors when working in lowp.
2629 }
2630 
2631 STAGE_PP(premul, Ctx::None) {
2632     r = div255(r * a);
2633     g = div255(g * a);
2634     b = div255(b * a);
2635 }
2636 STAGE_PP(premul_dst, Ctx::None) {
2637     dr = div255(dr * da);
2638     dg = div255(dg * da);
2639     db = div255(db * da);
2640 }
2641 
2642 STAGE_PP(force_opaque    , Ctx::None) {  a = 255; }
2643 STAGE_PP(force_opaque_dst, Ctx::None) { da = 255; }
2644 
2645 STAGE_PP(swap_rb, Ctx::None) {
2646     auto tmp = r;
2647     r = b;
2648     b = tmp;
2649 }
2650 STAGE_PP(swap_rb_dst, Ctx::None) {
2651     auto tmp = dr;
2652     dr = db;
2653     db = tmp;
2654 }
2655 
2656 STAGE_PP(move_src_dst, Ctx::None) {
2657     dr = r;
2658     dg = g;
2659     db = b;
2660     da = a;
2661 }
2662 
2663 STAGE_PP(move_dst_src, Ctx::None) {
2664     r = dr;
2665     g = dg;
2666     b = db;
2667     a = da;
2668 }
2669 
2670 // ~~~~~~ Blend modes ~~~~~~ //
2671 
2672 // The same logic applied to all 4 channels.
2673 #define BLEND_MODE(name)                                 \
2674     SI U16 name##_channel(U16 s, U16 d, U16 sa, U16 da); \
2675     STAGE_PP(name, Ctx::None) {                          \
2676         r = name##_channel(r,dr,a,da);                   \
2677         g = name##_channel(g,dg,a,da);                   \
2678         b = name##_channel(b,db,a,da);                   \
2679         a = name##_channel(a,da,a,da);                   \
2680     }                                                    \
2681     SI U16 name##_channel(U16 s, U16 d, U16 sa, U16 da)
2682 
2683     BLEND_MODE(clear)    { return 0; }
2684     BLEND_MODE(srcatop)  { return div255( s*da + d*inv(sa) ); }
2685     BLEND_MODE(dstatop)  { return div255( d*sa + s*inv(da) ); }
2686     BLEND_MODE(srcin)    { return div255( s*da ); }
2687     BLEND_MODE(dstin)    { return div255( d*sa ); }
2688     BLEND_MODE(srcout)   { return div255( s*inv(da) ); }
2689     BLEND_MODE(dstout)   { return div255( d*inv(sa) ); }
2690     BLEND_MODE(srcover)  { return s + div255( d*inv(sa) ); }
2691     BLEND_MODE(dstover)  { return d + div255( s*inv(da) ); }
2692     BLEND_MODE(modulate) { return div255( s*d ); }
2693     BLEND_MODE(multiply) { return div255( s*inv(da) + d*inv(sa) + s*d ); }
2694     BLEND_MODE(plus_)    { return min(s+d, 255); }
2695     BLEND_MODE(screen)   { return s + d - div255( s*d ); }
2696     BLEND_MODE(xor_)     { return div255( s*inv(da) + d*inv(sa) ); }
2697 #undef BLEND_MODE
2698 
2699 // The same logic applied to color, and srcover for alpha.
2700 #define BLEND_MODE(name)                                 \
2701     SI U16 name##_channel(U16 s, U16 d, U16 sa, U16 da); \
2702     STAGE_PP(name, Ctx::None) {                          \
2703         r = name##_channel(r,dr,a,da);                   \
2704         g = name##_channel(g,dg,a,da);                   \
2705         b = name##_channel(b,db,a,da);                   \
2706         a = a + div255( da*inv(a) );                     \
2707     }                                                    \
2708     SI U16 name##_channel(U16 s, U16 d, U16 sa, U16 da)
2709 
2710     BLEND_MODE(darken)     { return s + d -   div255( max(s*da, d*sa) ); }
2711     BLEND_MODE(lighten)    { return s + d -   div255( min(s*da, d*sa) ); }
2712     BLEND_MODE(difference) { return s + d - 2*div255( min(s*da, d*sa) ); }
2713     BLEND_MODE(exclusion)  { return s + d - 2*div255( s*d ); }
2714 
2715     BLEND_MODE(hardlight) {
2716         return div255( s*inv(da) + d*inv(sa) +
2717                        if_then_else(2*s <= sa, 2*s*d, sa*da - 2*(sa-s)*(da-d)) );
2718     }
2719     BLEND_MODE(overlay) {
2720         return div255( s*inv(da) + d*inv(sa) +
2721                        if_then_else(2*d <= da, 2*s*d, sa*da - 2*(sa-s)*(da-d)) );
2722     }
2723 #undef BLEND_MODE
2724 
2725 // ~~~~~~ Helpers for interacting with memory ~~~~~~ //
2726 
2727 template <typename T>
2728 SI T* ptr_at_xy(const SkRasterPipeline_MemoryCtx* ctx, size_t dx, size_t dy) {
2729     return (T*)ctx->pixels + dy*ctx->stride + dx;
2730 }
2731 
2732 template <typename T>
2733 SI U32 ix_and_ptr(T** ptr, const SkRasterPipeline_GatherCtx* ctx, F x, F y) {
2734     auto clamp = [](F v, F limit) {
2735         limit = bit_cast<F>( bit_cast<U32>(limit) - 1 );  // Exclusive -> inclusive.
2736         return min(max(0, v), limit);
2737     };
2738     x = clamp(x, ctx->width);
2739     y = clamp(y, ctx->height);
2740 
2741     *ptr = (const T*)ctx->pixels;
2742     return trunc_(y)*ctx->stride + trunc_(x);
2743 }
2744 
2745 template <typename V, typename T>
2746 SI V load(const T* ptr, size_t tail) {
2747     V v = 0;
2748     switch (tail & (N-1)) {
2749         case  0: memcpy(&v, ptr, sizeof(v)); break;
2750     #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2751         case 15: v[14] = ptr[14];
2752         case 14: v[13] = ptr[13];
2753         case 13: v[12] = ptr[12];
2754         case 12: memcpy(&v, ptr, 12*sizeof(T)); break;
2755         case 11: v[10] = ptr[10];
2756         case 10: v[ 9] = ptr[ 9];
2757         case  9: v[ 8] = ptr[ 8];
2758         case  8: memcpy(&v, ptr,  8*sizeof(T)); break;
2759     #endif
2760         case  7: v[ 6] = ptr[ 6];
2761         case  6: v[ 5] = ptr[ 5];
2762         case  5: v[ 4] = ptr[ 4];
2763         case  4: memcpy(&v, ptr,  4*sizeof(T)); break;
2764         case  3: v[ 2] = ptr[ 2];
2765         case  2: memcpy(&v, ptr,  2*sizeof(T)); break;
2766         case  1: v[ 0] = ptr[ 0];
2767     }
2768     return v;
2769 }
2770 template <typename V, typename T>
2771 SI void store(T* ptr, size_t tail, V v) {
2772     switch (tail & (N-1)) {
2773         case  0: memcpy(ptr, &v, sizeof(v)); break;
2774     #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2775         case 15: ptr[14] = v[14];
2776         case 14: ptr[13] = v[13];
2777         case 13: ptr[12] = v[12];
2778         case 12: memcpy(ptr, &v, 12*sizeof(T)); break;
2779         case 11: ptr[10] = v[10];
2780         case 10: ptr[ 9] = v[ 9];
2781         case  9: ptr[ 8] = v[ 8];
2782         case  8: memcpy(ptr, &v,  8*sizeof(T)); break;
2783     #endif
2784         case  7: ptr[ 6] = v[ 6];
2785         case  6: ptr[ 5] = v[ 5];
2786         case  5: ptr[ 4] = v[ 4];
2787         case  4: memcpy(ptr, &v,  4*sizeof(T)); break;
2788         case  3: ptr[ 2] = v[ 2];
2789         case  2: memcpy(ptr, &v,  2*sizeof(T)); break;
2790         case  1: ptr[ 0] = v[ 0];
2791     }
2792 }
2793 
2794 #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2795     template <typename V, typename T>
2796     SI V gather(const T* ptr, U32 ix) {
2797         return V{ ptr[ix[ 0]], ptr[ix[ 1]], ptr[ix[ 2]], ptr[ix[ 3]],
2798                   ptr[ix[ 4]], ptr[ix[ 5]], ptr[ix[ 6]], ptr[ix[ 7]],
2799                   ptr[ix[ 8]], ptr[ix[ 9]], ptr[ix[10]], ptr[ix[11]],
2800                   ptr[ix[12]], ptr[ix[13]], ptr[ix[14]], ptr[ix[15]], };
2801     }
2802 
2803     template<>
2804     F gather(const float* ptr, U32 ix) {
2805         __m256i lo, hi;
2806         split(ix, &lo, &hi);
2807 
2808         return join<F>(_mm256_i32gather_ps(ptr, lo, 4),
2809                        _mm256_i32gather_ps(ptr, hi, 4));
2810     }
2811 
2812     template<>
2813     U32 gather(const uint32_t* ptr, U32 ix) {
2814         __m256i lo, hi;
2815         split(ix, &lo, &hi);
2816 
2817         return join<U32>(_mm256_i32gather_epi32(ptr, lo, 4),
2818                          _mm256_i32gather_epi32(ptr, hi, 4));
2819     }
2820 #else
2821     template <typename V, typename T>
2822     SI V gather(const T* ptr, U32 ix) {
2823         return V{ ptr[ix[ 0]], ptr[ix[ 1]], ptr[ix[ 2]], ptr[ix[ 3]],
2824                   ptr[ix[ 4]], ptr[ix[ 5]], ptr[ix[ 6]], ptr[ix[ 7]], };
2825     }
2826 #endif
2827 
2828 
2829 // ~~~~~~ 32-bit memory loads and stores ~~~~~~ //
2830 
2831 SI void from_8888(U32 rgba, U16* r, U16* g, U16* b, U16* a) {
2832 #if 1 && defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
2833     // Swap the middle 128-bit lanes to make _mm256_packus_epi32() in cast_U16() work out nicely.
2834     __m256i _01,_23;
2835     split(rgba, &_01, &_23);
2836     __m256i _02 = _mm256_permute2x128_si256(_01,_23, 0x20),
2837             _13 = _mm256_permute2x128_si256(_01,_23, 0x31);
2838     rgba = join<U32>(_02, _13);
2839 
2840     auto cast_U16 = [](U32 v) -> U16 {
2841         __m256i _02,_13;
2842         split(v, &_02,&_13);
2843         return _mm256_packus_epi32(_02,_13);
2844     };
2845 #else
2846     auto cast_U16 = [](U32 v) -> U16 {
2847         return cast<U16>(v);
2848     };
2849 #endif
2850     *r = cast_U16(rgba & 65535) & 255;
2851     *g = cast_U16(rgba & 65535) >>  8;
2852     *b = cast_U16(rgba >>   16) & 255;
2853     *a = cast_U16(rgba >>   16) >>  8;
2854 }
2855 
2856 SI void load_8888_(const uint32_t* ptr, size_t tail, U16* r, U16* g, U16* b, U16* a) {
2857 #if 1 && defined(JUMPER_IS_NEON)
2858     uint8x8x4_t rgba;
2859     switch (tail & (N-1)) {
2860         case 0: rgba = vld4_u8     ((const uint8_t*)(ptr+0)         ); break;
2861         case 7: rgba = vld4_lane_u8((const uint8_t*)(ptr+6), rgba, 6);
2862         case 6: rgba = vld4_lane_u8((const uint8_t*)(ptr+5), rgba, 5);
2863         case 5: rgba = vld4_lane_u8((const uint8_t*)(ptr+4), rgba, 4);
2864         case 4: rgba = vld4_lane_u8((const uint8_t*)(ptr+3), rgba, 3);
2865         case 3: rgba = vld4_lane_u8((const uint8_t*)(ptr+2), rgba, 2);
2866         case 2: rgba = vld4_lane_u8((const uint8_t*)(ptr+1), rgba, 1);
2867         case 1: rgba = vld4_lane_u8((const uint8_t*)(ptr+0), rgba, 0);
2868     }
2869     *r = cast<U16>(rgba.val[0]);
2870     *g = cast<U16>(rgba.val[1]);
2871     *b = cast<U16>(rgba.val[2]);
2872     *a = cast<U16>(rgba.val[3]);
2873 #else
2874     from_8888(load<U32>(ptr, tail), r,g,b,a);
2875 #endif
2876 }
2877 SI void store_8888_(uint32_t* ptr, size_t tail, U16 r, U16 g, U16 b, U16 a) {
2878 #if 1 && defined(JUMPER_IS_NEON)
2879     uint8x8x4_t rgba = {{
2880         cast<U8>(r),
2881         cast<U8>(g),
2882         cast<U8>(b),
2883         cast<U8>(a),
2884     }};
2885     switch (tail & (N-1)) {
2886         case 0: vst4_u8     ((uint8_t*)(ptr+0), rgba   ); break;
2887         case 7: vst4_lane_u8((uint8_t*)(ptr+6), rgba, 6);
2888         case 6: vst4_lane_u8((uint8_t*)(ptr+5), rgba, 5);
2889         case 5: vst4_lane_u8((uint8_t*)(ptr+4), rgba, 4);
2890         case 4: vst4_lane_u8((uint8_t*)(ptr+3), rgba, 3);
2891         case 3: vst4_lane_u8((uint8_t*)(ptr+2), rgba, 2);
2892         case 2: vst4_lane_u8((uint8_t*)(ptr+1), rgba, 1);
2893         case 1: vst4_lane_u8((uint8_t*)(ptr+0), rgba, 0);
2894     }
2895 #else
2896     store(ptr, tail, cast<U32>(r | (g<<8)) <<  0
2897                    | cast<U32>(b | (a<<8)) << 16);
2898 #endif
2899 }
2900 
2901 STAGE_PP(load_8888, const SkRasterPipeline_MemoryCtx* ctx) {
2902     load_8888_(ptr_at_xy<const uint32_t>(ctx, dx,dy), tail, &r,&g,&b,&a);
2903 }
2904 STAGE_PP(load_8888_dst, const SkRasterPipeline_MemoryCtx* ctx) {
2905     load_8888_(ptr_at_xy<const uint32_t>(ctx, dx,dy), tail, &dr,&dg,&db,&da);
2906 }
2907 STAGE_PP(store_8888, const SkRasterPipeline_MemoryCtx* ctx) {
2908     store_8888_(ptr_at_xy<uint32_t>(ctx, dx,dy), tail, r,g,b,a);
2909 }
2910 STAGE_GP(gather_8888, const SkRasterPipeline_GatherCtx* ctx) {
2911     const uint32_t* ptr;
2912     U32 ix = ix_and_ptr(&ptr, ctx, x,y);
2913     from_8888(gather<U32>(ptr, ix), &r, &g, &b, &a);
2914 }
2915 
2916 // ~~~~~~ 16-bit memory loads and stores ~~~~~~ //
2917 
2918 SI void from_565(U16 rgb, U16* r, U16* g, U16* b) {
2919     // Format for 565 buffers: 15|rrrrr gggggg bbbbb|0
2920     U16 R = (rgb >> 11) & 31,
2921         G = (rgb >>  5) & 63,
2922         B = (rgb >>  0) & 31;
2923 
2924     // These bit replications are the same as multiplying by 255/31 or 255/63 to scale to 8-bit.
2925     *r = (R << 3) | (R >> 2);
2926     *g = (G << 2) | (G >> 4);
2927     *b = (B << 3) | (B >> 2);
2928 }
2929 SI void load_565_(const uint16_t* ptr, size_t tail, U16* r, U16* g, U16* b) {
2930     from_565(load<U16>(ptr, tail), r,g,b);
2931 }
2932 SI void store_565_(uint16_t* ptr, size_t tail, U16 r, U16 g, U16 b) {
2933     // Select the top 5,6,5 bits.
2934     U16 R = r >> 3,
2935         G = g >> 2,
2936         B = b >> 3;
2937     // Pack them back into 15|rrrrr gggggg bbbbb|0.
2938     store(ptr, tail, R << 11
2939                    | G <<  5
2940                    | B <<  0);
2941 }
2942 
2943 STAGE_PP(load_565, const SkRasterPipeline_MemoryCtx* ctx) {
2944     load_565_(ptr_at_xy<const uint16_t>(ctx, dx,dy), tail, &r,&g,&b);
2945     a = 255;
2946 }
2947 STAGE_PP(load_565_dst, const SkRasterPipeline_MemoryCtx* ctx) {
2948     load_565_(ptr_at_xy<const uint16_t>(ctx, dx,dy), tail, &dr,&dg,&db);
2949     da = 255;
2950 }
2951 STAGE_PP(store_565, const SkRasterPipeline_MemoryCtx* ctx) {
2952     store_565_(ptr_at_xy<uint16_t>(ctx, dx,dy), tail, r,g,b);
2953 }
2954 STAGE_GP(gather_565, const SkRasterPipeline_GatherCtx* ctx) {
2955     const uint16_t* ptr;
2956     U32 ix = ix_and_ptr(&ptr, ctx, x,y);
2957     from_565(gather<U16>(ptr, ix), &r, &g, &b);
2958     a = 255;
2959 }
2960 
2961 SI void from_4444(U16 rgba, U16* r, U16* g, U16* b, U16* a) {
2962     // Format for 4444 buffers: 15|rrrr gggg bbbb aaaa|0.
2963     U16 R = (rgba >> 12) & 15,
2964         G = (rgba >>  8) & 15,
2965         B = (rgba >>  4) & 15,
2966         A = (rgba >>  0) & 15;
2967 
2968     // Scale [0,15] to [0,255].
2969     *r = (R << 4) | R;
2970     *g = (G << 4) | G;
2971     *b = (B << 4) | B;
2972     *a = (A << 4) | A;
2973 }
2974 SI void load_4444_(const uint16_t* ptr, size_t tail, U16* r, U16* g, U16* b, U16* a) {
2975     from_4444(load<U16>(ptr, tail), r,g,b,a);
2976 }
2977 SI void store_4444_(uint16_t* ptr, size_t tail, U16 r, U16 g, U16 b, U16 a) {
2978     // Select the top 4 bits of each.
2979     U16 R = r >> 4,
2980         G = g >> 4,
2981         B = b >> 4,
2982         A = a >> 4;
2983     // Pack them back into 15|rrrr gggg bbbb aaaa|0.
2984     store(ptr, tail, R << 12
2985                    | G <<  8
2986                    | B <<  4
2987                    | A <<  0);
2988 }
2989 
2990 STAGE_PP(load_4444, const SkRasterPipeline_MemoryCtx* ctx) {
2991     load_4444_(ptr_at_xy<const uint16_t>(ctx, dx,dy), tail, &r,&g,&b,&a);
2992 }
2993 STAGE_PP(load_4444_dst, const SkRasterPipeline_MemoryCtx* ctx) {
2994     load_4444_(ptr_at_xy<const uint16_t>(ctx, dx,dy), tail, &dr,&dg,&db,&da);
2995 }
2996 STAGE_PP(store_4444, const SkRasterPipeline_MemoryCtx* ctx) {
2997     store_4444_(ptr_at_xy<uint16_t>(ctx, dx,dy), tail, r,g,b,a);
2998 }
2999 STAGE_GP(gather_4444, const SkRasterPipeline_GatherCtx* ctx) {
3000     const uint16_t* ptr;
3001     U32 ix = ix_and_ptr(&ptr, ctx, x,y);
3002     from_4444(gather<U16>(ptr, ix), &r,&g,&b,&a);
3003 }
3004 
3005 // ~~~~~~ 8-bit memory loads and stores ~~~~~~ //
3006 
3007 SI U16 load_8(const uint8_t* ptr, size_t tail) {
3008     return cast<U16>(load<U8>(ptr, tail));
3009 }
3010 SI void store_8(uint8_t* ptr, size_t tail, U16 v) {
3011     store(ptr, tail, cast<U8>(v));
3012 }
3013 
3014 STAGE_PP(load_a8, const SkRasterPipeline_MemoryCtx* ctx) {
3015     r = g = b = 0;
3016     a = load_8(ptr_at_xy<const uint8_t>(ctx, dx,dy), tail);
3017 }
3018 STAGE_PP(load_a8_dst, const SkRasterPipeline_MemoryCtx* ctx) {
3019     dr = dg = db = 0;
3020     da = load_8(ptr_at_xy<const uint8_t>(ctx, dx,dy), tail);
3021 }
3022 STAGE_PP(store_a8, const SkRasterPipeline_MemoryCtx* ctx) {
3023     store_8(ptr_at_xy<uint8_t>(ctx, dx,dy), tail, a);
3024 }
3025 STAGE_GP(gather_a8, const SkRasterPipeline_GatherCtx* ctx) {
3026     const uint8_t* ptr;
3027     U32 ix = ix_and_ptr(&ptr, ctx, x,y);
3028     r = g = b = 0;
3029     a = cast<U16>(gather<U8>(ptr, ix));
3030 }
3031 
3032 STAGE_PP(alpha_to_gray, Ctx::None) {
3033     r = g = b = a;
3034     a = 255;
3035 }
3036 STAGE_PP(alpha_to_gray_dst, Ctx::None) {
3037     dr = dg = db = da;
3038     da = 255;
3039 }
3040 STAGE_PP(luminance_to_alpha, Ctx::None) {
3041     a = (r*54 + g*183 + b*19)/256;  // 0.2126, 0.7152, 0.0722 with 256 denominator.
3042     r = g = b = 0;
3043 }
3044 
3045 // ~~~~~~ Coverage scales / lerps ~~~~~~ //
3046 
3047 STAGE_PP(scale_1_float, const float* f) {
3048     U16 c = from_float(*f);
3049     r = div255( r * c );
3050     g = div255( g * c );
3051     b = div255( b * c );
3052     a = div255( a * c );
3053 }
3054 STAGE_PP(lerp_1_float, const float* f) {
3055     U16 c = from_float(*f);
3056     r = lerp(dr, r, c);
3057     g = lerp(dg, g, c);
3058     b = lerp(db, b, c);
3059     a = lerp(da, a, c);
3060 }
3061 
3062 STAGE_PP(scale_u8, const SkRasterPipeline_MemoryCtx* ctx) {
3063     U16 c = load_8(ptr_at_xy<const uint8_t>(ctx, dx,dy), tail);
3064     r = div255( r * c );
3065     g = div255( g * c );
3066     b = div255( b * c );
3067     a = div255( a * c );
3068 }
3069 STAGE_PP(lerp_u8, const SkRasterPipeline_MemoryCtx* ctx) {
3070     U16 c = load_8(ptr_at_xy<const uint8_t>(ctx, dx,dy), tail);
3071     r = lerp(dr, r, c);
3072     g = lerp(dg, g, c);
3073     b = lerp(db, b, c);
3074     a = lerp(da, a, c);
3075 }
3076 
3077 // Derive alpha's coverage from rgb coverage and the values of src and dst alpha.
3078 SI U16 alpha_coverage_from_rgb_coverage(U16 a, U16 da, U16 cr, U16 cg, U16 cb) {
3079     return if_then_else(a < da, min(cr,cg,cb)
3080                               , max(cr,cg,cb));
3081 }
3082 STAGE_PP(scale_565, const SkRasterPipeline_MemoryCtx* ctx) {
3083     U16 cr,cg,cb;
3084     load_565_(ptr_at_xy<const uint16_t>(ctx, dx,dy), tail, &cr,&cg,&cb);
3085     U16 ca = alpha_coverage_from_rgb_coverage(a,da, cr,cg,cb);
3086 
3087     r = div255( r * cr );
3088     g = div255( g * cg );
3089     b = div255( b * cb );
3090     a = div255( a * ca );
3091 }
3092 STAGE_PP(lerp_565, const SkRasterPipeline_MemoryCtx* ctx) {
3093     U16 cr,cg,cb;
3094     load_565_(ptr_at_xy<const uint16_t>(ctx, dx,dy), tail, &cr,&cg,&cb);
3095     U16 ca = alpha_coverage_from_rgb_coverage(a,da, cr,cg,cb);
3096 
3097     r = lerp(dr, r, cr);
3098     g = lerp(dg, g, cg);
3099     b = lerp(db, b, cb);
3100     a = lerp(da, a, ca);
3101 }
3102 
3103 STAGE_PP(emboss, const SkRasterPipeline_EmbossCtx* ctx) {
3104     U16 mul = load_8(ptr_at_xy<const uint8_t>(&ctx->mul, dx,dy), tail),
3105         add = load_8(ptr_at_xy<const uint8_t>(&ctx->add, dx,dy), tail);
3106 
3107     r = min(div255(r*mul) + add, a);
3108     g = min(div255(g*mul) + add, a);
3109     b = min(div255(b*mul) + add, a);
3110 }
3111 
3112 
3113 // ~~~~~~ Gradient stages ~~~~~~ //
3114 
3115 // Clamp x to [0,1], both sides inclusive (think, gradients).
3116 // Even repeat and mirror funnel through a clamp to handle bad inputs like +Inf, NaN.
3117 SI F clamp_01(F v) { return min(max(0, v), 1); }
3118 
3119 STAGE_GG(clamp_x_1 , Ctx::None) { x = clamp_01(x); }
3120 STAGE_GG(repeat_x_1, Ctx::None) { x = clamp_01(x - floor_(x)); }
3121 STAGE_GG(mirror_x_1, Ctx::None) {
3122     auto two = [](F x){ return x+x; };
3123     x = clamp_01(abs_( (x-1.0f) - two(floor_((x-1.0f)*0.5f)) - 1.0f ));
3124 }
3125 
3126 SI I16 cond_to_mask_16(I32 cond) { return cast<I16>(cond); }
3127 
3128 STAGE_GG(decal_x, SkRasterPipeline_DecalTileCtx* ctx) {
3129     auto w = ctx->limit_x;
3130     unaligned_store(ctx->mask, cond_to_mask_16((0 <= x) & (x < w)));
3131 }
3132 STAGE_GG(decal_y, SkRasterPipeline_DecalTileCtx* ctx) {
3133     auto h = ctx->limit_y;
3134     unaligned_store(ctx->mask, cond_to_mask_16((0 <= y) & (y < h)));
3135 }
3136 STAGE_GG(decal_x_and_y, SkRasterPipeline_DecalTileCtx* ctx) {
3137     auto w = ctx->limit_x;
3138     auto h = ctx->limit_y;
3139     unaligned_store(ctx->mask, cond_to_mask_16((0 <= x) & (x < w) & (0 <= y) & (y < h)));
3140 }
3141 STAGE_PP(check_decal_mask, SkRasterPipeline_DecalTileCtx* ctx) {
3142     auto mask = unaligned_load<U16>(ctx->mask);
3143     r = r & mask;
3144     g = g & mask;
3145     b = b & mask;
3146     a = a & mask;
3147 }
3148 
3149 SI void round_F_to_U16(F    R, F    G, F    B, F    A, bool interpolatedInPremul,
3150                        U16* r, U16* g, U16* b, U16* a) {
3151     auto round = [](F x) { return cast<U16>(x * 255.0f + 0.5f); };
3152 
3153     F limit = interpolatedInPremul ? A
3154                                    : 1;
3155     *r = round(min(max(0,R), limit));
3156     *g = round(min(max(0,G), limit));
3157     *b = round(min(max(0,B), limit));
3158     *a = round(A);  // we assume alpha is already in [0,1].
3159 }
3160 
3161 SI void gradient_lookup(const SkRasterPipeline_GradientCtx* c, U32 idx, F t,
3162                         U16* r, U16* g, U16* b, U16* a) {
3163 
3164     F fr, fg, fb, fa, br, bg, bb, ba;
3165 #if defined(JUMPER_IS_HSW) || defined(JUMPER_IS_AVX512)
3166     if (c->stopCount <=8) {
3167         __m256i lo, hi;
3168         split(idx, &lo, &hi);
3169 
3170         fr = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[0]), lo),
3171                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[0]), hi));
3172         br = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[0]), lo),
3173                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[0]), hi));
3174         fg = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[1]), lo),
3175                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[1]), hi));
3176         bg = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[1]), lo),
3177                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[1]), hi));
3178         fb = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[2]), lo),
3179                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[2]), hi));
3180         bb = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[2]), lo),
3181                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[2]), hi));
3182         fa = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[3]), lo),
3183                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->fs[3]), hi));
3184         ba = join<F>(_mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[3]), lo),
3185                      _mm256_permutevar8x32_ps(_mm256_loadu_ps(c->bs[3]), hi));
3186     } else
3187 #endif
3188     {
3189         fr = gather<F>(c->fs[0], idx);
3190         fg = gather<F>(c->fs[1], idx);
3191         fb = gather<F>(c->fs[2], idx);
3192         fa = gather<F>(c->fs[3], idx);
3193         br = gather<F>(c->bs[0], idx);
3194         bg = gather<F>(c->bs[1], idx);
3195         bb = gather<F>(c->bs[2], idx);
3196         ba = gather<F>(c->bs[3], idx);
3197     }
3198     round_F_to_U16(mad(t, fr, br),
3199                    mad(t, fg, bg),
3200                    mad(t, fb, bb),
3201                    mad(t, fa, ba),
3202                    c->interpolatedInPremul,
3203                    r,g,b,a);
3204 }
3205 
3206 STAGE_GP(gradient, const SkRasterPipeline_GradientCtx* c) {
3207     auto t = x;
3208     U32 idx = 0;
3209 
3210     // N.B. The loop starts at 1 because idx 0 is the color to use before the first stop.
3211     for (size_t i = 1; i < c->stopCount; i++) {
3212         idx += if_then_else(t >= c->ts[i], U32(1), U32(0));
3213     }
3214 
3215     gradient_lookup(c, idx, t, &r, &g, &b, &a);
3216 }
3217 
3218 STAGE_GP(evenly_spaced_gradient, const SkRasterPipeline_GradientCtx* c) {
3219     auto t = x;
3220     auto idx = trunc_(t * (c->stopCount-1));
3221     gradient_lookup(c, idx, t, &r, &g, &b, &a);
3222 }
3223 
3224 STAGE_GP(evenly_spaced_2_stop_gradient, const SkRasterPipeline_EvenlySpaced2StopGradientCtx* c) {
3225     auto t = x;
3226     round_F_to_U16(mad(t, c->f[0], c->b[0]),
3227                    mad(t, c->f[1], c->b[1]),
3228                    mad(t, c->f[2], c->b[2]),
3229                    mad(t, c->f[3], c->b[3]),
3230                    c->interpolatedInPremul,
3231                    &r,&g,&b,&a);
3232 }
3233 
3234 STAGE_GG(xy_to_unit_angle, Ctx::None) {
3235     F xabs = abs_(x),
3236       yabs = abs_(y);
3237 
3238     F slope = min(xabs, yabs)/max(xabs, yabs);
3239     F s = slope * slope;
3240 
3241     // Use a 7th degree polynomial to approximate atan.
3242     // This was generated using sollya.gforge.inria.fr.
3243     // A float optimized polynomial was generated using the following command.
3244     // P1 = fpminimax((1/(2*Pi))*atan(x),[|1,3,5,7|],[|24...|],[2^(-40),1],relative);
3245     F phi = slope
3246              * (0.15912117063999176025390625f     + s
3247              * (-5.185396969318389892578125e-2f   + s
3248              * (2.476101927459239959716796875e-2f + s
3249              * (-7.0547382347285747528076171875e-3f))));
3250 
3251     phi = if_then_else(xabs < yabs, 1.0f/4.0f - phi, phi);
3252     phi = if_then_else(x < 0.0f   , 1.0f/2.0f - phi, phi);
3253     phi = if_then_else(y < 0.0f   , 1.0f - phi     , phi);
3254     phi = if_then_else(phi != phi , 0              , phi);  // Check for NaN.
3255     x = phi;
3256 }
3257 STAGE_GG(xy_to_radius, Ctx::None) {
3258     x = sqrt_(x*x + y*y);
3259 }
3260 
3261 // ~~~~~~ Compound stages ~~~~~~ //
3262 
3263 STAGE_PP(srcover_rgba_8888, const SkRasterPipeline_MemoryCtx* ctx) {
3264     auto ptr = ptr_at_xy<uint32_t>(ctx, dx,dy);
3265 
3266     load_8888_(ptr, tail, &dr,&dg,&db,&da);
3267     r = r + div255( dr*inv(a) );
3268     g = g + div255( dg*inv(a) );
3269     b = b + div255( db*inv(a) );
3270     a = a + div255( da*inv(a) );
3271     store_8888_(ptr, tail, r,g,b,a);
3272 }
3273 
3274 // Now we'll add null stand-ins for stages we haven't implemented in lowp.
3275 // If a pipeline uses these stages, it'll boot it out of lowp into highp.
3276 #define NOT_IMPLEMENTED(st) static void (*st)(void) = nullptr;
3277     NOT_IMPLEMENTED(callback)
3278     NOT_IMPLEMENTED(load_rgba)
3279     NOT_IMPLEMENTED(store_rgba)
3280     NOT_IMPLEMENTED(unbounded_set_rgb)
3281     NOT_IMPLEMENTED(unbounded_uniform_color)
3282     NOT_IMPLEMENTED(unpremul)
3283     NOT_IMPLEMENTED(dither)
3284     NOT_IMPLEMENTED(from_srgb)
3285     NOT_IMPLEMENTED(to_srgb)
3286     NOT_IMPLEMENTED(load_f16)
3287     NOT_IMPLEMENTED(load_f16_dst)
3288     NOT_IMPLEMENTED(store_f16)
3289     NOT_IMPLEMENTED(gather_f16)
3290     NOT_IMPLEMENTED(load_f32)
3291     NOT_IMPLEMENTED(load_f32_dst)
3292     NOT_IMPLEMENTED(store_f32)
3293     NOT_IMPLEMENTED(gather_f32)
3294     NOT_IMPLEMENTED(load_1010102)
3295     NOT_IMPLEMENTED(load_1010102_dst)
3296     NOT_IMPLEMENTED(store_1010102)
3297     NOT_IMPLEMENTED(gather_1010102)
3298     NOT_IMPLEMENTED(store_u16_be)
3299     NOT_IMPLEMENTED(byte_tables)
3300     NOT_IMPLEMENTED(colorburn)
3301     NOT_IMPLEMENTED(colordodge)
3302     NOT_IMPLEMENTED(softlight)
3303     NOT_IMPLEMENTED(hue)
3304     NOT_IMPLEMENTED(saturation)
3305     NOT_IMPLEMENTED(color)
3306     NOT_IMPLEMENTED(luminosity)
3307     NOT_IMPLEMENTED(matrix_3x3)
3308     NOT_IMPLEMENTED(matrix_3x4)
3309     NOT_IMPLEMENTED(matrix_4x5)
3310     NOT_IMPLEMENTED(matrix_4x3)
3311     NOT_IMPLEMENTED(parametric)
3312     NOT_IMPLEMENTED(gamma)
3313     NOT_IMPLEMENTED(rgb_to_hsl)
3314     NOT_IMPLEMENTED(hsl_to_rgb)
3315     NOT_IMPLEMENTED(gauss_a_to_rgba)
3316     NOT_IMPLEMENTED(mirror_x)
3317     NOT_IMPLEMENTED(repeat_x)
3318     NOT_IMPLEMENTED(mirror_y)
3319     NOT_IMPLEMENTED(repeat_y)
3320     NOT_IMPLEMENTED(negate_x)
3321     NOT_IMPLEMENTED(bilerp_clamp_8888)
3322     NOT_IMPLEMENTED(bilinear_nx)
3323     NOT_IMPLEMENTED(bilinear_ny)
3324     NOT_IMPLEMENTED(bilinear_px)
3325     NOT_IMPLEMENTED(bilinear_py)
3326     NOT_IMPLEMENTED(bicubic_n3x)
3327     NOT_IMPLEMENTED(bicubic_n1x)
3328     NOT_IMPLEMENTED(bicubic_p1x)
3329     NOT_IMPLEMENTED(bicubic_p3x)
3330     NOT_IMPLEMENTED(bicubic_n3y)
3331     NOT_IMPLEMENTED(bicubic_n1y)
3332     NOT_IMPLEMENTED(bicubic_p1y)
3333     NOT_IMPLEMENTED(bicubic_p3y)
3334     NOT_IMPLEMENTED(save_xy)
3335     NOT_IMPLEMENTED(accumulate)
3336     NOT_IMPLEMENTED(xy_to_2pt_conical_well_behaved)
3337     NOT_IMPLEMENTED(xy_to_2pt_conical_strip)
3338     NOT_IMPLEMENTED(xy_to_2pt_conical_focal_on_circle)
3339     NOT_IMPLEMENTED(xy_to_2pt_conical_smaller)
3340     NOT_IMPLEMENTED(xy_to_2pt_conical_greater)
3341     NOT_IMPLEMENTED(alter_2pt_conical_compensate_focal)
3342     NOT_IMPLEMENTED(alter_2pt_conical_unswap)
3343     NOT_IMPLEMENTED(mask_2pt_conical_nan)
3344     NOT_IMPLEMENTED(mask_2pt_conical_degenerates)
3345     NOT_IMPLEMENTED(apply_vector_mask)
3346 #undef NOT_IMPLEMENTED
3347 
3348 #endif//defined(JUMPER_IS_SCALAR) controlling whether we build lowp stages
3349 }  // namespace lowp
3350 
3351 }  // namespace SK_OPTS_NS
3352 
3353 #endif//SkRasterPipeline_opts_DEFINED
3354