1 /*
2 * Copyright © 2015 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 "nir.h"
25 #include "nir_builder.h"
26 #include "nir_xfb_info.h"
27
28 /**
29 * \file nir_lower_gs_intrinsics.c
30 *
31 * Geometry Shaders can call EmitVertex()/EmitStreamVertex() to output an
32 * arbitrary number of vertices. However, the shader must declare the maximum
33 * number of vertices that it will ever output - further attempts to emit
34 * vertices result in undefined behavior according to the GLSL specification.
35 *
36 * Drivers might use this maximum number of vertices to allocate enough space
37 * to hold the geometry shader's output. Some drivers (such as i965) need to
38 * implement "safety checks" which ensure that the shader hasn't emitted too
39 * many vertices, to avoid overflowing that space and trashing other memory.
40 *
41 * The count of emitted vertices can also be useful in buffer offset
42 * calculations, so drivers know where to write the GS output.
43 *
44 * However, for simple geometry shaders that emit a statically determinable
45 * number of vertices, this extra bookkeeping is unnecessary and inefficient.
46 * By tracking the vertex count in NIR, we allow constant folding/propagation
47 * and dead control flow optimizations to eliminate most of it where possible.
48 *
49 * This pass introduces a new global variable which stores the current vertex
50 * count (initialized to 0), and converts emit_vertex/end_primitive intrinsics
51 * to their *_with_counter variants. emit_vertex is also wrapped in a safety
52 * check to avoid buffer overflows. Finally, it adds a set_vertex_count
53 * intrinsic at the end of the program, informing the driver of the final
54 * vertex count.
55 */
56
57 struct state {
58 nir_builder *builder;
59 nir_variable *vertex_count_vars[NIR_MAX_XFB_STREAMS];
60 nir_variable *vtxcnt_per_prim_vars[NIR_MAX_XFB_STREAMS];
61 nir_variable *primitive_count_vars[NIR_MAX_XFB_STREAMS];
62 bool per_stream;
63 bool count_prims;
64 bool count_vtx_per_prim;
65 bool overwrite_incomplete;
66 bool progress;
67 };
68
69 /**
70 * Replace emit_vertex intrinsics with:
71 *
72 * if (vertex_count < max_vertices) {
73 * emit_vertex_with_counter vertex_count, vertex_count_per_primitive (optional) ...
74 * vertex_count += 1
75 * vertex_count_per_primitive += 1
76 * }
77 */
78 static void
rewrite_emit_vertex(nir_intrinsic_instr * intrin,struct state * state)79 rewrite_emit_vertex(nir_intrinsic_instr *intrin, struct state *state)
80 {
81 nir_builder *b = state->builder;
82 unsigned stream = nir_intrinsic_stream_id(intrin);
83
84 /* Load the vertex count */
85 b->cursor = nir_before_instr(&intrin->instr);
86 assert(state->vertex_count_vars[stream] != NULL);
87 nir_ssa_def *count = nir_load_var(b, state->vertex_count_vars[stream]);
88 nir_ssa_def *count_per_primitive;
89
90 if (state->count_vtx_per_prim)
91 count_per_primitive = nir_load_var(b, state->vtxcnt_per_prim_vars[stream]);
92 else
93 count_per_primitive = nir_ssa_undef(b, 1, 32);
94
95 nir_ssa_def *max_vertices =
96 nir_imm_int(b, b->shader->info.gs.vertices_out);
97
98 /* Create: if (vertex_count < max_vertices) and insert it.
99 *
100 * The new if statement needs to be hooked up to the control flow graph
101 * before we start inserting instructions into it.
102 */
103 nir_push_if(b, nir_ilt(b, count, max_vertices));
104
105 nir_intrinsic_instr *lowered =
106 nir_intrinsic_instr_create(b->shader,
107 nir_intrinsic_emit_vertex_with_counter);
108 nir_intrinsic_set_stream_id(lowered, stream);
109 lowered->src[0] = nir_src_for_ssa(count);
110 lowered->src[1] = nir_src_for_ssa(count_per_primitive);
111 nir_builder_instr_insert(b, &lowered->instr);
112
113 /* Increment the vertex count by 1 */
114 nir_store_var(b, state->vertex_count_vars[stream],
115 nir_iadd_imm(b, count, 1),
116 0x1); /* .x */
117
118 if (state->count_vtx_per_prim) {
119 /* Increment the per-primitive vertex count by 1 */
120 nir_variable *var = state->vtxcnt_per_prim_vars[stream];
121 nir_ssa_def *vtx_per_prim_cnt = nir_load_var(b, var);
122 nir_store_var(b, var,
123 nir_iadd_imm(b, vtx_per_prim_cnt, 1),
124 0x1); /* .x */
125 }
126
127 nir_pop_if(b, NULL);
128
129 nir_instr_remove(&intrin->instr);
130
131 state->progress = true;
132 }
133
134 /**
135 * Emits code that overwrites incomplete primitives and their vertices.
136 *
137 * A primitive is considered incomplete when it doesn't have enough vertices.
138 * For example, a triangle strip that has 2 or fewer vertices, or a line strip
139 * with 1 vertex are considered incomplete.
140 *
141 * After each end_primitive and at the end of the shader before emitting
142 * set_vertex_and_primitive_count, we check if the primitive that is being
143 * emitted has enough vertices or not, and we adjust the vertex and primitive
144 * counters accordingly.
145 *
146 * This means that the following emit_vertex can reuse the vertex index of
147 * a previous vertex, if the previous primitive was incomplete, so the compiler
148 * backend is expected to simply overwrite any data that belonged to those.
149 */
150 static void
overwrite_incomplete_primitives(struct state * state,unsigned stream)151 overwrite_incomplete_primitives(struct state *state, unsigned stream)
152 {
153 assert(state->count_vtx_per_prim);
154
155 nir_builder *b = state->builder;
156 unsigned outprim = b->shader->info.gs.output_primitive;
157 unsigned outprim_min_vertices;
158
159 if (outprim == GL_POINTS)
160 outprim_min_vertices = 1;
161 else if (outprim == GL_LINE_STRIP)
162 outprim_min_vertices = 2;
163 else if (outprim == GL_TRIANGLE_STRIP)
164 outprim_min_vertices = 3;
165 else
166 unreachable("Invalid GS output primitive type.");
167
168 /* Total count of vertices emitted so far. */
169 nir_ssa_def *vtxcnt_total =
170 nir_load_var(b, state->vertex_count_vars[stream]);
171
172 /* Number of vertices emitted for the last primitive */
173 nir_ssa_def *vtxcnt_per_primitive =
174 nir_load_var(b, state->vtxcnt_per_prim_vars[stream]);
175
176 /* See if the current primitive is a incomplete */
177 nir_ssa_def *is_inc_prim =
178 nir_ilt(b, vtxcnt_per_primitive, nir_imm_int(b, outprim_min_vertices));
179
180 /* Number of vertices in the incomplete primitive */
181 nir_ssa_def *num_inc_vtx =
182 nir_bcsel(b, is_inc_prim, vtxcnt_per_primitive, nir_imm_int(b, 0));
183
184 /* Store corrected total vertex count */
185 nir_store_var(b, state->vertex_count_vars[stream],
186 nir_isub(b, vtxcnt_total, num_inc_vtx),
187 0x1); /* .x */
188
189 if (state->count_prims) {
190 /* Number of incomplete primitives (0 or 1) */
191 nir_ssa_def *num_inc_prim = nir_b2i32(b, is_inc_prim);
192
193 /* Store corrected primitive count */
194 nir_ssa_def *prim_cnt = nir_load_var(b, state->primitive_count_vars[stream]);
195 nir_store_var(b, state->primitive_count_vars[stream],
196 nir_isub(b, prim_cnt, num_inc_prim),
197 0x1); /* .x */
198 }
199 }
200
201 /**
202 * Replace end_primitive with end_primitive_with_counter.
203 */
204 static void
rewrite_end_primitive(nir_intrinsic_instr * intrin,struct state * state)205 rewrite_end_primitive(nir_intrinsic_instr *intrin, struct state *state)
206 {
207 nir_builder *b = state->builder;
208 unsigned stream = nir_intrinsic_stream_id(intrin);
209
210 b->cursor = nir_before_instr(&intrin->instr);
211 assert(state->vertex_count_vars[stream] != NULL);
212 nir_ssa_def *count = nir_load_var(b, state->vertex_count_vars[stream]);
213 nir_ssa_def *count_per_primitive;
214
215 if (state->count_vtx_per_prim)
216 count_per_primitive = nir_load_var(b, state->vtxcnt_per_prim_vars[stream]);
217 else
218 count_per_primitive = nir_ssa_undef(b, count->num_components, count->bit_size);
219
220 nir_intrinsic_instr *lowered =
221 nir_intrinsic_instr_create(b->shader,
222 nir_intrinsic_end_primitive_with_counter);
223 nir_intrinsic_set_stream_id(lowered, stream);
224 lowered->src[0] = nir_src_for_ssa(count);
225 lowered->src[1] = nir_src_for_ssa(count_per_primitive);
226 nir_builder_instr_insert(b, &lowered->instr);
227
228 if (state->count_prims) {
229 /* Increment the primitive count by 1 */
230 nir_ssa_def *prim_cnt = nir_load_var(b, state->primitive_count_vars[stream]);
231 nir_store_var(b, state->primitive_count_vars[stream],
232 nir_iadd_imm(b, prim_cnt, 1),
233 0x1); /* .x */
234 }
235
236 if (state->count_vtx_per_prim) {
237 if (state->overwrite_incomplete)
238 overwrite_incomplete_primitives(state, stream);
239
240 /* Store 0 to per-primitive vertex count */
241 nir_store_var(b, state->vtxcnt_per_prim_vars[stream],
242 nir_imm_int(b, 0),
243 0x1); /* .x */
244 }
245
246 nir_instr_remove(&intrin->instr);
247
248 state->progress = true;
249 }
250
251 static bool
rewrite_intrinsics(nir_block * block,struct state * state)252 rewrite_intrinsics(nir_block *block, struct state *state)
253 {
254 nir_foreach_instr_safe(instr, block) {
255 if (instr->type != nir_instr_type_intrinsic)
256 continue;
257
258 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
259 switch (intrin->intrinsic) {
260 case nir_intrinsic_emit_vertex:
261 rewrite_emit_vertex(intrin, state);
262 break;
263 case nir_intrinsic_end_primitive:
264 rewrite_end_primitive(intrin, state);
265 break;
266 default:
267 /* not interesting; skip this */
268 break;
269 }
270 }
271
272 return true;
273 }
274
275 /**
276 * Add a set_vertex_and_primitive_count intrinsic at the end of the program
277 * (representing the final total vertex and primitive count).
278 */
279 static void
append_set_vertex_and_primitive_count(nir_block * end_block,struct state * state)280 append_set_vertex_and_primitive_count(nir_block *end_block, struct state *state)
281 {
282 nir_builder *b = state->builder;
283 nir_shader *shader = state->builder->shader;
284
285 /* Insert the new intrinsic in all of the predecessors of the end block,
286 * but before any jump instructions (return).
287 */
288 set_foreach(end_block->predecessors, entry) {
289 nir_block *pred = (nir_block *) entry->key;
290 b->cursor = nir_after_block_before_jump(pred);
291
292 for (unsigned stream = 0; stream < NIR_MAX_XFB_STREAMS; ++stream) {
293 /* When it's not per-stream, we only need to write one variable. */
294 if (!state->per_stream && stream != 0)
295 continue;
296
297 nir_ssa_def *vtx_cnt;
298 nir_ssa_def *prim_cnt;
299
300 if (state->per_stream && !(shader->info.gs.active_stream_mask & (1 << stream))) {
301 /* Inactive stream: vertex count is 0, primitive count is 0 or undef. */
302 vtx_cnt = nir_imm_int(b, 0);
303 prim_cnt = state->count_prims
304 ? nir_imm_int(b, 0)
305 : nir_ssa_undef(b, 1, 32);
306 } else {
307 if (state->overwrite_incomplete)
308 overwrite_incomplete_primitives(state, stream);
309
310 vtx_cnt = nir_load_var(b, state->vertex_count_vars[stream]);
311 prim_cnt = state->count_prims
312 ? nir_load_var(b, state->primitive_count_vars[stream])
313 : nir_ssa_undef(b, 1, 32);
314 }
315
316 nir_intrinsic_instr *set_cnt_intrin =
317 nir_intrinsic_instr_create(shader,
318 nir_intrinsic_set_vertex_and_primitive_count);
319
320 nir_intrinsic_set_stream_id(set_cnt_intrin, stream);
321 set_cnt_intrin->src[0] = nir_src_for_ssa(vtx_cnt);
322 set_cnt_intrin->src[1] = nir_src_for_ssa(prim_cnt);
323 nir_builder_instr_insert(b, &set_cnt_intrin->instr);
324 }
325 }
326 }
327
328 bool
nir_lower_gs_intrinsics(nir_shader * shader,nir_lower_gs_intrinsics_flags options)329 nir_lower_gs_intrinsics(nir_shader *shader, nir_lower_gs_intrinsics_flags options)
330 {
331 bool per_stream = options & nir_lower_gs_intrinsics_per_stream;
332 bool count_primitives = options & nir_lower_gs_intrinsics_count_primitives;
333 bool overwrite_incomplete = options & nir_lower_gs_intrinsics_overwrite_incomplete;
334 bool count_vtx_per_prim =
335 overwrite_incomplete ||
336 (options & nir_lower_gs_intrinsics_count_vertices_per_primitive);
337
338 struct state state;
339 state.progress = false;
340 state.count_prims = count_primitives;
341 state.count_vtx_per_prim = count_vtx_per_prim;
342 state.overwrite_incomplete = overwrite_incomplete;
343 state.per_stream = per_stream;
344
345 nir_function_impl *impl = nir_shader_get_entrypoint(shader);
346 assert(impl);
347
348 nir_builder b;
349 nir_builder_init(&b, impl);
350 state.builder = &b;
351
352 b.cursor = nir_before_cf_list(&impl->body);
353
354 for (unsigned i = 0; i < NIR_MAX_XFB_STREAMS; i++) {
355 if (per_stream && !(shader->info.gs.active_stream_mask & (1 << i)))
356 continue;
357
358 if (i == 0 || per_stream) {
359 state.vertex_count_vars[i] =
360 nir_local_variable_create(impl, glsl_uint_type(), "vertex_count");
361 /* initialize to 0 */
362 nir_store_var(&b, state.vertex_count_vars[i], nir_imm_int(&b, 0), 0x1);
363
364 if (count_primitives) {
365 state.primitive_count_vars[i] =
366 nir_local_variable_create(impl, glsl_uint_type(), "primitive_count");
367 /* initialize to 1 */
368 nir_store_var(&b, state.primitive_count_vars[i], nir_imm_int(&b, 1), 0x1);
369 }
370 if (count_vtx_per_prim) {
371 state.vtxcnt_per_prim_vars[i] =
372 nir_local_variable_create(impl, glsl_uint_type(), "vertices_per_primitive");
373 /* initialize to 0 */
374 nir_store_var(&b, state.vtxcnt_per_prim_vars[i], nir_imm_int(&b, 0), 0x1);
375 }
376 } else {
377 /* If per_stream is false, we only have one counter of each kind which we
378 * want to use for all streams. Duplicate the counter pointers so all
379 * streams use the same counters.
380 */
381 state.vertex_count_vars[i] = state.vertex_count_vars[0];
382
383 if (count_primitives)
384 state.primitive_count_vars[i] = state.primitive_count_vars[0];
385 if (count_vtx_per_prim)
386 state.vtxcnt_per_prim_vars[i] = state.vtxcnt_per_prim_vars[0];
387 }
388 }
389
390 nir_foreach_block_safe(block, impl)
391 rewrite_intrinsics(block, &state);
392
393 /* This only works because we have a single main() function. */
394 append_set_vertex_and_primitive_count(impl->end_block, &state);
395
396 nir_metadata_preserve(impl, 0);
397
398 return state.progress;
399 }
400