OSDN Git Service

i965/blorp: Add INTEL_DEBUG=blorp flag.
[android-x86/external-mesa.git] / src / mesa / drivers / dri / i965 / brw_blorp_blit.cpp
1 /*
2  * Copyright © 2012 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23
24 #include "main/teximage.h"
25 #include "main/fbobject.h"
26 #include "main/renderbuffer.h"
27
28 #include "glsl/ralloc.h"
29
30 #include "intel_fbo.h"
31
32 #include "brw_blorp.h"
33 #include "brw_context.h"
34 #include "brw_eu.h"
35 #include "brw_state.h"
36
37
38 /**
39  * Helper function for handling mirror image blits.
40  *
41  * If coord0 > coord1, swap them and invert the "mirror" boolean.
42  */
43 static inline void
44 fixup_mirroring(bool &mirror, GLint &coord0, GLint &coord1)
45 {
46    if (coord0 > coord1) {
47       mirror = !mirror;
48       GLint tmp = coord0;
49       coord0 = coord1;
50       coord1 = tmp;
51    }
52 }
53
54
55 /**
56  * Adjust {src,dst}_x{0,1} to account for clipping and scissoring of
57  * destination coordinates.
58  *
59  * Return true if there is still blitting to do, false if all pixels got
60  * rejected by the clip and/or scissor.
61  *
62  * For clarity, the nomenclature of this function assumes we are clipping and
63  * scissoring the X coordinate; the exact same logic applies for Y
64  * coordinates.
65  *
66  * Note: this function may also be used to account for clipping of source
67  * coordinates, by swapping the roles of src and dst.
68  */
69 static inline bool
70 clip_or_scissor(bool mirror, GLint &src_x0, GLint &src_x1, GLint &dst_x0,
71                 GLint &dst_x1, GLint fb_xmin, GLint fb_xmax)
72 {
73    /* If we are going to scissor everything away, stop. */
74    if (!(fb_xmin < fb_xmax &&
75          dst_x0 < fb_xmax &&
76          fb_xmin < dst_x1 &&
77          dst_x0 < dst_x1)) {
78       return false;
79    }
80
81    /* Clip the destination rectangle, and keep track of how many pixels we
82     * clipped off of the left and right sides of it.
83     */
84    GLint pixels_clipped_left = 0;
85    GLint pixels_clipped_right = 0;
86    if (dst_x0 < fb_xmin) {
87       pixels_clipped_left = fb_xmin - dst_x0;
88       dst_x0 = fb_xmin;
89    }
90    if (fb_xmax < dst_x1) {
91       pixels_clipped_right = dst_x1 - fb_xmax;
92       dst_x1 = fb_xmax;
93    }
94
95    /* If we are mirrored, then before applying pixels_clipped_{left,right} to
96     * the source coordinates, we need to flip them to account for the
97     * mirroring.
98     */
99    if (mirror) {
100       GLint tmp = pixels_clipped_left;
101       pixels_clipped_left = pixels_clipped_right;
102       pixels_clipped_right = tmp;
103    }
104
105    /* Adjust the source rectangle to remove the pixels corresponding to those
106     * that were clipped/scissored out of the destination rectangle.
107     */
108    src_x0 += pixels_clipped_left;
109    src_x1 -= pixels_clipped_right;
110
111    return true;
112 }
113
114
115 static struct intel_mipmap_tree *
116 find_miptree(GLbitfield buffer_bit, struct intel_renderbuffer *irb)
117 {
118    struct intel_mipmap_tree *mt = irb->mt;
119    if (buffer_bit == GL_STENCIL_BUFFER_BIT && mt->stencil_mt)
120       mt = mt->stencil_mt;
121    return mt;
122 }
123
124 void
125 brw_blorp_blit_miptrees(struct intel_context *intel,
126                         struct intel_mipmap_tree *src_mt,
127                         unsigned src_level, unsigned src_layer,
128                         struct intel_mipmap_tree *dst_mt,
129                         unsigned dst_level, unsigned dst_layer,
130                         int src_x0, int src_y0,
131                         int dst_x0, int dst_y0,
132                         int dst_x1, int dst_y1,
133                         bool mirror_x, bool mirror_y)
134 {
135    brw_blorp_blit_params params(brw_context(&intel->ctx),
136                                 src_mt, src_level, src_layer,
137                                 dst_mt, dst_level, dst_layer,
138                                 src_x0, src_y0,
139                                 dst_x0, dst_y0,
140                                 dst_x1, dst_y1,
141                                 mirror_x, mirror_y);
142    brw_blorp_exec(intel, &params);
143 }
144
145 static void
146 do_blorp_blit(struct intel_context *intel, GLbitfield buffer_bit,
147               struct intel_renderbuffer *src_irb,
148               struct intel_renderbuffer *dst_irb,
149               GLint srcX0, GLint srcY0,
150               GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
151               bool mirror_x, bool mirror_y)
152 {
153    /* Find source/dst miptrees */
154    struct intel_mipmap_tree *src_mt = find_miptree(buffer_bit, src_irb);
155    struct intel_mipmap_tree *dst_mt = find_miptree(buffer_bit, dst_irb);
156
157    /* Get ready to blit.  This includes depth resolving the src and dst
158     * buffers if necessary.
159     */
160    intel_renderbuffer_resolve_depth(intel, src_irb);
161    intel_renderbuffer_resolve_depth(intel, dst_irb);
162
163    /* Do the blit */
164    brw_blorp_blit_miptrees(intel,
165                            src_mt, src_irb->mt_level, src_irb->mt_layer,
166                            dst_mt, dst_irb->mt_level, dst_irb->mt_layer,
167                            srcX0, srcY0, dstX0, dstY0, dstX1, dstY1,
168                            mirror_x, mirror_y);
169
170    intel_renderbuffer_set_needs_hiz_resolve(dst_irb);
171    intel_renderbuffer_set_needs_downsample(dst_irb);
172 }
173
174
175 static bool
176 formats_match(GLbitfield buffer_bit, struct intel_renderbuffer *src_irb,
177               struct intel_renderbuffer *dst_irb)
178 {
179    /* Note: don't just check gl_renderbuffer::Format, because in some cases
180     * multiple gl_formats resolve to the same native type in the miptree (for
181     * example MESA_FORMAT_X8_Z24 and MESA_FORMAT_S8_Z24), and we can blit
182     * between those formats.
183     */
184    gl_format src_format = find_miptree(buffer_bit, src_irb)->format;
185    gl_format dst_format = find_miptree(buffer_bit, dst_irb)->format;
186
187    gl_format linear_src_format = _mesa_get_srgb_format_linear(src_format);
188    gl_format linear_dst_format = _mesa_get_srgb_format_linear(dst_format);
189
190    /* Normally, we require the formats to be equal.  However, we also support
191     * blitting from ARGB to XRGB (discarding alpha), and from XRGB to ARGB
192     * (overriding alpha to 1.0 via blending).
193     */
194    return linear_src_format == linear_dst_format ||
195           (linear_src_format == MESA_FORMAT_XRGB8888 &&
196            linear_dst_format == MESA_FORMAT_ARGB8888) ||
197           (linear_src_format == MESA_FORMAT_ARGB8888 &&
198            linear_dst_format == MESA_FORMAT_XRGB8888);
199 }
200
201 static bool
202 try_blorp_blit(struct intel_context *intel,
203                GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
204                GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
205                GLenum filter, GLbitfield buffer_bit)
206 {
207    struct gl_context *ctx = &intel->ctx;
208
209    /* Sync up the state of window system buffers.  We need to do this before
210     * we go looking for the buffers.
211     */
212    intel_prepare_render(intel);
213
214    const struct gl_framebuffer *read_fb = ctx->ReadBuffer;
215    const struct gl_framebuffer *draw_fb = ctx->DrawBuffer;
216
217    /* Detect if the blit needs to be mirrored */
218    bool mirror_x = false, mirror_y = false;
219    fixup_mirroring(mirror_x, srcX0, srcX1);
220    fixup_mirroring(mirror_x, dstX0, dstX1);
221    fixup_mirroring(mirror_y, srcY0, srcY1);
222    fixup_mirroring(mirror_y, dstY0, dstY1);
223
224    /* Make sure width and height match */
225    if (srcX1 - srcX0 != dstX1 - dstX0) return false;
226    if (srcY1 - srcY0 != dstY1 - dstY0) return false;
227
228    /* If the destination rectangle needs to be clipped or scissored, do so.
229     */
230    if (!(clip_or_scissor(mirror_x, srcX0, srcX1, dstX0, dstX1,
231                          draw_fb->_Xmin, draw_fb->_Xmax) &&
232          clip_or_scissor(mirror_y, srcY0, srcY1, dstY0, dstY1,
233                          draw_fb->_Ymin, draw_fb->_Ymax))) {
234       /* Everything got clipped/scissored away, so the blit was successful. */
235       return true;
236    }
237
238    /* If the source rectangle needs to be clipped or scissored, do so. */
239    if (!(clip_or_scissor(mirror_x, dstX0, dstX1, srcX0, srcX1,
240                          0, read_fb->Width) &&
241          clip_or_scissor(mirror_y, dstY0, dstY1, srcY0, srcY1,
242                          0, read_fb->Height))) {
243       /* Everything got clipped/scissored away, so the blit was successful. */
244       return true;
245    }
246
247    /* Account for the fact that in the system framebuffer, the origin is at
248     * the lower left.
249     */
250    if (_mesa_is_winsys_fbo(read_fb)) {
251       GLint tmp = read_fb->Height - srcY0;
252       srcY0 = read_fb->Height - srcY1;
253       srcY1 = tmp;
254       mirror_y = !mirror_y;
255    }
256    if (_mesa_is_winsys_fbo(draw_fb)) {
257       GLint tmp = draw_fb->Height - dstY0;
258       dstY0 = draw_fb->Height - dstY1;
259       dstY1 = tmp;
260       mirror_y = !mirror_y;
261    }
262
263    /* Find buffers */
264    struct intel_renderbuffer *src_irb;
265    struct intel_renderbuffer *dst_irb;
266    switch (buffer_bit) {
267    case GL_COLOR_BUFFER_BIT:
268       src_irb = intel_renderbuffer(read_fb->_ColorReadBuffer);
269       for (unsigned i = 0; i < ctx->DrawBuffer->_NumColorDrawBuffers; ++i) {
270          dst_irb = intel_renderbuffer(ctx->DrawBuffer->_ColorDrawBuffers[i]);
271          if (dst_irb && !formats_match(buffer_bit, src_irb, dst_irb))
272             return false;
273       }
274       for (unsigned i = 0; i < ctx->DrawBuffer->_NumColorDrawBuffers; ++i) {
275          dst_irb = intel_renderbuffer(ctx->DrawBuffer->_ColorDrawBuffers[i]);
276          if (dst_irb)
277             do_blorp_blit(intel, buffer_bit, src_irb, dst_irb, srcX0, srcY0,
278                           dstX0, dstY0, dstX1, dstY1, mirror_x, mirror_y);
279       }
280       break;
281    case GL_DEPTH_BUFFER_BIT:
282       src_irb =
283          intel_renderbuffer(read_fb->Attachment[BUFFER_DEPTH].Renderbuffer);
284       dst_irb =
285          intel_renderbuffer(draw_fb->Attachment[BUFFER_DEPTH].Renderbuffer);
286       if (!formats_match(buffer_bit, src_irb, dst_irb))
287          return false;
288       do_blorp_blit(intel, buffer_bit, src_irb, dst_irb, srcX0, srcY0,
289                     dstX0, dstY0, dstX1, dstY1, mirror_x, mirror_y);
290       break;
291    case GL_STENCIL_BUFFER_BIT:
292       src_irb =
293          intel_renderbuffer(read_fb->Attachment[BUFFER_STENCIL].Renderbuffer);
294       dst_irb =
295          intel_renderbuffer(draw_fb->Attachment[BUFFER_STENCIL].Renderbuffer);
296       if (!formats_match(buffer_bit, src_irb, dst_irb))
297          return false;
298       do_blorp_blit(intel, buffer_bit, src_irb, dst_irb, srcX0, srcY0,
299                     dstX0, dstY0, dstX1, dstY1, mirror_x, mirror_y);
300       break;
301    default:
302       assert(false);
303    }
304
305    return true;
306 }
307
308 bool
309 brw_blorp_copytexsubimage(struct intel_context *intel,
310                           struct gl_renderbuffer *src_rb,
311                           struct gl_texture_image *dst_image,
312                           int srcX0, int srcY0,
313                           int dstX0, int dstY0,
314                           int width, int height)
315 {
316    struct gl_context *ctx = &intel->ctx;
317    struct intel_renderbuffer *src_irb = intel_renderbuffer(src_rb);
318    struct intel_renderbuffer *dst_irb;
319
320    /* BLORP is not supported before Gen6. */
321    if (intel->gen < 6)
322       return false;
323
324    /* Create a fake/wrapper renderbuffer to allow us to use do_blorp_blit(). */
325    dst_irb = intel_create_fake_renderbuffer_wrapper(intel, dst_image);
326    if (!dst_irb)
327       return false;
328
329    struct gl_renderbuffer *dst_rb = &dst_irb->Base.Base;
330
331    /* Unlike BlitFramebuffer, CopyTexSubImage doesn't have a buffer bit.
332     * It's only used by find_miptee() to decide whether to dereference the
333     * separate stencil miptree.  In the case of packed depth/stencil, core
334     * Mesa hands us the depth attachment as src_rb (not stencil), so assume
335     * non-stencil for now.  A buffer bit of 0 works for both color and depth.
336     */
337    GLbitfield buffer_bit = 0;
338
339    if (!formats_match(buffer_bit, src_irb, dst_irb)) {
340       dst_rb->Delete(ctx, dst_rb);
341       return false;
342    }
343
344    /* Source clipping shouldn't be necessary, since copytexsubimage (in
345     * src/mesa/main/teximage.c) calls _mesa_clip_copytexsubimage() which
346     * takes care of it.
347     *
348     * Destination clipping shouldn't be necessary since the restrictions on
349     * glCopyTexSubImage prevent the user from specifying a destination rectangle
350     * that falls outside the bounds of the destination texture.
351     * See error_check_subtexture_dimensions().
352     */
353
354    int srcY1 = srcY0 + height;
355    int dstX1 = dstX0 + width;
356    int dstY1 = dstY0 + height;
357
358    /* Sync up the state of window system buffers.  We need to do this before
359     * we go looking for the buffers.
360     */
361    intel_prepare_render(intel);
362
363    /* Account for the fact that in the system framebuffer, the origin is at
364     * the lower left.
365     */
366    bool mirror_y = false;
367    if (_mesa_is_winsys_fbo(ctx->ReadBuffer)) {
368       GLint tmp = src_rb->Height - srcY0;
369       srcY0 = src_rb->Height - srcY1;
370       srcY1 = tmp;
371       mirror_y = true;
372    }
373
374    do_blorp_blit(intel, buffer_bit, src_irb, dst_irb,
375                  srcX0, srcY0, dstX0, dstY0, dstX1, dstY1, false, mirror_y);
376
377    /* If we're copying a packed depth stencil texture, the above do_blorp_blit
378     * copied depth (since buffer_bit != GL_STENCIL_BIT).  Now copy stencil as
379     * well.  There's no need to do a formats_match() check because the separate
380     * stencil buffer is always S8.
381     */
382    src_rb = ctx->ReadBuffer->Attachment[BUFFER_STENCIL].Renderbuffer;
383    if (_mesa_get_format_bits(dst_image->TexFormat, GL_STENCIL_BITS) > 0 &&
384        src_rb != NULL) {
385       src_irb = intel_renderbuffer(src_rb);
386       do_blorp_blit(intel, GL_STENCIL_BUFFER_BIT, src_irb, dst_irb,
387                     srcX0, srcY0, dstX0, dstY0, dstX1, dstY1, false, mirror_y);
388    }
389
390    dst_rb->Delete(ctx, dst_rb);
391    return true;
392 }
393
394
395 GLbitfield
396 brw_blorp_framebuffer(struct intel_context *intel,
397                       GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
398                       GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
399                       GLbitfield mask, GLenum filter)
400 {
401    /* BLORP is not supported before Gen6. */
402    if (intel->gen < 6)
403       return mask;
404
405    static GLbitfield buffer_bits[] = {
406       GL_COLOR_BUFFER_BIT,
407       GL_DEPTH_BUFFER_BIT,
408       GL_STENCIL_BUFFER_BIT,
409    };
410
411    for (unsigned int i = 0; i < ARRAY_SIZE(buffer_bits); ++i) {
412       if ((mask & buffer_bits[i]) &&
413        try_blorp_blit(intel,
414                       srcX0, srcY0, srcX1, srcY1,
415                       dstX0, dstY0, dstX1, dstY1,
416                       filter, buffer_bits[i])) {
417          mask &= ~buffer_bits[i];
418       }
419    }
420
421    return mask;
422 }
423
424
425 /**
426  * Enum to specify the order of arguments in a sampler message
427  */
428 enum sampler_message_arg
429 {
430    SAMPLER_MESSAGE_ARG_U_FLOAT,
431    SAMPLER_MESSAGE_ARG_V_FLOAT,
432    SAMPLER_MESSAGE_ARG_U_INT,
433    SAMPLER_MESSAGE_ARG_V_INT,
434    SAMPLER_MESSAGE_ARG_SI_INT,
435    SAMPLER_MESSAGE_ARG_MCS_INT,
436    SAMPLER_MESSAGE_ARG_ZERO_INT,
437 };
438
439 /**
440  * Generator for WM programs used in BLORP blits.
441  *
442  * The bulk of the work done by the WM program is to wrap and unwrap the
443  * coordinate transformations used by the hardware to store surfaces in
444  * memory.  The hardware transforms a pixel location (X, Y, S) (where S is the
445  * sample index for a multisampled surface) to a memory offset by the
446  * following formulas:
447  *
448  *   offset = tile(tiling_format, encode_msaa(num_samples, layout, X, Y, S))
449  *   (X, Y, S) = decode_msaa(num_samples, layout, detile(tiling_format, offset))
450  *
451  * For a single-sampled surface, or for a multisampled surface using
452  * INTEL_MSAA_LAYOUT_UMS, encode_msaa() and decode_msaa are the identity
453  * function:
454  *
455  *   encode_msaa(1, NONE, X, Y, 0) = (X, Y, 0)
456  *   decode_msaa(1, NONE, X, Y, 0) = (X, Y, 0)
457  *   encode_msaa(n, UMS, X, Y, S) = (X, Y, S)
458  *   decode_msaa(n, UMS, X, Y, S) = (X, Y, S)
459  *
460  * For a 4x multisampled surface using INTEL_MSAA_LAYOUT_IMS, encode_msaa()
461  * embeds the sample number into bit 1 of the X and Y coordinates:
462  *
463  *   encode_msaa(4, IMS, X, Y, S) = (X', Y', 0)
464  *     where X' = (X & ~0b1) << 1 | (S & 0b1) << 1 | (X & 0b1)
465  *           Y' = (Y & ~0b1 ) << 1 | (S & 0b10) | (Y & 0b1)
466  *   decode_msaa(4, IMS, X, Y, 0) = (X', Y', S)
467  *     where X' = (X & ~0b11) >> 1 | (X & 0b1)
468  *           Y' = (Y & ~0b11) >> 1 | (Y & 0b1)
469  *           S = (Y & 0b10) | (X & 0b10) >> 1
470  *
471  * For an 8x multisampled surface using INTEL_MSAA_LAYOUT_IMS, encode_msaa()
472  * embeds the sample number into bits 1 and 2 of the X coordinate and bit 1 of
473  * the Y coordinate:
474  *
475  *   encode_msaa(8, IMS, X, Y, S) = (X', Y', 0)
476  *     where X' = (X & ~0b1) << 2 | (S & 0b100) | (S & 0b1) << 1 | (X & 0b1)
477  *           Y' = (Y & ~0b1) << 1 | (S & 0b10) | (Y & 0b1)
478  *   decode_msaa(8, IMS, X, Y, 0) = (X', Y', S)
479  *     where X' = (X & ~0b111) >> 2 | (X & 0b1)
480  *           Y' = (Y & ~0b11) >> 1 | (Y & 0b1)
481  *           S = (X & 0b100) | (Y & 0b10) | (X & 0b10) >> 1
482  *
483  * For X tiling, tile() combines together the low-order bits of the X and Y
484  * coordinates in the pattern 0byyyxxxxxxxxx, creating 4k tiles that are 512
485  * bytes wide and 8 rows high:
486  *
487  *   tile(x_tiled, X, Y, S) = A
488  *     where A = tile_num << 12 | offset
489  *           tile_num = (Y' >> 3) * tile_pitch + (X' >> 9)
490  *           offset = (Y' & 0b111) << 9
491  *                    | (X & 0b111111111)
492  *           X' = X * cpp
493  *           Y' = Y + S * qpitch
494  *   detile(x_tiled, A) = (X, Y, S)
495  *     where X = X' / cpp
496  *           Y = Y' % qpitch
497  *           S = Y' / qpitch
498  *           Y' = (tile_num / tile_pitch) << 3
499  *                | (A & 0b111000000000) >> 9
500  *           X' = (tile_num % tile_pitch) << 9
501  *                | (A & 0b111111111)
502  *
503  * (In all tiling formulas, cpp is the number of bytes occupied by a single
504  * sample ("chars per pixel"), tile_pitch is the number of 4k tiles required
505  * to fill the width of the surface, and qpitch is the spacing (in rows)
506  * between array slices).
507  *
508  * For Y tiling, tile() combines together the low-order bits of the X and Y
509  * coordinates in the pattern 0bxxxyyyyyxxxx, creating 4k tiles that are 128
510  * bytes wide and 32 rows high:
511  *
512  *   tile(y_tiled, X, Y, S) = A
513  *     where A = tile_num << 12 | offset
514  *           tile_num = (Y' >> 5) * tile_pitch + (X' >> 7)
515  *           offset = (X' & 0b1110000) << 5
516  *                    | (Y' & 0b11111) << 4
517  *                    | (X' & 0b1111)
518  *           X' = X * cpp
519  *           Y' = Y + S * qpitch
520  *   detile(y_tiled, A) = (X, Y, S)
521  *     where X = X' / cpp
522  *           Y = Y' % qpitch
523  *           S = Y' / qpitch
524  *           Y' = (tile_num / tile_pitch) << 5
525  *                | (A & 0b111110000) >> 4
526  *           X' = (tile_num % tile_pitch) << 7
527  *                | (A & 0b111000000000) >> 5
528  *                | (A & 0b1111)
529  *
530  * For W tiling, tile() combines together the low-order bits of the X and Y
531  * coordinates in the pattern 0bxxxyyyyxyxyx, creating 4k tiles that are 64
532  * bytes wide and 64 rows high (note that W tiling is only used for stencil
533  * buffers, which always have cpp = 1 and S=0):
534  *
535  *   tile(w_tiled, X, Y, S) = A
536  *     where A = tile_num << 12 | offset
537  *           tile_num = (Y' >> 6) * tile_pitch + (X' >> 6)
538  *           offset = (X' & 0b111000) << 6
539  *                    | (Y' & 0b111100) << 3
540  *                    | (X' & 0b100) << 2
541  *                    | (Y' & 0b10) << 2
542  *                    | (X' & 0b10) << 1
543  *                    | (Y' & 0b1) << 1
544  *                    | (X' & 0b1)
545  *           X' = X * cpp = X
546  *           Y' = Y + S * qpitch
547  *   detile(w_tiled, A) = (X, Y, S)
548  *     where X = X' / cpp = X'
549  *           Y = Y' % qpitch = Y'
550  *           S = Y / qpitch = 0
551  *           Y' = (tile_num / tile_pitch) << 6
552  *                | (A & 0b111100000) >> 3
553  *                | (A & 0b1000) >> 2
554  *                | (A & 0b10) >> 1
555  *           X' = (tile_num % tile_pitch) << 6
556  *                | (A & 0b111000000000) >> 6
557  *                | (A & 0b10000) >> 2
558  *                | (A & 0b100) >> 1
559  *                | (A & 0b1)
560  *
561  * Finally, for a non-tiled surface, tile() simply combines together the X and
562  * Y coordinates in the natural way:
563  *
564  *   tile(untiled, X, Y, S) = A
565  *     where A = Y * pitch + X'
566  *           X' = X * cpp
567  *           Y' = Y + S * qpitch
568  *   detile(untiled, A) = (X, Y, S)
569  *     where X = X' / cpp
570  *           Y = Y' % qpitch
571  *           S = Y' / qpitch
572  *           X' = A % pitch
573  *           Y' = A / pitch
574  *
575  * (In these formulas, pitch is the number of bytes occupied by a single row
576  * of samples).
577  */
578 class brw_blorp_blit_program
579 {
580 public:
581    brw_blorp_blit_program(struct brw_context *brw,
582                           const brw_blorp_blit_prog_key *key);
583    ~brw_blorp_blit_program();
584
585    const GLuint *compile(struct brw_context *brw, GLuint *program_size);
586
587    brw_blorp_prog_data prog_data;
588
589 private:
590    void alloc_regs();
591    void alloc_push_const_regs(int base_reg);
592    void compute_frag_coords();
593    void translate_tiling(bool old_tiled_w, bool new_tiled_w);
594    void encode_msaa(unsigned num_samples, intel_msaa_layout layout);
595    void decode_msaa(unsigned num_samples, intel_msaa_layout layout);
596    void kill_if_outside_dst_rect();
597    void translate_dst_to_src();
598    void single_to_blend();
599    void manual_blend(unsigned num_samples);
600    void sample(struct brw_reg dst);
601    void texel_fetch(struct brw_reg dst);
602    void mcs_fetch();
603    void expand_to_32_bits(struct brw_reg src, struct brw_reg dst);
604    void texture_lookup(struct brw_reg dst, GLuint msg_type,
605                        const sampler_message_arg *args, int num_args);
606    void render_target_write();
607
608    /**
609     * Base-2 logarithm of the maximum number of samples that can be blended.
610     */
611    static const unsigned LOG2_MAX_BLEND_SAMPLES = 3;
612
613    void *mem_ctx;
614    struct brw_context *brw;
615    const brw_blorp_blit_prog_key *key;
616    struct brw_compile func;
617
618    /* Thread dispatch header */
619    struct brw_reg R0;
620
621    /* Pixel X/Y coordinates (always in R1). */
622    struct brw_reg R1;
623
624    /* Push constants */
625    struct brw_reg dst_x0;
626    struct brw_reg dst_x1;
627    struct brw_reg dst_y0;
628    struct brw_reg dst_y1;
629    struct {
630       struct brw_reg multiplier;
631       struct brw_reg offset;
632    } x_transform, y_transform;
633
634    /* Data read from texture (4 vec16's per array element) */
635    struct brw_reg texture_data[LOG2_MAX_BLEND_SAMPLES + 1];
636
637    /* Auxiliary storage for the contents of the MCS surface.
638     *
639     * Since the sampler always returns 8 registers worth of data, this is 8
640     * registers wide, even though we only use the first 2 registers of it.
641     */
642    struct brw_reg mcs_data;
643
644    /* X coordinates.  We have two of them so that we can perform coordinate
645     * transformations easily.
646     */
647    struct brw_reg x_coords[2];
648
649    /* Y coordinates.  We have two of them so that we can perform coordinate
650     * transformations easily.
651     */
652    struct brw_reg y_coords[2];
653
654    /* Which element of x_coords and y_coords is currently in use.
655     */
656    int xy_coord_index;
657
658    /* True if, at the point in the program currently being compiled, the
659     * sample index is known to be zero.
660     */
661    bool s_is_zero;
662
663    /* Register storing the sample index when s_is_zero is false. */
664    struct brw_reg sample_index;
665
666    /* Temporaries */
667    struct brw_reg t1;
668    struct brw_reg t2;
669
670    /* MRF used for sampling and render target writes */
671    GLuint base_mrf;
672 };
673
674 brw_blorp_blit_program::brw_blorp_blit_program(
675       struct brw_context *brw,
676       const brw_blorp_blit_prog_key *key)
677    : mem_ctx(ralloc_context(NULL)),
678      brw(brw),
679      key(key)
680 {
681    brw_init_compile(brw, &func, mem_ctx);
682 }
683
684 brw_blorp_blit_program::~brw_blorp_blit_program()
685 {
686    ralloc_free(mem_ctx);
687 }
688
689 const GLuint *
690 brw_blorp_blit_program::compile(struct brw_context *brw,
691                                 GLuint *program_size)
692 {
693    /* Sanity checks */
694    if (key->dst_tiled_w && key->rt_samples > 0) {
695       /* If the destination image is W tiled and multisampled, then the thread
696        * must be dispatched once per sample, not once per pixel.  This is
697        * necessary because after conversion between W and Y tiling, there's no
698        * guarantee that all samples corresponding to a single pixel will still
699        * be together.
700        */
701       assert(key->persample_msaa_dispatch);
702    }
703
704    if (key->blend) {
705       /* We are blending, which means we won't have an opportunity to
706        * translate the tiling and sample count for the texture surface.  So
707        * the surface state for the texture must be configured with the correct
708        * tiling and sample count.
709        */
710       assert(!key->src_tiled_w);
711       assert(key->tex_samples == key->src_samples);
712       assert(key->tex_layout == key->src_layout);
713       assert(key->tex_samples > 0);
714    }
715
716    if (key->persample_msaa_dispatch) {
717       /* It only makes sense to do persample dispatch if the render target is
718        * configured as multisampled.
719        */
720       assert(key->rt_samples > 0);
721    }
722
723    /* Make sure layout is consistent with sample count */
724    assert((key->tex_layout == INTEL_MSAA_LAYOUT_NONE) ==
725           (key->tex_samples == 0));
726    assert((key->rt_layout == INTEL_MSAA_LAYOUT_NONE) ==
727           (key->rt_samples == 0));
728    assert((key->src_layout == INTEL_MSAA_LAYOUT_NONE) ==
729           (key->src_samples == 0));
730    assert((key->dst_layout == INTEL_MSAA_LAYOUT_NONE) ==
731           (key->dst_samples == 0));
732
733    /* Set up prog_data */
734    memset(&prog_data, 0, sizeof(prog_data));
735    prog_data.persample_msaa_dispatch = key->persample_msaa_dispatch;
736
737    brw_set_compression_control(&func, BRW_COMPRESSION_NONE);
738
739    alloc_regs();
740    compute_frag_coords();
741
742    /* Render target and texture hardware don't support W tiling. */
743    const bool rt_tiled_w = false;
744    const bool tex_tiled_w = false;
745
746    /* The address that data will be written to is determined by the
747     * coordinates supplied to the WM thread and the tiling and sample count of
748     * the render target, according to the formula:
749     *
750     * (X, Y, S) = decode_msaa(rt_samples, detile(rt_tiling, offset))
751     *
752     * If the actual tiling and sample count of the destination surface are not
753     * the same as the configuration of the render target, then these
754     * coordinates are wrong and we have to adjust them to compensate for the
755     * difference.
756     */
757    if (rt_tiled_w != key->dst_tiled_w ||
758        key->rt_samples != key->dst_samples ||
759        key->rt_layout != key->dst_layout) {
760       encode_msaa(key->rt_samples, key->rt_layout);
761       /* Now (X, Y, S) = detile(rt_tiling, offset) */
762       translate_tiling(rt_tiled_w, key->dst_tiled_w);
763       /* Now (X, Y, S) = detile(dst_tiling, offset) */
764       decode_msaa(key->dst_samples, key->dst_layout);
765    }
766
767    /* Now (X, Y, S) = decode_msaa(dst_samples, detile(dst_tiling, offset)).
768     *
769     * That is: X, Y and S now contain the true coordinates and sample index of
770     * the data that the WM thread should output.
771     *
772     * If we need to kill pixels that are outside the destination rectangle,
773     * now is the time to do it.
774     */
775
776    if (key->use_kill)
777       kill_if_outside_dst_rect();
778
779    /* Next, apply a translation to obtain coordinates in the source image. */
780    translate_dst_to_src();
781
782    /* If the source image is not multisampled, then we want to fetch sample
783     * number 0, because that's the only sample there is.
784     */
785    if (key->src_samples == 0)
786       s_is_zero = true;
787
788    /* X, Y, and S are now the coordinates of the pixel in the source image
789     * that we want to texture from.  Exception: if we are blending, then S is
790     * irrelevant, because we are going to fetch all samples.
791     */
792    if (key->blend) {
793       if (brw->intel.gen == 6) {
794          /* Gen6 hardware an automatically blend using the SAMPLE message */
795          single_to_blend();
796          sample(texture_data[0]);
797       } else {
798          /* Gen7+ hardware doesn't automaticaly blend. */
799          manual_blend(key->src_samples);
800       }
801    } else {
802       /* We aren't blending, which means we just want to fetch a single sample
803        * from the source surface.  The address that we want to fetch from is
804        * related to the X, Y and S values according to the formula:
805        *
806        * (X, Y, S) = decode_msaa(src_samples, detile(src_tiling, offset)).
807        *
808        * If the actual tiling and sample count of the source surface are not
809        * the same as the configuration of the texture, then we need to adjust
810        * the coordinates to compensate for the difference.
811        */
812       if (tex_tiled_w != key->src_tiled_w ||
813           key->tex_samples != key->src_samples ||
814           key->tex_layout != key->src_layout) {
815          encode_msaa(key->src_samples, key->src_layout);
816          /* Now (X, Y, S) = detile(src_tiling, offset) */
817          translate_tiling(key->src_tiled_w, tex_tiled_w);
818          /* Now (X, Y, S) = detile(tex_tiling, offset) */
819          decode_msaa(key->tex_samples, key->tex_layout);
820       }
821
822       /* Now (X, Y, S) = decode_msaa(tex_samples, detile(tex_tiling, offset)).
823        *
824        * In other words: X, Y, and S now contain values which, when passed to
825        * the texturing unit, will cause data to be read from the correct
826        * memory location.  So we can fetch the texel now.
827        */
828       if (key->tex_layout == INTEL_MSAA_LAYOUT_CMS)
829          mcs_fetch();
830       texel_fetch(texture_data[0]);
831    }
832
833    /* Finally, write the fetched (or blended) value to the render target and
834     * terminate the thread.
835     */
836    render_target_write();
837
838    if (unlikely(INTEL_DEBUG & DEBUG_BLORP)) {
839       printf("Native code for BLORP blit:\n");
840       brw_dump_compile(&func, stdout, 0, func.next_insn_offset);
841       printf("\n");
842    }
843    return brw_get_program(&func, program_size);
844 }
845
846 void
847 brw_blorp_blit_program::alloc_push_const_regs(int base_reg)
848 {
849 #define CONST_LOC(name) offsetof(brw_blorp_wm_push_constants, name)
850 #define ALLOC_REG(name) \
851    this->name = \
852       brw_uw1_reg(BRW_GENERAL_REGISTER_FILE, base_reg, CONST_LOC(name) / 2)
853
854    ALLOC_REG(dst_x0);
855    ALLOC_REG(dst_x1);
856    ALLOC_REG(dst_y0);
857    ALLOC_REG(dst_y1);
858    ALLOC_REG(x_transform.multiplier);
859    ALLOC_REG(x_transform.offset);
860    ALLOC_REG(y_transform.multiplier);
861    ALLOC_REG(y_transform.offset);
862 #undef CONST_LOC
863 #undef ALLOC_REG
864 }
865
866 void
867 brw_blorp_blit_program::alloc_regs()
868 {
869    int reg = 0;
870    this->R0 = retype(brw_vec8_grf(reg++, 0), BRW_REGISTER_TYPE_UW);
871    this->R1 = retype(brw_vec8_grf(reg++, 0), BRW_REGISTER_TYPE_UW);
872    prog_data.first_curbe_grf = reg;
873    alloc_push_const_regs(reg);
874    reg += BRW_BLORP_NUM_PUSH_CONST_REGS;
875    for (unsigned i = 0; i < ARRAY_SIZE(texture_data); ++i) {
876       this->texture_data[i] =
877          retype(vec16(brw_vec8_grf(reg, 0)), key->texture_data_type);
878       reg += 8;
879    }
880    this->mcs_data =
881       retype(brw_vec8_grf(reg, 0), BRW_REGISTER_TYPE_UD); reg += 8;
882    for (int i = 0; i < 2; ++i) {
883       this->x_coords[i]
884          = vec16(retype(brw_vec8_grf(reg++, 0), BRW_REGISTER_TYPE_UW));
885       this->y_coords[i]
886          = vec16(retype(brw_vec8_grf(reg++, 0), BRW_REGISTER_TYPE_UW));
887    }
888    this->xy_coord_index = 0;
889    this->sample_index
890       = vec16(retype(brw_vec8_grf(reg++, 0), BRW_REGISTER_TYPE_UW));
891    this->t1 = vec16(retype(brw_vec8_grf(reg++, 0), BRW_REGISTER_TYPE_UW));
892    this->t2 = vec16(retype(brw_vec8_grf(reg++, 0), BRW_REGISTER_TYPE_UW));
893
894    /* Make sure we didn't run out of registers */
895    assert(reg <= GEN7_MRF_HACK_START);
896
897    int mrf = 2;
898    this->base_mrf = mrf;
899 }
900
901 /* In the code that follows, X and Y can be used to quickly refer to the
902  * active elements of x_coords and y_coords, and Xp and Yp ("X prime" and "Y
903  * prime") to the inactive elements.
904  *
905  * S can be used to quickly refer to sample_index.
906  */
907 #define X x_coords[xy_coord_index]
908 #define Y y_coords[xy_coord_index]
909 #define Xp x_coords[!xy_coord_index]
910 #define Yp y_coords[!xy_coord_index]
911 #define S sample_index
912
913 /* Quickly swap the roles of (X, Y) and (Xp, Yp).  Saves us from having to do
914  * MOVs to transfor (Xp, Yp) to (X, Y) after a coordinate transformation.
915  */
916 #define SWAP_XY_AND_XPYP() xy_coord_index = !xy_coord_index;
917
918 /**
919  * Emit code to compute the X and Y coordinates of the pixels being rendered
920  * by this WM invocation.
921  *
922  * Assuming the render target is set up for Y tiling, these (X, Y) values are
923  * related to the address offset where outputs will be written by the formula:
924  *
925  *   (X, Y, S) = decode_msaa(detile(offset)).
926  *
927  * (See brw_blorp_blit_program).
928  */
929 void
930 brw_blorp_blit_program::compute_frag_coords()
931 {
932    /* R1.2[15:0] = X coordinate of upper left pixel of subspan 0 (pixel 0)
933     * R1.3[15:0] = X coordinate of upper left pixel of subspan 1 (pixel 4)
934     * R1.4[15:0] = X coordinate of upper left pixel of subspan 2 (pixel 8)
935     * R1.5[15:0] = X coordinate of upper left pixel of subspan 3 (pixel 12)
936     *
937     * Pixels within a subspan are laid out in this arrangement:
938     * 0 1
939     * 2 3
940     *
941     * So, to compute the coordinates of each pixel, we need to read every 2nd
942     * 16-bit value (vstride=2) from R1, starting at the 4th 16-bit value
943     * (suboffset=4), and duplicate each value 4 times (hstride=0, width=4).
944     * In other words, the data we want to access is R1.4<2;4,0>UW.
945     *
946     * Then, we need to add the repeating sequence (0, 1, 0, 1, ...) to the
947     * result, since pixels n+1 and n+3 are in the right half of the subspan.
948     */
949    brw_ADD(&func, X, stride(suboffset(R1, 4), 2, 4, 0), brw_imm_v(0x10101010));
950
951    /* Similarly, Y coordinates for subspans come from R1.2[31:16] through
952     * R1.5[31:16], so to get pixel Y coordinates we need to start at the 5th
953     * 16-bit value instead of the 4th (R1.5<2;4,0>UW instead of
954     * R1.4<2;4,0>UW).
955     *
956     * And we need to add the repeating sequence (0, 0, 1, 1, ...), since
957     * pixels n+2 and n+3 are in the bottom half of the subspan.
958     */
959    brw_ADD(&func, Y, stride(suboffset(R1, 5), 2, 4, 0), brw_imm_v(0x11001100));
960
961    if (key->persample_msaa_dispatch) {
962       switch (key->rt_samples) {
963       case 4:
964          /* The WM will be run in MSDISPMODE_PERSAMPLE with num_samples == 4.
965           * Therefore, subspan 0 will represent sample 0, subspan 1 will
966           * represent sample 1, and so on.
967           *
968           * So we need to populate S with the sequence (0, 0, 0, 0, 1, 1, 1,
969           * 1, 2, 2, 2, 2, 3, 3, 3, 3).  The easiest way to do this is to
970           * populate a temporary variable with the sequence (0, 1, 2, 3), and
971           * then copy from it using vstride=1, width=4, hstride=0.
972           */
973          brw_MOV(&func, t1, brw_imm_v(0x3210));
974          brw_MOV(&func, S, stride(t1, 1, 4, 0));
975          break;
976       case 8: {
977          /* The WM will be run in MSDISPMODE_PERSAMPLE with num_samples == 8.
978           * Therefore, subspan 0 will represent sample N (where N is 0 or 4),
979           * subspan 1 will represent sample 1, and so on.  We can find the
980           * value of N by looking at R0.0 bits 7:6 ("Starting Sample Pair
981           * Index") and multiplying by two (since samples are always delivered
982           * in pairs).  That is, we compute 2*((R0.0 & 0xc0) >> 6) == (R0.0 &
983           * 0xc0) >> 5.
984           *
985           * Then we need to add N to the sequence (0, 0, 0, 0, 1, 1, 1, 1, 2,
986           * 2, 2, 2, 3, 3, 3, 3), which we compute by populating a temporary
987           * variable with the sequence (0, 1, 2, 3), and then reading from it
988           * using vstride=1, width=4, hstride=0.
989           */
990          struct brw_reg t1_ud1 = vec1(retype(t1, BRW_REGISTER_TYPE_UD));
991          struct brw_reg r0_ud1 = vec1(retype(R0, BRW_REGISTER_TYPE_UD));
992          brw_AND(&func, t1_ud1, r0_ud1, brw_imm_ud(0xc0));
993          brw_SHR(&func, t1_ud1, t1_ud1, brw_imm_ud(5));
994          brw_MOV(&func, t2, brw_imm_v(0x3210));
995          brw_ADD(&func, S, retype(t1_ud1, BRW_REGISTER_TYPE_UW),
996                  stride(t2, 1, 4, 0));
997          break;
998       }
999       default:
1000          assert(!"Unrecognized sample count in "
1001                 "brw_blorp_blit_program::compute_frag_coords()");
1002          break;
1003       }
1004       s_is_zero = false;
1005    } else {
1006       /* Either the destination surface is single-sampled, or the WM will be
1007        * run in MSDISPMODE_PERPIXEL (which causes a single fragment dispatch
1008        * per pixel).  In either case, it's not meaningful to compute a sample
1009        * value.  Just set it to 0.
1010        */
1011       s_is_zero = true;
1012    }
1013 }
1014
1015 /**
1016  * Emit code to compensate for the difference between Y and W tiling.
1017  *
1018  * This code modifies the X and Y coordinates according to the formula:
1019  *
1020  *   (X', Y', S') = detile(new_tiling, tile(old_tiling, X, Y, S))
1021  *
1022  * (See brw_blorp_blit_program).
1023  *
1024  * It can only translate between W and Y tiling, so new_tiling and old_tiling
1025  * are booleans where true represents W tiling and false represents Y tiling.
1026  */
1027 void
1028 brw_blorp_blit_program::translate_tiling(bool old_tiled_w, bool new_tiled_w)
1029 {
1030    if (old_tiled_w == new_tiled_w)
1031       return;
1032
1033    /* In the code that follows, we can safely assume that S = 0, because W
1034     * tiling formats always use IMS layout.
1035     */
1036    assert(s_is_zero);
1037
1038    if (new_tiled_w) {
1039       /* Given X and Y coordinates that describe an address using Y tiling,
1040        * translate to the X and Y coordinates that describe the same address
1041        * using W tiling.
1042        *
1043        * If we break down the low order bits of X and Y, using a
1044        * single letter to represent each low-order bit:
1045        *
1046        *   X = A << 7 | 0bBCDEFGH
1047        *   Y = J << 5 | 0bKLMNP                                       (1)
1048        *
1049        * Then we can apply the Y tiling formula to see the memory offset being
1050        * addressed:
1051        *
1052        *   offset = (J * tile_pitch + A) << 12 | 0bBCDKLMNPEFGH       (2)
1053        *
1054        * If we apply the W detiling formula to this memory location, that the
1055        * corresponding X' and Y' coordinates are:
1056        *
1057        *   X' = A << 6 | 0bBCDPFH                                     (3)
1058        *   Y' = J << 6 | 0bKLMNEG
1059        *
1060        * Combining (1) and (3), we see that to transform (X, Y) to (X', Y'),
1061        * we need to make the following computation:
1062        *
1063        *   X' = (X & ~0b1011) >> 1 | (Y & 0b1) << 2 | X & 0b1         (4)
1064        *   Y' = (Y & ~0b1) << 1 | (X & 0b1000) >> 2 | (X & 0b10) >> 1
1065        */
1066       brw_AND(&func, t1, X, brw_imm_uw(0xfff4)); /* X & ~0b1011 */
1067       brw_SHR(&func, t1, t1, brw_imm_uw(1)); /* (X & ~0b1011) >> 1 */
1068       brw_AND(&func, t2, Y, brw_imm_uw(1)); /* Y & 0b1 */
1069       brw_SHL(&func, t2, t2, brw_imm_uw(2)); /* (Y & 0b1) << 2 */
1070       brw_OR(&func, t1, t1, t2); /* (X & ~0b1011) >> 1 | (Y & 0b1) << 2 */
1071       brw_AND(&func, t2, X, brw_imm_uw(1)); /* X & 0b1 */
1072       brw_OR(&func, Xp, t1, t2);
1073       brw_AND(&func, t1, Y, brw_imm_uw(0xfffe)); /* Y & ~0b1 */
1074       brw_SHL(&func, t1, t1, brw_imm_uw(1)); /* (Y & ~0b1) << 1 */
1075       brw_AND(&func, t2, X, brw_imm_uw(8)); /* X & 0b1000 */
1076       brw_SHR(&func, t2, t2, brw_imm_uw(2)); /* (X & 0b1000) >> 2 */
1077       brw_OR(&func, t1, t1, t2); /* (Y & ~0b1) << 1 | (X & 0b1000) >> 2 */
1078       brw_AND(&func, t2, X, brw_imm_uw(2)); /* X & 0b10 */
1079       brw_SHR(&func, t2, t2, brw_imm_uw(1)); /* (X & 0b10) >> 1 */
1080       brw_OR(&func, Yp, t1, t2);
1081       SWAP_XY_AND_XPYP();
1082    } else {
1083       /* Applying the same logic as above, but in reverse, we obtain the
1084        * formulas:
1085        *
1086        * X' = (X & ~0b101) << 1 | (Y & 0b10) << 2 | (Y & 0b1) << 1 | X & 0b1
1087        * Y' = (Y & ~0b11) >> 1 | (X & 0b100) >> 2
1088        */
1089       brw_AND(&func, t1, X, brw_imm_uw(0xfffa)); /* X & ~0b101 */
1090       brw_SHL(&func, t1, t1, brw_imm_uw(1)); /* (X & ~0b101) << 1 */
1091       brw_AND(&func, t2, Y, brw_imm_uw(2)); /* Y & 0b10 */
1092       brw_SHL(&func, t2, t2, brw_imm_uw(2)); /* (Y & 0b10) << 2 */
1093       brw_OR(&func, t1, t1, t2); /* (X & ~0b101) << 1 | (Y & 0b10) << 2 */
1094       brw_AND(&func, t2, Y, brw_imm_uw(1)); /* Y & 0b1 */
1095       brw_SHL(&func, t2, t2, brw_imm_uw(1)); /* (Y & 0b1) << 1 */
1096       brw_OR(&func, t1, t1, t2); /* (X & ~0b101) << 1 | (Y & 0b10) << 2
1097                                     | (Y & 0b1) << 1 */
1098       brw_AND(&func, t2, X, brw_imm_uw(1)); /* X & 0b1 */
1099       brw_OR(&func, Xp, t1, t2);
1100       brw_AND(&func, t1, Y, brw_imm_uw(0xfffc)); /* Y & ~0b11 */
1101       brw_SHR(&func, t1, t1, brw_imm_uw(1)); /* (Y & ~0b11) >> 1 */
1102       brw_AND(&func, t2, X, brw_imm_uw(4)); /* X & 0b100 */
1103       brw_SHR(&func, t2, t2, brw_imm_uw(2)); /* (X & 0b100) >> 2 */
1104       brw_OR(&func, Yp, t1, t2);
1105       SWAP_XY_AND_XPYP();
1106    }
1107 }
1108
1109 /**
1110  * Emit code to compensate for the difference between MSAA and non-MSAA
1111  * surfaces.
1112  *
1113  * This code modifies the X and Y coordinates according to the formula:
1114  *
1115  *   (X', Y', S') = encode_msaa(num_samples, IMS, X, Y, S)
1116  *
1117  * (See brw_blorp_blit_program).
1118  */
1119 void
1120 brw_blorp_blit_program::encode_msaa(unsigned num_samples,
1121                                     intel_msaa_layout layout)
1122 {
1123    switch (layout) {
1124    case INTEL_MSAA_LAYOUT_NONE:
1125       /* No translation necessary, and S should already be zero. */
1126       assert(s_is_zero);
1127       break;
1128    case INTEL_MSAA_LAYOUT_CMS:
1129       /* We can't compensate for compressed layout since at this point in the
1130        * program we haven't read from the MCS buffer.
1131        */
1132       assert(!"Bad layout in encode_msaa");
1133       break;
1134    case INTEL_MSAA_LAYOUT_UMS:
1135       /* No translation necessary. */
1136       break;
1137    case INTEL_MSAA_LAYOUT_IMS:
1138       switch (num_samples) {
1139       case 4:
1140          /* encode_msaa(4, IMS, X, Y, S) = (X', Y', 0)
1141           *   where X' = (X & ~0b1) << 1 | (S & 0b1) << 1 | (X & 0b1)
1142           *         Y' = (Y & ~0b1) << 1 | (S & 0b10) | (Y & 0b1)
1143           */
1144          brw_AND(&func, t1, X, brw_imm_uw(0xfffe)); /* X & ~0b1 */
1145          if (!s_is_zero) {
1146             brw_AND(&func, t2, S, brw_imm_uw(1)); /* S & 0b1 */
1147             brw_OR(&func, t1, t1, t2); /* (X & ~0b1) | (S & 0b1) */
1148          }
1149          brw_SHL(&func, t1, t1, brw_imm_uw(1)); /* (X & ~0b1) << 1
1150                                                    | (S & 0b1) << 1 */
1151          brw_AND(&func, t2, X, brw_imm_uw(1)); /* X & 0b1 */
1152          brw_OR(&func, Xp, t1, t2);
1153          brw_AND(&func, t1, Y, brw_imm_uw(0xfffe)); /* Y & ~0b1 */
1154          brw_SHL(&func, t1, t1, brw_imm_uw(1)); /* (Y & ~0b1) << 1 */
1155          if (!s_is_zero) {
1156             brw_AND(&func, t2, S, brw_imm_uw(2)); /* S & 0b10 */
1157             brw_OR(&func, t1, t1, t2); /* (Y & ~0b1) << 1 | (S & 0b10) */
1158          }
1159          brw_AND(&func, t2, Y, brw_imm_uw(1)); /* Y & 0b1 */
1160          brw_OR(&func, Yp, t1, t2);
1161          break;
1162       case 8:
1163          /* encode_msaa(8, IMS, X, Y, S) = (X', Y', 0)
1164           *   where X' = (X & ~0b1) << 2 | (S & 0b100) | (S & 0b1) << 1
1165           *              | (X & 0b1)
1166           *         Y' = (Y & ~0b1) << 1 | (S & 0b10) | (Y & 0b1)
1167           */
1168          brw_AND(&func, t1, X, brw_imm_uw(0xfffe)); /* X & ~0b1 */
1169          brw_SHL(&func, t1, t1, brw_imm_uw(2)); /* (X & ~0b1) << 2 */
1170          if (!s_is_zero) {
1171             brw_AND(&func, t2, S, brw_imm_uw(4)); /* S & 0b100 */
1172             brw_OR(&func, t1, t1, t2); /* (X & ~0b1) << 2 | (S & 0b100) */
1173             brw_AND(&func, t2, S, brw_imm_uw(1)); /* S & 0b1 */
1174             brw_SHL(&func, t2, t2, brw_imm_uw(1)); /* (S & 0b1) << 1 */
1175             brw_OR(&func, t1, t1, t2); /* (X & ~0b1) << 2 | (S & 0b100)
1176                                           | (S & 0b1) << 1 */
1177          }
1178          brw_AND(&func, t2, X, brw_imm_uw(1)); /* X & 0b1 */
1179          brw_OR(&func, Xp, t1, t2);
1180          brw_AND(&func, t1, Y, brw_imm_uw(0xfffe)); /* Y & ~0b1 */
1181          brw_SHL(&func, t1, t1, brw_imm_uw(1)); /* (Y & ~0b1) << 1 */
1182          if (!s_is_zero) {
1183             brw_AND(&func, t2, S, brw_imm_uw(2)); /* S & 0b10 */
1184             brw_OR(&func, t1, t1, t2); /* (Y & ~0b1) << 1 | (S & 0b10) */
1185          }
1186          brw_AND(&func, t2, Y, brw_imm_uw(1)); /* Y & 0b1 */
1187          brw_OR(&func, Yp, t1, t2);
1188          break;
1189       }
1190       SWAP_XY_AND_XPYP();
1191       s_is_zero = true;
1192       break;
1193    }
1194 }
1195
1196 /**
1197  * Emit code to compensate for the difference between MSAA and non-MSAA
1198  * surfaces.
1199  *
1200  * This code modifies the X and Y coordinates according to the formula:
1201  *
1202  *   (X', Y', S) = decode_msaa(num_samples, IMS, X, Y, S)
1203  *
1204  * (See brw_blorp_blit_program).
1205  */
1206 void
1207 brw_blorp_blit_program::decode_msaa(unsigned num_samples,
1208                                     intel_msaa_layout layout)
1209 {
1210    switch (layout) {
1211    case INTEL_MSAA_LAYOUT_NONE:
1212       /* No translation necessary, and S should already be zero. */
1213       assert(s_is_zero);
1214       break;
1215    case INTEL_MSAA_LAYOUT_CMS:
1216       /* We can't compensate for compressed layout since at this point in the
1217        * program we don't have access to the MCS buffer.
1218        */
1219       assert(!"Bad layout in encode_msaa");
1220       break;
1221    case INTEL_MSAA_LAYOUT_UMS:
1222       /* No translation necessary. */
1223       break;
1224    case INTEL_MSAA_LAYOUT_IMS:
1225       assert(s_is_zero);
1226       switch (num_samples) {
1227       case 4:
1228          /* decode_msaa(4, IMS, X, Y, 0) = (X', Y', S)
1229           *   where X' = (X & ~0b11) >> 1 | (X & 0b1)
1230           *         Y' = (Y & ~0b11) >> 1 | (Y & 0b1)
1231           *         S = (Y & 0b10) | (X & 0b10) >> 1
1232           */
1233          brw_AND(&func, t1, X, brw_imm_uw(0xfffc)); /* X & ~0b11 */
1234          brw_SHR(&func, t1, t1, brw_imm_uw(1)); /* (X & ~0b11) >> 1 */
1235          brw_AND(&func, t2, X, brw_imm_uw(1)); /* X & 0b1 */
1236          brw_OR(&func, Xp, t1, t2);
1237          brw_AND(&func, t1, Y, brw_imm_uw(0xfffc)); /* Y & ~0b11 */
1238          brw_SHR(&func, t1, t1, brw_imm_uw(1)); /* (Y & ~0b11) >> 1 */
1239          brw_AND(&func, t2, Y, brw_imm_uw(1)); /* Y & 0b1 */
1240          brw_OR(&func, Yp, t1, t2);
1241          brw_AND(&func, t1, Y, brw_imm_uw(2)); /* Y & 0b10 */
1242          brw_AND(&func, t2, X, brw_imm_uw(2)); /* X & 0b10 */
1243          brw_SHR(&func, t2, t2, brw_imm_uw(1)); /* (X & 0b10) >> 1 */
1244          brw_OR(&func, S, t1, t2);
1245          break;
1246       case 8:
1247          /* decode_msaa(8, IMS, X, Y, 0) = (X', Y', S)
1248           *   where X' = (X & ~0b111) >> 2 | (X & 0b1)
1249           *         Y' = (Y & ~0b11) >> 1 | (Y & 0b1)
1250           *         S = (X & 0b100) | (Y & 0b10) | (X & 0b10) >> 1
1251           */
1252          brw_AND(&func, t1, X, brw_imm_uw(0xfff8)); /* X & ~0b111 */
1253          brw_SHR(&func, t1, t1, brw_imm_uw(2)); /* (X & ~0b111) >> 2 */
1254          brw_AND(&func, t2, X, brw_imm_uw(1)); /* X & 0b1 */
1255          brw_OR(&func, Xp, t1, t2);
1256          brw_AND(&func, t1, Y, brw_imm_uw(0xfffc)); /* Y & ~0b11 */
1257          brw_SHR(&func, t1, t1, brw_imm_uw(1)); /* (Y & ~0b11) >> 1 */
1258          brw_AND(&func, t2, Y, brw_imm_uw(1)); /* Y & 0b1 */
1259          brw_OR(&func, Yp, t1, t2);
1260          brw_AND(&func, t1, X, brw_imm_uw(4)); /* X & 0b100 */
1261          brw_AND(&func, t2, Y, brw_imm_uw(2)); /* Y & 0b10 */
1262          brw_OR(&func, t1, t1, t2); /* (X & 0b100) | (Y & 0b10) */
1263          brw_AND(&func, t2, X, brw_imm_uw(2)); /* X & 0b10 */
1264          brw_SHR(&func, t2, t2, brw_imm_uw(1)); /* (X & 0b10) >> 1 */
1265          brw_OR(&func, S, t1, t2);
1266          break;
1267       }
1268       s_is_zero = false;
1269       SWAP_XY_AND_XPYP();
1270       break;
1271    }
1272 }
1273
1274 /**
1275  * Emit code that kills pixels whose X and Y coordinates are outside the
1276  * boundary of the rectangle defined by the push constants (dst_x0, dst_y0,
1277  * dst_x1, dst_y1).
1278  */
1279 void
1280 brw_blorp_blit_program::kill_if_outside_dst_rect()
1281 {
1282    struct brw_reg f0 = brw_flag_reg(0, 0);
1283    struct brw_reg g1 = retype(brw_vec1_grf(1, 7), BRW_REGISTER_TYPE_UW);
1284    struct brw_reg null16 = vec16(retype(brw_null_reg(), BRW_REGISTER_TYPE_UW));
1285
1286    brw_CMP(&func, null16, BRW_CONDITIONAL_GE, X, dst_x0);
1287    brw_CMP(&func, null16, BRW_CONDITIONAL_GE, Y, dst_y0);
1288    brw_CMP(&func, null16, BRW_CONDITIONAL_L, X, dst_x1);
1289    brw_CMP(&func, null16, BRW_CONDITIONAL_L, Y, dst_y1);
1290
1291    brw_set_predicate_control(&func, BRW_PREDICATE_NONE);
1292    brw_push_insn_state(&func);
1293    brw_set_mask_control(&func, BRW_MASK_DISABLE);
1294    brw_AND(&func, g1, f0, g1);
1295    brw_pop_insn_state(&func);
1296 }
1297
1298 /**
1299  * Emit code to translate from destination (X, Y) coordinates to source (X, Y)
1300  * coordinates.
1301  */
1302 void
1303 brw_blorp_blit_program::translate_dst_to_src()
1304 {
1305    brw_MUL(&func, Xp, X, x_transform.multiplier);
1306    brw_MUL(&func, Yp, Y, y_transform.multiplier);
1307    brw_ADD(&func, Xp, Xp, x_transform.offset);
1308    brw_ADD(&func, Yp, Yp, y_transform.offset);
1309    SWAP_XY_AND_XPYP();
1310 }
1311
1312 /**
1313  * Emit code to transform the X and Y coordinates as needed for blending
1314  * together the different samples in an MSAA texture.
1315  */
1316 void
1317 brw_blorp_blit_program::single_to_blend()
1318 {
1319    /* When looking up samples in an MSAA texture using the SAMPLE message,
1320     * Gen6 requires the texture coordinates to be odd integers (so that they
1321     * correspond to the center of a 2x2 block representing the four samples
1322     * that maxe up a pixel).  So we need to multiply our X and Y coordinates
1323     * each by 2 and then add 1.
1324     */
1325    brw_SHL(&func, t1, X, brw_imm_w(1));
1326    brw_SHL(&func, t2, Y, brw_imm_w(1));
1327    brw_ADD(&func, Xp, t1, brw_imm_w(1));
1328    brw_ADD(&func, Yp, t2, brw_imm_w(1));
1329    SWAP_XY_AND_XPYP();
1330 }
1331
1332
1333 /**
1334  * Count the number of trailing 1 bits in the given value.  For example:
1335  *
1336  * count_trailing_one_bits(0) == 0
1337  * count_trailing_one_bits(7) == 3
1338  * count_trailing_one_bits(11) == 2
1339  */
1340 inline int count_trailing_one_bits(unsigned value)
1341 {
1342 #if defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 304) /* gcc 3.4 or later */
1343    return __builtin_ctz(~value);
1344 #else
1345    return _mesa_bitcount(value & ~(value + 1));
1346 #endif
1347 }
1348
1349
1350 void
1351 brw_blorp_blit_program::manual_blend(unsigned num_samples)
1352 {
1353    if (key->tex_layout == INTEL_MSAA_LAYOUT_CMS)
1354       mcs_fetch();
1355
1356    /* We add together samples using a binary tree structure, e.g. for 4x MSAA:
1357     *
1358     *   result = ((sample[0] + sample[1]) + (sample[2] + sample[3])) / 4
1359     *
1360     * This ensures that when all samples have the same value, no numerical
1361     * precision is lost, since each addition operation always adds two equal
1362     * values, and summing two equal floating point values does not lose
1363     * precision.
1364     *
1365     * We perform this computation by treating the texture_data array as a
1366     * stack and performing the following operations:
1367     *
1368     * - push sample 0 onto stack
1369     * - push sample 1 onto stack
1370     * - add top two stack entries
1371     * - push sample 2 onto stack
1372     * - push sample 3 onto stack
1373     * - add top two stack entries
1374     * - add top two stack entries
1375     * - divide top stack entry by 4
1376     *
1377     * Note that after pushing sample i onto the stack, the number of add
1378     * operations we do is equal to the number of trailing 1 bits in i.  This
1379     * works provided the total number of samples is a power of two, which it
1380     * always is for i965.
1381     *
1382     * For integer formats, we replace the add operations with average
1383     * operations and skip the final division.
1384     */
1385    typedef struct brw_instruction *(*brw_op2_ptr)(struct brw_compile *,
1386                                                   struct brw_reg,
1387                                                   struct brw_reg,
1388                                                   struct brw_reg);
1389    brw_op2_ptr combine_op =
1390       key->texture_data_type == BRW_REGISTER_TYPE_F ? brw_ADD : brw_AVG;
1391    unsigned stack_depth = 0;
1392    for (unsigned i = 0; i < num_samples; ++i) {
1393       assert(stack_depth == _mesa_bitcount(i)); /* Loop invariant */
1394
1395       /* Push sample i onto the stack */
1396       assert(stack_depth < ARRAY_SIZE(texture_data));
1397       if (i == 0) {
1398          s_is_zero = true;
1399       } else {
1400          s_is_zero = false;
1401          brw_MOV(&func, S, brw_imm_uw(i));
1402       }
1403       texel_fetch(texture_data[stack_depth++]);
1404
1405       if (i == 0 && key->tex_layout == INTEL_MSAA_LAYOUT_CMS) {
1406          /* The Ivy Bridge PRM, Vol4 Part1 p27 (Multisample Control Surface)
1407           * suggests an optimization:
1408           *
1409           *     "A simple optimization with probable large return in
1410           *     performance is to compare the MCS value to zero (indicating
1411           *     all samples are on sample slice 0), and sample only from
1412           *     sample slice 0 using ld2dss if MCS is zero."
1413           *
1414           * Note that in the case where the MCS value is zero, sampling from
1415           * sample slice 0 using ld2dss and sampling from sample 0 using
1416           * ld2dms are equivalent (since all samples are on sample slice 0).
1417           * Since we have already sampled from sample 0, all we need to do is
1418           * skip the remaining fetches and averaging if MCS is zero.
1419           */
1420          brw_CMP(&func, vec16(brw_null_reg()), BRW_CONDITIONAL_NZ,
1421                  mcs_data, brw_imm_ud(0));
1422          brw_IF(&func, BRW_EXECUTE_16);
1423       }
1424
1425       /* Do count_trailing_one_bits(i) times */
1426       for (int j = count_trailing_one_bits(i); j-- > 0; ) {
1427          assert(stack_depth >= 2);
1428          --stack_depth;
1429
1430          /* TODO: should use a smaller loop bound for non_RGBA formats */
1431          for (int k = 0; k < 4; ++k) {
1432             combine_op(&func, offset(texture_data[stack_depth - 1], 2*k),
1433                        offset(vec8(texture_data[stack_depth - 1]), 2*k),
1434                        offset(vec8(texture_data[stack_depth]), 2*k));
1435          }
1436       }
1437    }
1438
1439    /* We should have just 1 sample on the stack now. */
1440    assert(stack_depth == 1);
1441
1442    if (key->texture_data_type == BRW_REGISTER_TYPE_F) {
1443       /* Scale the result down by a factor of num_samples */
1444       /* TODO: should use a smaller loop bound for non-RGBA formats */
1445       for (int j = 0; j < 4; ++j) {
1446          brw_MUL(&func, offset(texture_data[0], 2*j),
1447                  offset(vec8(texture_data[0]), 2*j),
1448                  brw_imm_f(1.0/num_samples));
1449       }
1450    }
1451
1452    if (key->tex_layout == INTEL_MSAA_LAYOUT_CMS)
1453       brw_ENDIF(&func);
1454 }
1455
1456 /**
1457  * Emit code to look up a value in the texture using the SAMPLE message (which
1458  * does blending of MSAA surfaces).
1459  */
1460 void
1461 brw_blorp_blit_program::sample(struct brw_reg dst)
1462 {
1463    static const sampler_message_arg args[2] = {
1464       SAMPLER_MESSAGE_ARG_U_FLOAT,
1465       SAMPLER_MESSAGE_ARG_V_FLOAT
1466    };
1467
1468    texture_lookup(dst, GEN5_SAMPLER_MESSAGE_SAMPLE, args, ARRAY_SIZE(args));
1469 }
1470
1471 /**
1472  * Emit code to look up a value in the texture using the SAMPLE_LD message
1473  * (which does a simple texel fetch).
1474  */
1475 void
1476 brw_blorp_blit_program::texel_fetch(struct brw_reg dst)
1477 {
1478    static const sampler_message_arg gen6_args[5] = {
1479       SAMPLER_MESSAGE_ARG_U_INT,
1480       SAMPLER_MESSAGE_ARG_V_INT,
1481       SAMPLER_MESSAGE_ARG_ZERO_INT, /* R */
1482       SAMPLER_MESSAGE_ARG_ZERO_INT, /* LOD */
1483       SAMPLER_MESSAGE_ARG_SI_INT
1484    };
1485    static const sampler_message_arg gen7_ld_args[3] = {
1486       SAMPLER_MESSAGE_ARG_U_INT,
1487       SAMPLER_MESSAGE_ARG_ZERO_INT, /* LOD */
1488       SAMPLER_MESSAGE_ARG_V_INT
1489    };
1490    static const sampler_message_arg gen7_ld2dss_args[3] = {
1491       SAMPLER_MESSAGE_ARG_SI_INT,
1492       SAMPLER_MESSAGE_ARG_U_INT,
1493       SAMPLER_MESSAGE_ARG_V_INT
1494    };
1495    static const sampler_message_arg gen7_ld2dms_args[4] = {
1496       SAMPLER_MESSAGE_ARG_SI_INT,
1497       SAMPLER_MESSAGE_ARG_MCS_INT,
1498       SAMPLER_MESSAGE_ARG_U_INT,
1499       SAMPLER_MESSAGE_ARG_V_INT
1500    };
1501
1502    switch (brw->intel.gen) {
1503    case 6:
1504       texture_lookup(dst, GEN5_SAMPLER_MESSAGE_SAMPLE_LD, gen6_args,
1505                      s_is_zero ? 2 : 5);
1506       break;
1507    case 7:
1508       switch (key->tex_layout) {
1509       case INTEL_MSAA_LAYOUT_IMS:
1510          /* From the Ivy Bridge PRM, Vol4 Part1 p72 (Multisampled Surface Storage
1511           * Format):
1512           *
1513           *     If this field is MSFMT_DEPTH_STENCIL
1514           *     [a.k.a. INTEL_MSAA_LAYOUT_IMS], the only sampling engine
1515           *     messages allowed are "ld2dms", "resinfo", and "sampleinfo".
1516           *
1517           * So fall through to emit the same message as we use for
1518           * INTEL_MSAA_LAYOUT_CMS.
1519           */
1520       case INTEL_MSAA_LAYOUT_CMS:
1521          texture_lookup(dst, GEN7_SAMPLER_MESSAGE_SAMPLE_LD2DMS,
1522                         gen7_ld2dms_args, ARRAY_SIZE(gen7_ld2dms_args));
1523          break;
1524       case INTEL_MSAA_LAYOUT_UMS:
1525          texture_lookup(dst, GEN7_SAMPLER_MESSAGE_SAMPLE_LD2DSS,
1526                         gen7_ld2dss_args, ARRAY_SIZE(gen7_ld2dss_args));
1527          break;
1528       case INTEL_MSAA_LAYOUT_NONE:
1529          assert(s_is_zero);
1530          texture_lookup(dst, GEN5_SAMPLER_MESSAGE_SAMPLE_LD, gen7_ld_args,
1531                         ARRAY_SIZE(gen7_ld_args));
1532          break;
1533       }
1534       break;
1535    default:
1536       assert(!"Should not get here.");
1537       break;
1538    };
1539 }
1540
1541 void
1542 brw_blorp_blit_program::mcs_fetch()
1543 {
1544    static const sampler_message_arg gen7_ld_mcs_args[2] = {
1545       SAMPLER_MESSAGE_ARG_U_INT,
1546       SAMPLER_MESSAGE_ARG_V_INT
1547    };
1548    texture_lookup(vec16(mcs_data), GEN7_SAMPLER_MESSAGE_SAMPLE_LD_MCS,
1549                   gen7_ld_mcs_args, ARRAY_SIZE(gen7_ld_mcs_args));
1550 }
1551
1552 void
1553 brw_blorp_blit_program::expand_to_32_bits(struct brw_reg src,
1554                                           struct brw_reg dst)
1555 {
1556    brw_MOV(&func, vec8(dst), vec8(src));
1557    brw_set_compression_control(&func, BRW_COMPRESSION_2NDHALF);
1558    brw_MOV(&func, offset(vec8(dst), 1), suboffset(vec8(src), 8));
1559    brw_set_compression_control(&func, BRW_COMPRESSION_NONE);
1560 }
1561
1562 void
1563 brw_blorp_blit_program::texture_lookup(struct brw_reg dst,
1564                                        GLuint msg_type,
1565                                        const sampler_message_arg *args,
1566                                        int num_args)
1567 {
1568    struct brw_reg mrf =
1569       retype(vec16(brw_message_reg(base_mrf)), BRW_REGISTER_TYPE_UD);
1570    for (int arg = 0; arg < num_args; ++arg) {
1571       switch (args[arg]) {
1572       case SAMPLER_MESSAGE_ARG_U_FLOAT:
1573          expand_to_32_bits(X, retype(mrf, BRW_REGISTER_TYPE_F));
1574          break;
1575       case SAMPLER_MESSAGE_ARG_V_FLOAT:
1576          expand_to_32_bits(Y, retype(mrf, BRW_REGISTER_TYPE_F));
1577          break;
1578       case SAMPLER_MESSAGE_ARG_U_INT:
1579          expand_to_32_bits(X, mrf);
1580          break;
1581       case SAMPLER_MESSAGE_ARG_V_INT:
1582          expand_to_32_bits(Y, mrf);
1583          break;
1584       case SAMPLER_MESSAGE_ARG_SI_INT:
1585          /* Note: on Gen7, this code may be reached with s_is_zero==true
1586           * because in Gen7's ld2dss message, the sample index is the first
1587           * argument.  When this happens, we need to move a 0 into the
1588           * appropriate message register.
1589           */
1590          if (s_is_zero)
1591             brw_MOV(&func, mrf, brw_imm_ud(0));
1592          else
1593             expand_to_32_bits(S, mrf);
1594          break;
1595       case SAMPLER_MESSAGE_ARG_MCS_INT:
1596          switch (key->tex_layout) {
1597          case INTEL_MSAA_LAYOUT_CMS:
1598             brw_MOV(&func, mrf, mcs_data);
1599             break;
1600          case INTEL_MSAA_LAYOUT_IMS:
1601             /* When sampling from an IMS surface, MCS data is not relevant,
1602              * and the hardware ignores it.  So don't bother populating it.
1603              */
1604             break;
1605          default:
1606             /* We shouldn't be trying to send MCS data with any other
1607              * layouts.
1608              */
1609             assert (!"Unsupported layout for MCS data");
1610             break;
1611          }
1612          break;
1613       case SAMPLER_MESSAGE_ARG_ZERO_INT:
1614          brw_MOV(&func, mrf, brw_imm_ud(0));
1615          break;
1616       }
1617       mrf.nr += 2;
1618    }
1619
1620    brw_SAMPLE(&func,
1621               retype(dst, BRW_REGISTER_TYPE_UW) /* dest */,
1622               base_mrf /* msg_reg_nr */,
1623               brw_message_reg(base_mrf) /* src0 */,
1624               BRW_BLORP_TEXTURE_BINDING_TABLE_INDEX,
1625               0 /* sampler */,
1626               msg_type,
1627               8 /* response_length.  TODO: should be smaller for non-RGBA formats? */,
1628               mrf.nr - base_mrf /* msg_length */,
1629               0 /* header_present */,
1630               BRW_SAMPLER_SIMD_MODE_SIMD16,
1631               BRW_SAMPLER_RETURN_FORMAT_FLOAT32);
1632 }
1633
1634 #undef X
1635 #undef Y
1636 #undef U
1637 #undef V
1638 #undef S
1639 #undef SWAP_XY_AND_XPYP
1640
1641 void
1642 brw_blorp_blit_program::render_target_write()
1643 {
1644    struct brw_reg mrf_rt_write =
1645       retype(vec16(brw_message_reg(base_mrf)), key->texture_data_type);
1646    int mrf_offset = 0;
1647
1648    /* If we may have killed pixels, then we need to send R0 and R1 in a header
1649     * so that the render target knows which pixels we killed.
1650     */
1651    bool use_header = key->use_kill;
1652    if (use_header) {
1653       /* Copy R0/1 to MRF */
1654       brw_MOV(&func, retype(mrf_rt_write, BRW_REGISTER_TYPE_UD),
1655               retype(R0, BRW_REGISTER_TYPE_UD));
1656       mrf_offset += 2;
1657    }
1658
1659    /* Copy texture data to MRFs */
1660    for (int i = 0; i < 4; ++i) {
1661       /* E.g. mov(16) m2.0<1>:f r2.0<8;8,1>:f { Align1, H1 } */
1662       brw_MOV(&func, offset(mrf_rt_write, mrf_offset),
1663               offset(vec8(texture_data[0]), 2*i));
1664       mrf_offset += 2;
1665    }
1666
1667    /* Now write to the render target and terminate the thread */
1668    brw_fb_WRITE(&func,
1669                 16 /* dispatch_width */,
1670                 base_mrf /* msg_reg_nr */,
1671                 mrf_rt_write /* src0 */,
1672                 BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD16_SINGLE_SOURCE,
1673                 BRW_BLORP_RENDERBUFFER_BINDING_TABLE_INDEX,
1674                 mrf_offset /* msg_length.  TODO: Should be smaller for non-RGBA formats. */,
1675                 0 /* response_length */,
1676                 true /* eot */,
1677                 use_header);
1678 }
1679
1680
1681 void
1682 brw_blorp_coord_transform_params::setup(GLuint src0, GLuint dst0, GLuint dst1,
1683                                         bool mirror)
1684 {
1685    if (!mirror) {
1686       /* When not mirroring a coordinate (say, X), we need:
1687        *   x' - src_x0 = x - dst_x0
1688        * Therefore:
1689        *   x' = 1*x + (src_x0 - dst_x0)
1690        */
1691       multiplier = 1;
1692       offset = src0 - dst0;
1693    } else {
1694       /* When mirroring X we need:
1695        *   x' - src_x0 = dst_x1 - x - 1
1696        * Therefore:
1697        *   x' = -1*x + (src_x0 + dst_x1 - 1)
1698        */
1699       multiplier = -1;
1700       offset = src0 + dst1 - 1;
1701    }
1702 }
1703
1704
1705 /**
1706  * Determine which MSAA layout the GPU pipeline should be configured for,
1707  * based on the chip generation, the number of samples, and the true layout of
1708  * the image in memory.
1709  */
1710 inline intel_msaa_layout
1711 compute_msaa_layout_for_pipeline(struct brw_context *brw, unsigned num_samples,
1712                                  intel_msaa_layout true_layout)
1713 {
1714    if (num_samples <= 1) {
1715       /* When configuring the GPU for non-MSAA, we can still accommodate IMS
1716        * format buffers, by transforming coordinates appropriately.
1717        */
1718       assert(true_layout == INTEL_MSAA_LAYOUT_NONE ||
1719              true_layout == INTEL_MSAA_LAYOUT_IMS);
1720       return INTEL_MSAA_LAYOUT_NONE;
1721    } else {
1722       assert(true_layout != INTEL_MSAA_LAYOUT_NONE);
1723    }
1724
1725    /* Prior to Gen7, all MSAA surfaces use IMS layout. */
1726    if (brw->intel.gen == 6) {
1727       assert(true_layout == INTEL_MSAA_LAYOUT_IMS);
1728    }
1729
1730    return true_layout;
1731 }
1732
1733
1734 brw_blorp_blit_params::brw_blorp_blit_params(struct brw_context *brw,
1735                                              struct intel_mipmap_tree *src_mt,
1736                                              unsigned src_level, unsigned src_layer,
1737                                              struct intel_mipmap_tree *dst_mt,
1738                                              unsigned dst_level, unsigned dst_layer,
1739                                              GLuint src_x0, GLuint src_y0,
1740                                              GLuint dst_x0, GLuint dst_y0,
1741                                              GLuint dst_x1, GLuint dst_y1,
1742                                              bool mirror_x, bool mirror_y)
1743 {
1744    src.set(brw, src_mt, src_level, src_layer);
1745    dst.set(brw, dst_mt, dst_level, dst_layer);
1746
1747    src.brw_surfaceformat = dst.brw_surfaceformat;
1748
1749    use_wm_prog = true;
1750    memset(&wm_prog_key, 0, sizeof(wm_prog_key));
1751
1752    /* texture_data_type indicates the register type that should be used to
1753     * manipulate texture data.
1754     */
1755    switch (_mesa_get_format_datatype(src_mt->format)) {
1756    case GL_UNSIGNED_NORMALIZED:
1757    case GL_SIGNED_NORMALIZED:
1758    case GL_FLOAT:
1759       wm_prog_key.texture_data_type = BRW_REGISTER_TYPE_F;
1760       break;
1761    case GL_UNSIGNED_INT:
1762       if (src_mt->format == MESA_FORMAT_S8) {
1763          /* We process stencil as though it's an unsigned normalized color */
1764          wm_prog_key.texture_data_type = BRW_REGISTER_TYPE_F;
1765       } else {
1766          wm_prog_key.texture_data_type = BRW_REGISTER_TYPE_UD;
1767       }
1768       break;
1769    case GL_INT:
1770       wm_prog_key.texture_data_type = BRW_REGISTER_TYPE_D;
1771       break;
1772    default:
1773       assert(!"Unrecognized blorp format");
1774       break;
1775    }
1776
1777    if (brw->intel.gen > 6) {
1778       /* Gen7's rendering hardware only supports the IMS layout for depth and
1779        * stencil render targets.  Blorp always maps its destination surface as
1780        * a color render target (even if it's actually a depth or stencil
1781        * buffer).  So if the destination is IMS, we'll have to map it as a
1782        * single-sampled texture and interleave the samples ourselves.
1783        */
1784       if (dst_mt->msaa_layout == INTEL_MSAA_LAYOUT_IMS)
1785          dst.num_samples = 0;
1786    }
1787
1788    if (dst.map_stencil_as_y_tiled && dst.num_samples > 1) {
1789       /* If the destination surface is a W-tiled multisampled stencil buffer
1790        * that we're mapping as Y tiled, then we need to arrange for the WM
1791        * program to run once per sample rather than once per pixel, because
1792        * the memory layout of related samples doesn't match between W and Y
1793        * tiling.
1794        */
1795       wm_prog_key.persample_msaa_dispatch = true;
1796    }
1797
1798    if (src.num_samples > 0 && dst.num_samples > 1) {
1799       /* We are blitting from a multisample buffer to a multisample buffer, so
1800        * we must preserve samples within a pixel.  This means we have to
1801        * arrange for the WM program to run once per sample rather than once
1802        * per pixel.
1803        */
1804       wm_prog_key.persample_msaa_dispatch = true;
1805    }
1806
1807    /* The render path must be configured to use the same number of samples as
1808     * the destination buffer.
1809     */
1810    num_samples = dst.num_samples;
1811
1812    GLenum base_format = _mesa_get_format_base_format(src_mt->format);
1813    if (base_format != GL_DEPTH_COMPONENT && /* TODO: what about depth/stencil? */
1814        base_format != GL_STENCIL_INDEX &&
1815        src_mt->num_samples > 1 && dst_mt->num_samples <= 1) {
1816       /* We are downsampling a color buffer, so blend. */
1817       wm_prog_key.blend = true;
1818    }
1819
1820    /* src_samples and dst_samples are the true sample counts */
1821    wm_prog_key.src_samples = src_mt->num_samples;
1822    wm_prog_key.dst_samples = dst_mt->num_samples;
1823
1824    /* tex_samples and rt_samples are the sample counts that are set up in
1825     * SURFACE_STATE.
1826     */
1827    wm_prog_key.tex_samples = src.num_samples;
1828    wm_prog_key.rt_samples  = dst.num_samples;
1829
1830    /* tex_layout and rt_layout indicate the MSAA layout the GPU pipeline will
1831     * use to access the source and destination surfaces.
1832     */
1833    wm_prog_key.tex_layout =
1834       compute_msaa_layout_for_pipeline(brw, src.num_samples, src.msaa_layout);
1835    wm_prog_key.rt_layout =
1836       compute_msaa_layout_for_pipeline(brw, dst.num_samples, dst.msaa_layout);
1837
1838    /* src_layout and dst_layout indicate the true MSAA layout used by src and
1839     * dst.
1840     */
1841    wm_prog_key.src_layout = src_mt->msaa_layout;
1842    wm_prog_key.dst_layout = dst_mt->msaa_layout;
1843
1844    wm_prog_key.src_tiled_w = src.map_stencil_as_y_tiled;
1845    wm_prog_key.dst_tiled_w = dst.map_stencil_as_y_tiled;
1846    x0 = wm_push_consts.dst_x0 = dst_x0;
1847    y0 = wm_push_consts.dst_y0 = dst_y0;
1848    x1 = wm_push_consts.dst_x1 = dst_x1;
1849    y1 = wm_push_consts.dst_y1 = dst_y1;
1850    wm_push_consts.x_transform.setup(src_x0, dst_x0, dst_x1, mirror_x);
1851    wm_push_consts.y_transform.setup(src_y0, dst_y0, dst_y1, mirror_y);
1852
1853    if (dst.num_samples <= 1 && dst_mt->num_samples > 1) {
1854       /* We must expand the rectangle we send through the rendering pipeline,
1855        * to account for the fact that we are mapping the destination region as
1856        * single-sampled when it is in fact multisampled.  We must also align
1857        * it to a multiple of the multisampling pattern, because the
1858        * differences between multisampled and single-sampled surface formats
1859        * will mean that pixels are scrambled within the multisampling pattern.
1860        * TODO: what if this makes the coordinates too large?
1861        *
1862        * Note: this only works if the destination surface uses the IMS layout.
1863        * If it's UMS, then we have no choice but to set up the rendering
1864        * pipeline as multisampled.
1865        */
1866       assert(dst_mt->msaa_layout == INTEL_MSAA_LAYOUT_IMS);
1867       switch (dst_mt->num_samples) {
1868       case 4:
1869          x0 = ROUND_DOWN_TO(x0 * 2, 4);
1870          y0 = ROUND_DOWN_TO(y0 * 2, 4);
1871          x1 = ALIGN(x1 * 2, 4);
1872          y1 = ALIGN(y1 * 2, 4);
1873          break;
1874       case 8:
1875          x0 = ROUND_DOWN_TO(x0 * 4, 8);
1876          y0 = ROUND_DOWN_TO(y0 * 2, 4);
1877          x1 = ALIGN(x1 * 4, 8);
1878          y1 = ALIGN(y1 * 2, 4);
1879          break;
1880       default:
1881          assert(!"Unrecognized sample count in brw_blorp_blit_params ctor");
1882          break;
1883       }
1884       wm_prog_key.use_kill = true;
1885    }
1886
1887    if (dst.map_stencil_as_y_tiled) {
1888       /* We must modify the rectangle we send through the rendering pipeline
1889        * (and the size and x/y offset of the destination surface), to account
1890        * for the fact that we are mapping it as Y-tiled when it is in fact
1891        * W-tiled.
1892        *
1893        * Both Y tiling and W tiling can be understood as organizations of
1894        * 32-byte sub-tiles; within each 32-byte sub-tile, the layout of pixels
1895        * is different, but the layout of the 32-byte sub-tiles within the 4k
1896        * tile is the same (8 sub-tiles across by 16 sub-tiles down, in
1897        * column-major order).  In Y tiling, the sub-tiles are 16 bytes wide
1898        * and 2 rows high; in W tiling, they are 8 bytes wide and 4 rows high.
1899        *
1900        * Therefore, to account for the layout differences within the 32-byte
1901        * sub-tiles, we must expand the rectangle so the X coordinates of its
1902        * edges are multiples of 8 (the W sub-tile width), and its Y
1903        * coordinates of its edges are multiples of 4 (the W sub-tile height).
1904        * Then we need to scale the X and Y coordinates of the rectangle to
1905        * account for the differences in aspect ratio between the Y and W
1906        * sub-tiles.  We need to modify the layer width and height similarly.
1907        *
1908        * A correction needs to be applied when MSAA is in use: since
1909        * INTEL_MSAA_LAYOUT_IMS uses an interleaving pattern whose height is 4,
1910        * we need to align the Y coordinates to multiples of 8, so that when
1911        * they are divided by two they are still multiples of 4.
1912        *
1913        * Note: Since the x/y offset of the surface will be applied using the
1914        * SURFACE_STATE command packet, it will be invisible to the swizzling
1915        * code in the shader; therefore it needs to be in a multiple of the
1916        * 32-byte sub-tile size.  Fortunately it is, since the sub-tile is 8
1917        * pixels wide and 4 pixels high (when viewed as a W-tiled stencil
1918        * buffer), and the miplevel alignment used for stencil buffers is 8
1919        * pixels horizontally and either 4 or 8 pixels vertically (see
1920        * intel_horizontal_texture_alignment_unit() and
1921        * intel_vertical_texture_alignment_unit()).
1922        *
1923        * Note: Also, since the SURFACE_STATE command packet can only apply
1924        * offsets that are multiples of 4 pixels horizontally and 2 pixels
1925        * vertically, it is important that the offsets will be multiples of
1926        * these sizes after they are converted into Y-tiled coordinates.
1927        * Fortunately they will be, since we know from above that the offsets
1928        * are a multiple of the 32-byte sub-tile size, and in Y-tiled
1929        * coordinates the sub-tile is 16 pixels wide and 2 pixels high.
1930        *
1931        * TODO: what if this makes the coordinates (or the texture size) too
1932        * large?
1933        */
1934       const unsigned x_align = 8, y_align = dst.num_samples != 0 ? 8 : 4;
1935       x0 = ROUND_DOWN_TO(x0, x_align) * 2;
1936       y0 = ROUND_DOWN_TO(y0, y_align) / 2;
1937       x1 = ALIGN(x1, x_align) * 2;
1938       y1 = ALIGN(y1, y_align) / 2;
1939       dst.width = ALIGN(dst.width, x_align) * 2;
1940       dst.height = ALIGN(dst.height, y_align) / 2;
1941       dst.x_offset *= 2;
1942       dst.y_offset /= 2;
1943       wm_prog_key.use_kill = true;
1944    }
1945
1946    if (src.map_stencil_as_y_tiled) {
1947       /* We must modify the size and x/y offset of the source surface to
1948        * account for the fact that we are mapping it as Y-tiled when it is in
1949        * fact W tiled.
1950        *
1951        * See the comments above concerning x/y offset alignment for the
1952        * destination surface.
1953        *
1954        * TODO: what if this makes the texture size too large?
1955        */
1956       const unsigned x_align = 8, y_align = src.num_samples != 0 ? 8 : 4;
1957       src.width = ALIGN(src.width, x_align) * 2;
1958       src.height = ALIGN(src.height, y_align) / 2;
1959       src.x_offset *= 2;
1960       src.y_offset /= 2;
1961    }
1962 }
1963
1964 uint32_t
1965 brw_blorp_blit_params::get_wm_prog(struct brw_context *brw,
1966                                    brw_blorp_prog_data **prog_data) const
1967 {
1968    uint32_t prog_offset;
1969    if (!brw_search_cache(&brw->cache, BRW_BLORP_BLIT_PROG,
1970                          &this->wm_prog_key, sizeof(this->wm_prog_key),
1971                          &prog_offset, prog_data)) {
1972       brw_blorp_blit_program prog(brw, &this->wm_prog_key);
1973       GLuint program_size;
1974       const GLuint *program = prog.compile(brw, &program_size);
1975       brw_upload_cache(&brw->cache, BRW_BLORP_BLIT_PROG,
1976                        &this->wm_prog_key, sizeof(this->wm_prog_key),
1977                        program, program_size,
1978                        &prog.prog_data, sizeof(prog.prog_data),
1979                        &prog_offset, prog_data);
1980    }
1981    return prog_offset;
1982 }