spirv: rename vtn_emit_cf_list to vtn_emit_cf_list_structured
[mesa.git] / src / compiler / spirv / vtn_cfg.c
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 "vtn_private.h"
25 #include "nir/nir_vla.h"
26
27 static struct vtn_block *
28 vtn_block(struct vtn_builder *b, uint32_t value_id)
29 {
30 return vtn_value(b, value_id, vtn_value_type_block)->block;
31 }
32
33 static unsigned
34 glsl_type_count_function_params(const struct glsl_type *type)
35 {
36 if (glsl_type_is_vector_or_scalar(type)) {
37 return 1;
38 } else if (glsl_type_is_array_or_matrix(type)) {
39 return glsl_get_length(type) *
40 glsl_type_count_function_params(glsl_get_array_element(type));
41 } else {
42 assert(glsl_type_is_struct_or_ifc(type));
43 unsigned count = 0;
44 unsigned elems = glsl_get_length(type);
45 for (unsigned i = 0; i < elems; i++) {
46 const struct glsl_type *elem_type = glsl_get_struct_field(type, i);
47 count += glsl_type_count_function_params(elem_type);
48 }
49 return count;
50 }
51 }
52
53 static void
54 glsl_type_add_to_function_params(const struct glsl_type *type,
55 nir_function *func,
56 unsigned *param_idx)
57 {
58 if (glsl_type_is_vector_or_scalar(type)) {
59 func->params[(*param_idx)++] = (nir_parameter) {
60 .num_components = glsl_get_vector_elements(type),
61 .bit_size = glsl_get_bit_size(type),
62 };
63 } else if (glsl_type_is_array_or_matrix(type)) {
64 unsigned elems = glsl_get_length(type);
65 const struct glsl_type *elem_type = glsl_get_array_element(type);
66 for (unsigned i = 0; i < elems; i++)
67 glsl_type_add_to_function_params(elem_type,func, param_idx);
68 } else {
69 assert(glsl_type_is_struct_or_ifc(type));
70 unsigned elems = glsl_get_length(type);
71 for (unsigned i = 0; i < elems; i++) {
72 const struct glsl_type *elem_type = glsl_get_struct_field(type, i);
73 glsl_type_add_to_function_params(elem_type, func, param_idx);
74 }
75 }
76 }
77
78 static void
79 vtn_ssa_value_add_to_call_params(struct vtn_builder *b,
80 struct vtn_ssa_value *value,
81 nir_call_instr *call,
82 unsigned *param_idx)
83 {
84 if (glsl_type_is_vector_or_scalar(value->type)) {
85 call->params[(*param_idx)++] = nir_src_for_ssa(value->def);
86 } else {
87 unsigned elems = glsl_get_length(value->type);
88 for (unsigned i = 0; i < elems; i++) {
89 vtn_ssa_value_add_to_call_params(b, value->elems[i],
90 call, param_idx);
91 }
92 }
93 }
94
95 static void
96 vtn_ssa_value_load_function_param(struct vtn_builder *b,
97 struct vtn_ssa_value *value,
98 unsigned *param_idx)
99 {
100 if (glsl_type_is_vector_or_scalar(value->type)) {
101 value->def = nir_load_param(&b->nb, (*param_idx)++);
102 } else {
103 unsigned elems = glsl_get_length(value->type);
104 for (unsigned i = 0; i < elems; i++)
105 vtn_ssa_value_load_function_param(b, value->elems[i], param_idx);
106 }
107 }
108
109 void
110 vtn_handle_function_call(struct vtn_builder *b, SpvOp opcode,
111 const uint32_t *w, unsigned count)
112 {
113 struct vtn_function *vtn_callee =
114 vtn_value(b, w[3], vtn_value_type_function)->func;
115 struct nir_function *callee = vtn_callee->impl->function;
116
117 vtn_callee->referenced = true;
118
119 nir_call_instr *call = nir_call_instr_create(b->nb.shader, callee);
120
121 unsigned param_idx = 0;
122
123 nir_deref_instr *ret_deref = NULL;
124 struct vtn_type *ret_type = vtn_callee->type->return_type;
125 if (ret_type->base_type != vtn_base_type_void) {
126 nir_variable *ret_tmp =
127 nir_local_variable_create(b->nb.impl,
128 glsl_get_bare_type(ret_type->type),
129 "return_tmp");
130 ret_deref = nir_build_deref_var(&b->nb, ret_tmp);
131 call->params[param_idx++] = nir_src_for_ssa(&ret_deref->dest.ssa);
132 }
133
134 for (unsigned i = 0; i < vtn_callee->type->length; i++) {
135 vtn_ssa_value_add_to_call_params(b, vtn_ssa_value(b, w[4 + i]),
136 call, &param_idx);
137 }
138 assert(param_idx == call->num_params);
139
140 nir_builder_instr_insert(&b->nb, &call->instr);
141
142 if (ret_type->base_type == vtn_base_type_void) {
143 vtn_push_value(b, w[2], vtn_value_type_undef);
144 } else {
145 vtn_push_ssa_value(b, w[2], vtn_local_load(b, ret_deref, 0));
146 }
147 }
148
149 static bool
150 vtn_cfg_handle_prepass_instruction(struct vtn_builder *b, SpvOp opcode,
151 const uint32_t *w, unsigned count)
152 {
153 switch (opcode) {
154 case SpvOpFunction: {
155 vtn_assert(b->func == NULL);
156 b->func = rzalloc(b, struct vtn_function);
157
158 b->func->node.type = vtn_cf_node_type_function;
159 b->func->node.parent = NULL;
160 list_inithead(&b->func->body);
161 b->func->control = w[3];
162
163 UNUSED const struct glsl_type *result_type = vtn_get_type(b, w[1])->type;
164 struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_function);
165 val->func = b->func;
166
167 b->func->type = vtn_get_type(b, w[4]);
168 const struct vtn_type *func_type = b->func->type;
169
170 vtn_assert(func_type->return_type->type == result_type);
171
172 nir_function *func =
173 nir_function_create(b->shader, ralloc_strdup(b->shader, val->name));
174
175 unsigned num_params = 0;
176 for (unsigned i = 0; i < func_type->length; i++)
177 num_params += glsl_type_count_function_params(func_type->params[i]->type);
178
179 /* Add one parameter for the function return value */
180 if (func_type->return_type->base_type != vtn_base_type_void)
181 num_params++;
182
183 func->num_params = num_params;
184 func->params = ralloc_array(b->shader, nir_parameter, num_params);
185
186 unsigned idx = 0;
187 if (func_type->return_type->base_type != vtn_base_type_void) {
188 nir_address_format addr_format =
189 vtn_mode_to_address_format(b, vtn_variable_mode_function);
190 /* The return value is a regular pointer */
191 func->params[idx++] = (nir_parameter) {
192 .num_components = nir_address_format_num_components(addr_format),
193 .bit_size = nir_address_format_bit_size(addr_format),
194 };
195 }
196
197 for (unsigned i = 0; i < func_type->length; i++)
198 glsl_type_add_to_function_params(func_type->params[i]->type, func, &idx);
199 assert(idx == num_params);
200
201 b->func->impl = nir_function_impl_create(func);
202 nir_builder_init(&b->nb, func->impl);
203 b->nb.cursor = nir_before_cf_list(&b->func->impl->body);
204 b->nb.exact = b->exact;
205
206 b->func_param_idx = 0;
207
208 /* The return value is the first parameter */
209 if (func_type->return_type->base_type != vtn_base_type_void)
210 b->func_param_idx++;
211 break;
212 }
213
214 case SpvOpFunctionEnd:
215 b->func->end = w;
216 b->func = NULL;
217 break;
218
219 case SpvOpFunctionParameter: {
220 vtn_assert(b->func_param_idx < b->func->impl->function->num_params);
221 struct vtn_type *type = vtn_get_type(b, w[1]);
222 struct vtn_ssa_value *value = vtn_create_ssa_value(b, type->type);
223 vtn_ssa_value_load_function_param(b, value, &b->func_param_idx);
224 vtn_push_ssa_value(b, w[2], value);
225 break;
226 }
227
228 case SpvOpLabel: {
229 vtn_assert(b->block == NULL);
230 b->block = rzalloc(b, struct vtn_block);
231 b->block->node.type = vtn_cf_node_type_block;
232 b->block->label = w;
233 vtn_push_value(b, w[1], vtn_value_type_block)->block = b->block;
234
235 if (b->func->start_block == NULL) {
236 /* This is the first block encountered for this function. In this
237 * case, we set the start block and add it to the list of
238 * implemented functions that we'll walk later.
239 */
240 b->func->start_block = b->block;
241 list_addtail(&b->func->node.link, &b->functions);
242 }
243 break;
244 }
245
246 case SpvOpSelectionMerge:
247 case SpvOpLoopMerge:
248 vtn_assert(b->block && b->block->merge == NULL);
249 b->block->merge = w;
250 break;
251
252 case SpvOpBranch:
253 case SpvOpBranchConditional:
254 case SpvOpSwitch:
255 case SpvOpKill:
256 case SpvOpReturn:
257 case SpvOpReturnValue:
258 case SpvOpUnreachable:
259 vtn_assert(b->block && b->block->branch == NULL);
260 b->block->branch = w;
261 b->block = NULL;
262 break;
263
264 default:
265 /* Continue on as per normal */
266 return true;
267 }
268
269 return true;
270 }
271
272 /* This function performs a depth-first search of the cases and puts them
273 * in fall-through order.
274 */
275 static void
276 vtn_order_case(struct vtn_switch *swtch, struct vtn_case *cse)
277 {
278 if (cse->visited)
279 return;
280
281 cse->visited = true;
282
283 list_del(&cse->node.link);
284
285 if (cse->fallthrough) {
286 vtn_order_case(swtch, cse->fallthrough);
287
288 /* If we have a fall-through, place this case right before the case it
289 * falls through to. This ensures that fallthroughs come one after
290 * the other. These two can never get separated because that would
291 * imply something else falling through to the same case. Also, this
292 * can't break ordering because the DFS ensures that this case is
293 * visited before anything that falls through to it.
294 */
295 list_addtail(&cse->node.link, &cse->fallthrough->node.link);
296 } else {
297 list_add(&cse->node.link, &swtch->cases);
298 }
299 }
300
301 static void
302 vtn_switch_order_cases(struct vtn_switch *swtch)
303 {
304 struct list_head cases;
305 list_replace(&swtch->cases, &cases);
306 list_inithead(&swtch->cases);
307 while (!list_is_empty(&cases)) {
308 struct vtn_case *cse =
309 list_first_entry(&cases, struct vtn_case, node.link);
310 vtn_order_case(swtch, cse);
311 }
312 }
313
314 static void
315 vtn_block_set_merge_cf_node(struct vtn_builder *b, struct vtn_block *block,
316 struct vtn_cf_node *cf_node)
317 {
318 vtn_fail_if(block->merge_cf_node != NULL,
319 "The merge block declared by a header block cannot be a "
320 "merge block declared by any other header block.");
321
322 block->merge_cf_node = cf_node;
323 }
324
325 #define VTN_DECL_CF_NODE_FIND(_type) \
326 static inline struct vtn_##_type * \
327 vtn_cf_node_find_##_type(struct vtn_cf_node *node) \
328 { \
329 while (node && node->type != vtn_cf_node_type_##_type) \
330 node = node->parent; \
331 return (struct vtn_##_type *)node; \
332 }
333
334 VTN_DECL_CF_NODE_FIND(if)
335 VTN_DECL_CF_NODE_FIND(loop)
336 VTN_DECL_CF_NODE_FIND(case)
337 VTN_DECL_CF_NODE_FIND(switch)
338 VTN_DECL_CF_NODE_FIND(function)
339
340 static enum vtn_branch_type
341 vtn_handle_branch(struct vtn_builder *b,
342 struct vtn_cf_node *cf_parent,
343 struct vtn_block *target_block)
344 {
345 struct vtn_loop *loop = vtn_cf_node_find_loop(cf_parent);
346
347 /* Detect a loop back-edge first. That way none of the code below
348 * accidentally operates on a loop back-edge.
349 */
350 if (loop && target_block == loop->header_block)
351 return vtn_branch_type_loop_back_edge;
352
353 /* Try to detect fall-through */
354 if (target_block->switch_case) {
355 /* When it comes to handling switch cases, we can break calls to
356 * vtn_handle_branch into two cases: calls from within a case construct
357 * and calls for the jump to each case construct. In the second case,
358 * cf_parent is the vtn_switch itself and vtn_cf_node_find_case() will
359 * return the outer switch case in which this switch is contained. It's
360 * fine if the target block is a switch case from an outer switch as
361 * long as it is also the switch break for this switch.
362 */
363 struct vtn_case *switch_case = vtn_cf_node_find_case(cf_parent);
364
365 /* This doesn't get called for the OpSwitch */
366 vtn_fail_if(switch_case == NULL,
367 "A switch case can only be entered through an OpSwitch or "
368 "falling through from another switch case.");
369
370 /* Because block->switch_case is only set on the entry block for a given
371 * switch case, we only ever get here if we're jumping to the start of a
372 * switch case. It's possible, however, that a switch case could jump
373 * to itself via a back-edge. That *should* get caught by the loop
374 * handling case above but if we have a back edge without a loop merge,
375 * we could en up here.
376 */
377 vtn_fail_if(target_block->switch_case == switch_case,
378 "A switch cannot fall-through to itself. Likely, there is "
379 "a back-edge which is not to a loop header.");
380
381 vtn_fail_if(target_block->switch_case->node.parent !=
382 switch_case->node.parent,
383 "A switch case fall-through must come from the same "
384 "OpSwitch construct");
385
386 vtn_fail_if(switch_case->fallthrough != NULL &&
387 switch_case->fallthrough != target_block->switch_case,
388 "Each case construct can have at most one branch to "
389 "another case construct");
390
391 switch_case->fallthrough = target_block->switch_case;
392
393 /* We don't immediately return vtn_branch_type_switch_fallthrough
394 * because it may also be a loop or switch break for an inner loop or
395 * switch and that takes precedence.
396 */
397 }
398
399 if (loop && target_block == loop->cont_block)
400 return vtn_branch_type_loop_continue;
401
402 /* We walk blocks as a breadth-first search on the control-flow construct
403 * tree where, when we find a construct, we add the vtn_cf_node for that
404 * construct and continue iterating at the merge target block (if any).
405 * Therefore, we want merges whose with parent == cf_parent to be treated
406 * as regular branches. We only want to consider merges if they break out
407 * of the current CF construct.
408 */
409 if (target_block->merge_cf_node != NULL &&
410 target_block->merge_cf_node->parent != cf_parent) {
411 switch (target_block->merge_cf_node->type) {
412 case vtn_cf_node_type_if:
413 for (struct vtn_cf_node *node = cf_parent;
414 node != target_block->merge_cf_node; node = node->parent) {
415 vtn_fail_if(node == NULL || node->type != vtn_cf_node_type_if,
416 "Branching to the merge block of a selection "
417 "construct can only be used to break out of a "
418 "selection construct");
419
420 struct vtn_if *if_stmt = vtn_cf_node_as_if(node);
421
422 /* This should be guaranteed by our iteration */
423 assert(if_stmt->merge_block != target_block);
424
425 vtn_fail_if(if_stmt->merge_block != NULL,
426 "Branching to the merge block of a selection "
427 "construct can only be used to break out of the "
428 "inner most nested selection level");
429 }
430 return vtn_branch_type_if_merge;
431
432 case vtn_cf_node_type_loop:
433 vtn_fail_if(target_block->merge_cf_node != &loop->node,
434 "Loop breaks can only break out of the inner most "
435 "nested loop level");
436 return vtn_branch_type_loop_break;
437
438 case vtn_cf_node_type_switch: {
439 struct vtn_switch *swtch = vtn_cf_node_find_switch(cf_parent);
440 vtn_fail_if(target_block->merge_cf_node != &swtch->node,
441 "Switch breaks can only break out of the inner most "
442 "nested switch level");
443 return vtn_branch_type_switch_break;
444 }
445
446 default:
447 unreachable("Invalid CF node type for a merge");
448 }
449 }
450
451 if (target_block->switch_case)
452 return vtn_branch_type_switch_fallthrough;
453
454 return vtn_branch_type_none;
455 }
456
457 struct vtn_cfg_work_item {
458 struct list_head link;
459
460 struct vtn_cf_node *cf_parent;
461 struct list_head *cf_list;
462 struct vtn_block *start_block;
463 };
464
465 static void
466 vtn_add_cfg_work_item(struct vtn_builder *b,
467 struct list_head *work_list,
468 struct vtn_cf_node *cf_parent,
469 struct list_head *cf_list,
470 struct vtn_block *start_block)
471 {
472 struct vtn_cfg_work_item *work = ralloc(b, struct vtn_cfg_work_item);
473 work->cf_parent = cf_parent;
474 work->cf_list = cf_list;
475 work->start_block = start_block;
476 list_addtail(&work->link, work_list);
477 }
478
479 /* Processes a block and returns the next block to process or NULL if we've
480 * reached the end of the construct.
481 */
482 static struct vtn_block *
483 vtn_process_block(struct vtn_builder *b,
484 struct list_head *work_list,
485 struct vtn_cf_node *cf_parent,
486 struct list_head *cf_list,
487 struct vtn_block *block)
488 {
489 if (!list_is_empty(cf_list)) {
490 /* vtn_process_block() acts like an iterator: it processes the given
491 * block and then returns the next block to process. For a given
492 * control-flow construct, vtn_build_cfg() calls vtn_process_block()
493 * repeatedly until it finally returns NULL. Therefore, we know that
494 * the only blocks on which vtn_process_block() can be called are either
495 * the first block in a construct or a block that vtn_process_block()
496 * returned for the current construct. If cf_list is empty then we know
497 * that we're processing the first block in the construct and we have to
498 * add it to the list.
499 *
500 * If cf_list is not empty, then it must be the block returned by the
501 * previous call to vtn_process_block(). We know a priori that
502 * vtn_process_block only returns either normal branches
503 * (vtn_branch_type_none) or merge target blocks.
504 */
505 switch (vtn_handle_branch(b, cf_parent, block)) {
506 case vtn_branch_type_none:
507 /* For normal branches, we want to process them and add them to the
508 * current construct. Merge target blocks also look like normal
509 * branches from the perspective of this construct. See also
510 * vtn_handle_branch().
511 */
512 break;
513
514 case vtn_branch_type_loop_continue:
515 case vtn_branch_type_switch_fallthrough:
516 /* The two cases where we can get early exits from a construct that
517 * are not to that construct's merge target are loop continues and
518 * switch fall-throughs. In these cases, we need to break out of the
519 * current construct by returning NULL.
520 */
521 return NULL;
522
523 default:
524 /* The only way we can get here is if something was used as two kinds
525 * of merges at the same time and that's illegal.
526 */
527 vtn_fail("A block was used as a merge target from two or more "
528 "structured control-flow constructs");
529 }
530 }
531
532 /* Once a block has been processed, it is placed into and the list link
533 * will point to something non-null. If we see a node we've already
534 * processed here, it either exists in multiple functions or it's an
535 * invalid back-edge.
536 */
537 if (block->node.parent != NULL) {
538 vtn_fail_if(vtn_cf_node_find_function(&block->node) !=
539 vtn_cf_node_find_function(cf_parent),
540 "A block cannot exist in two functions at the "
541 "same time");
542
543 vtn_fail("Invalid back or cross-edge in the CFG");
544 }
545
546 if (block->merge && (*block->merge & SpvOpCodeMask) == SpvOpLoopMerge &&
547 block->loop == NULL) {
548 vtn_fail_if((*block->branch & SpvOpCodeMask) != SpvOpBranch &&
549 (*block->branch & SpvOpCodeMask) != SpvOpBranchConditional,
550 "An OpLoopMerge instruction must immediately precede "
551 "either an OpBranch or OpBranchConditional instruction.");
552
553 struct vtn_loop *loop = rzalloc(b, struct vtn_loop);
554
555 loop->node.type = vtn_cf_node_type_loop;
556 loop->node.parent = cf_parent;
557 list_inithead(&loop->body);
558 list_inithead(&loop->cont_body);
559 loop->header_block = block;
560 loop->break_block = vtn_block(b, block->merge[1]);
561 loop->cont_block = vtn_block(b, block->merge[2]);
562 loop->control = block->merge[3];
563
564 list_addtail(&loop->node.link, cf_list);
565 block->loop = loop;
566
567 /* Note: The work item for the main loop body will start with the
568 * current block as its start block. If we weren't careful, we would
569 * get here again and end up in an infinite loop. This is why we set
570 * block->loop above and check for it before creating one. This way,
571 * we only create the loop once and the second iteration that tries to
572 * handle this loop goes to the cases below and gets handled as a
573 * regular block.
574 */
575 vtn_add_cfg_work_item(b, work_list, &loop->node,
576 &loop->body, loop->header_block);
577
578 /* For continue targets, SPIR-V guarantees the following:
579 *
580 * - the Continue Target must dominate the back-edge block
581 * - the back-edge block must post dominate the Continue Target
582 *
583 * If the header block is the same as the continue target, this
584 * condition is trivially satisfied and there is no real continue
585 * section.
586 */
587 if (loop->cont_block != loop->header_block) {
588 vtn_add_cfg_work_item(b, work_list, &loop->node,
589 &loop->cont_body, loop->cont_block);
590 }
591
592 vtn_block_set_merge_cf_node(b, loop->break_block, &loop->node);
593
594 return loop->break_block;
595 }
596
597 /* Add the block to the CF list */
598 block->node.parent = cf_parent;
599 list_addtail(&block->node.link, cf_list);
600
601 switch (*block->branch & SpvOpCodeMask) {
602 case SpvOpBranch: {
603 struct vtn_block *branch_block = vtn_block(b, block->branch[1]);
604
605 block->branch_type = vtn_handle_branch(b, cf_parent, branch_block);
606
607 if (block->branch_type == vtn_branch_type_none)
608 return branch_block;
609 else
610 return NULL;
611 }
612
613 case SpvOpReturn:
614 case SpvOpReturnValue:
615 block->branch_type = vtn_branch_type_return;
616 return NULL;
617
618 case SpvOpKill:
619 block->branch_type = vtn_branch_type_discard;
620 return NULL;
621
622 case SpvOpBranchConditional: {
623 struct vtn_value *cond_val = vtn_untyped_value(b, block->branch[1]);
624 vtn_fail_if(!cond_val->type ||
625 cond_val->type->base_type != vtn_base_type_scalar ||
626 cond_val->type->type != glsl_bool_type(),
627 "Condition must be a Boolean type scalar");
628
629 struct vtn_block *then_block = vtn_block(b, block->branch[2]);
630 struct vtn_block *else_block = vtn_block(b, block->branch[3]);
631
632 if (then_block == else_block) {
633 /* This is uncommon but it can happen. We treat this the same way as
634 * an unconditional branch.
635 */
636 block->branch_type = vtn_handle_branch(b, cf_parent, then_block);
637
638 if (block->branch_type == vtn_branch_type_none)
639 return then_block;
640 else
641 return NULL;
642 }
643
644 struct vtn_if *if_stmt = rzalloc(b, struct vtn_if);
645
646 if_stmt->node.type = vtn_cf_node_type_if;
647 if_stmt->node.parent = cf_parent;
648 if_stmt->condition = block->branch[1];
649 list_inithead(&if_stmt->then_body);
650 list_inithead(&if_stmt->else_body);
651
652 list_addtail(&if_stmt->node.link, cf_list);
653
654 if (block->merge &&
655 (*block->merge & SpvOpCodeMask) == SpvOpSelectionMerge) {
656 /* We may not always have a merge block and that merge doesn't
657 * technically have to be an OpSelectionMerge. We could have a block
658 * with an OpLoopMerge which ends in an OpBranchConditional.
659 */
660 if_stmt->merge_block = vtn_block(b, block->merge[1]);
661 vtn_block_set_merge_cf_node(b, if_stmt->merge_block, &if_stmt->node);
662
663 if_stmt->control = block->merge[2];
664 }
665
666 if_stmt->then_type = vtn_handle_branch(b, &if_stmt->node, then_block);
667 if (if_stmt->then_type == vtn_branch_type_none) {
668 vtn_add_cfg_work_item(b, work_list, &if_stmt->node,
669 &if_stmt->then_body, then_block);
670 }
671
672 if_stmt->else_type = vtn_handle_branch(b, &if_stmt->node, else_block);
673 if (if_stmt->else_type == vtn_branch_type_none) {
674 vtn_add_cfg_work_item(b, work_list, &if_stmt->node,
675 &if_stmt->else_body, else_block);
676 }
677
678 return if_stmt->merge_block;
679 }
680
681 case SpvOpSwitch: {
682 struct vtn_value *sel_val = vtn_untyped_value(b, block->branch[1]);
683 vtn_fail_if(!sel_val->type ||
684 sel_val->type->base_type != vtn_base_type_scalar,
685 "Selector of OpSwitch must have a type of OpTypeInt");
686
687 nir_alu_type sel_type =
688 nir_get_nir_type_for_glsl_type(sel_val->type->type);
689 vtn_fail_if(nir_alu_type_get_base_type(sel_type) != nir_type_int &&
690 nir_alu_type_get_base_type(sel_type) != nir_type_uint,
691 "Selector of OpSwitch must have a type of OpTypeInt");
692
693 struct vtn_switch *swtch = rzalloc(b, struct vtn_switch);
694
695 swtch->node.type = vtn_cf_node_type_switch;
696 swtch->node.parent = cf_parent;
697 swtch->selector = block->branch[1];
698 list_inithead(&swtch->cases);
699
700 list_addtail(&swtch->node.link, cf_list);
701
702 /* We may not always have a merge block */
703 if (block->merge) {
704 vtn_fail_if((*block->merge & SpvOpCodeMask) != SpvOpSelectionMerge,
705 "An OpLoopMerge instruction must immediately precede "
706 "either an OpBranch or OpBranchConditional "
707 "instruction.");
708 swtch->break_block = vtn_block(b, block->merge[1]);
709 vtn_block_set_merge_cf_node(b, swtch->break_block, &swtch->node);
710 }
711
712 /* First, we go through and record all of the cases. */
713 const uint32_t *branch_end =
714 block->branch + (block->branch[0] >> SpvWordCountShift);
715
716 struct hash_table *block_to_case = _mesa_pointer_hash_table_create(b);
717
718 bool is_default = true;
719 const unsigned bitsize = nir_alu_type_get_type_size(sel_type);
720 for (const uint32_t *w = block->branch + 2; w < branch_end;) {
721 uint64_t literal = 0;
722 if (!is_default) {
723 if (bitsize <= 32) {
724 literal = *(w++);
725 } else {
726 assert(bitsize == 64);
727 literal = vtn_u64_literal(w);
728 w += 2;
729 }
730 }
731 struct vtn_block *case_block = vtn_block(b, *(w++));
732
733 struct hash_entry *case_entry =
734 _mesa_hash_table_search(block_to_case, case_block);
735
736 struct vtn_case *cse;
737 if (case_entry) {
738 cse = case_entry->data;
739 } else {
740 cse = rzalloc(b, struct vtn_case);
741
742 cse->node.type = vtn_cf_node_type_case;
743 cse->node.parent = &swtch->node;
744 list_inithead(&cse->body);
745 util_dynarray_init(&cse->values, b);
746
747 cse->type = vtn_handle_branch(b, &swtch->node, case_block);
748 switch (cse->type) {
749 case vtn_branch_type_none:
750 /* This is a "real" cases which has stuff in it */
751 vtn_fail_if(case_block->switch_case != NULL,
752 "OpSwitch has a case which is also in another "
753 "OpSwitch construct");
754 case_block->switch_case = cse;
755 vtn_add_cfg_work_item(b, work_list, &cse->node,
756 &cse->body, case_block);
757 break;
758
759 case vtn_branch_type_switch_break:
760 case vtn_branch_type_loop_break:
761 case vtn_branch_type_loop_continue:
762 /* Switch breaks as well as loop breaks and continues can be
763 * used to break out of a switch construct or as direct targets
764 * of the OpSwitch.
765 */
766 break;
767
768 default:
769 vtn_fail("Target of OpSwitch is not a valid structured exit "
770 "from the switch construct.");
771 }
772
773 list_addtail(&cse->node.link, &swtch->cases);
774
775 _mesa_hash_table_insert(block_to_case, case_block, cse);
776 }
777
778 if (is_default) {
779 cse->is_default = true;
780 } else {
781 util_dynarray_append(&cse->values, uint64_t, literal);
782 }
783
784 is_default = false;
785 }
786
787 _mesa_hash_table_destroy(block_to_case, NULL);
788
789 return swtch->break_block;
790 }
791
792 case SpvOpUnreachable:
793 return NULL;
794
795 default:
796 vtn_fail("Block did not end with a valid branch instruction");
797 }
798 }
799
800 void
801 vtn_build_cfg(struct vtn_builder *b, const uint32_t *words, const uint32_t *end)
802 {
803 vtn_foreach_instruction(b, words, end,
804 vtn_cfg_handle_prepass_instruction);
805
806 vtn_foreach_cf_node(func_node, &b->functions) {
807 struct vtn_function *func = vtn_cf_node_as_function(func_node);
808
809 /* We build the CFG for each function by doing a breadth-first search on
810 * the control-flow graph. We keep track of our state using a worklist.
811 * Doing a BFS ensures that we visit each structured control-flow
812 * construct and its merge node before we visit the stuff inside the
813 * construct.
814 */
815 struct list_head work_list;
816 list_inithead(&work_list);
817 vtn_add_cfg_work_item(b, &work_list, &func->node, &func->body,
818 func->start_block);
819
820 while (!list_is_empty(&work_list)) {
821 struct vtn_cfg_work_item *work =
822 list_first_entry(&work_list, struct vtn_cfg_work_item, link);
823 list_del(&work->link);
824
825 for (struct vtn_block *block = work->start_block; block; ) {
826 block = vtn_process_block(b, &work_list, work->cf_parent,
827 work->cf_list, block);
828 }
829 }
830 }
831 }
832
833 static bool
834 vtn_handle_phis_first_pass(struct vtn_builder *b, SpvOp opcode,
835 const uint32_t *w, unsigned count)
836 {
837 if (opcode == SpvOpLabel)
838 return true; /* Nothing to do */
839
840 /* If this isn't a phi node, stop. */
841 if (opcode != SpvOpPhi)
842 return false;
843
844 /* For handling phi nodes, we do a poor-man's out-of-ssa on the spot.
845 * For each phi, we create a variable with the appropreate type and
846 * do a load from that variable. Then, in a second pass, we add
847 * stores to that variable to each of the predecessor blocks.
848 *
849 * We could do something more intelligent here. However, in order to
850 * handle loops and things properly, we really need dominance
851 * information. It would end up basically being the into-SSA
852 * algorithm all over again. It's easier if we just let
853 * lower_vars_to_ssa do that for us instead of repeating it here.
854 */
855 struct vtn_type *type = vtn_get_type(b, w[1]);
856 nir_variable *phi_var =
857 nir_local_variable_create(b->nb.impl, type->type, "phi");
858 _mesa_hash_table_insert(b->phi_table, w, phi_var);
859
860 vtn_push_ssa_value(b, w[2],
861 vtn_local_load(b, nir_build_deref_var(&b->nb, phi_var), 0));
862
863 return true;
864 }
865
866 static bool
867 vtn_handle_phi_second_pass(struct vtn_builder *b, SpvOp opcode,
868 const uint32_t *w, unsigned count)
869 {
870 if (opcode != SpvOpPhi)
871 return true;
872
873 struct hash_entry *phi_entry = _mesa_hash_table_search(b->phi_table, w);
874
875 /* It's possible that this phi is in an unreachable block in which case it
876 * may never have been emitted and therefore may not be in the hash table.
877 * In this case, there's no var for it and it's safe to just bail.
878 */
879 if (phi_entry == NULL)
880 return true;
881
882 nir_variable *phi_var = phi_entry->data;
883
884 for (unsigned i = 3; i < count; i += 2) {
885 struct vtn_block *pred = vtn_block(b, w[i + 1]);
886
887 /* If block does not have end_nop, that is because it is an unreacheable
888 * block, and hence it is not worth to handle it */
889 if (!pred->end_nop)
890 continue;
891
892 b->nb.cursor = nir_after_instr(&pred->end_nop->instr);
893
894 struct vtn_ssa_value *src = vtn_ssa_value(b, w[i]);
895
896 vtn_local_store(b, src, nir_build_deref_var(&b->nb, phi_var), 0);
897 }
898
899 return true;
900 }
901
902 static void
903 vtn_emit_branch(struct vtn_builder *b, enum vtn_branch_type branch_type,
904 nir_variable *switch_fall_var, bool *has_switch_break)
905 {
906 switch (branch_type) {
907 case vtn_branch_type_if_merge:
908 break; /* Nothing to do */
909 case vtn_branch_type_switch_break:
910 nir_store_var(&b->nb, switch_fall_var, nir_imm_false(&b->nb), 1);
911 *has_switch_break = true;
912 break;
913 case vtn_branch_type_switch_fallthrough:
914 break; /* Nothing to do */
915 case vtn_branch_type_loop_break:
916 nir_jump(&b->nb, nir_jump_break);
917 break;
918 case vtn_branch_type_loop_continue:
919 nir_jump(&b->nb, nir_jump_continue);
920 break;
921 case vtn_branch_type_loop_back_edge:
922 break;
923 case vtn_branch_type_return:
924 nir_jump(&b->nb, nir_jump_return);
925 break;
926 case vtn_branch_type_discard: {
927 nir_intrinsic_instr *discard =
928 nir_intrinsic_instr_create(b->nb.shader, nir_intrinsic_discard);
929 nir_builder_instr_insert(&b->nb, &discard->instr);
930 break;
931 }
932 default:
933 vtn_fail("Invalid branch type");
934 }
935 }
936
937 static nir_ssa_def *
938 vtn_switch_case_condition(struct vtn_builder *b, struct vtn_switch *swtch,
939 nir_ssa_def *sel, struct vtn_case *cse)
940 {
941 if (cse->is_default) {
942 nir_ssa_def *any = nir_imm_false(&b->nb);
943 vtn_foreach_cf_node(other_node, &swtch->cases) {
944 struct vtn_case *other = vtn_cf_node_as_case(other_node);
945 if (other->is_default)
946 continue;
947
948 any = nir_ior(&b->nb, any,
949 vtn_switch_case_condition(b, swtch, sel, other));
950 }
951 return nir_inot(&b->nb, any);
952 } else {
953 nir_ssa_def *cond = nir_imm_false(&b->nb);
954 util_dynarray_foreach(&cse->values, uint64_t, val) {
955 nir_ssa_def *imm = nir_imm_intN_t(&b->nb, *val, sel->bit_size);
956 cond = nir_ior(&b->nb, cond, nir_ieq(&b->nb, sel, imm));
957 }
958 return cond;
959 }
960 }
961
962 static nir_loop_control
963 vtn_loop_control(struct vtn_builder *b, struct vtn_loop *vtn_loop)
964 {
965 if (vtn_loop->control == SpvLoopControlMaskNone)
966 return nir_loop_control_none;
967 else if (vtn_loop->control & SpvLoopControlDontUnrollMask)
968 return nir_loop_control_dont_unroll;
969 else if (vtn_loop->control & SpvLoopControlUnrollMask)
970 return nir_loop_control_unroll;
971 else if (vtn_loop->control & SpvLoopControlDependencyInfiniteMask ||
972 vtn_loop->control & SpvLoopControlDependencyLengthMask ||
973 vtn_loop->control & SpvLoopControlMinIterationsMask ||
974 vtn_loop->control & SpvLoopControlMaxIterationsMask ||
975 vtn_loop->control & SpvLoopControlIterationMultipleMask ||
976 vtn_loop->control & SpvLoopControlPeelCountMask ||
977 vtn_loop->control & SpvLoopControlPartialCountMask) {
978 /* We do not do anything special with these yet. */
979 return nir_loop_control_none;
980 } else {
981 vtn_fail("Invalid loop control");
982 }
983 }
984
985 static nir_selection_control
986 vtn_selection_control(struct vtn_builder *b, struct vtn_if *vtn_if)
987 {
988 if (vtn_if->control == SpvSelectionControlMaskNone)
989 return nir_selection_control_none;
990 else if (vtn_if->control & SpvSelectionControlDontFlattenMask)
991 return nir_selection_control_dont_flatten;
992 else if (vtn_if->control & SpvSelectionControlFlattenMask)
993 return nir_selection_control_flatten;
994 else
995 vtn_fail("Invalid selection control");
996 }
997
998 static void
999 vtn_emit_cf_list_structured(struct vtn_builder *b, struct list_head *cf_list,
1000 nir_variable *switch_fall_var,
1001 bool *has_switch_break,
1002 vtn_instruction_handler handler)
1003 {
1004 vtn_foreach_cf_node(node, cf_list) {
1005 switch (node->type) {
1006 case vtn_cf_node_type_block: {
1007 struct vtn_block *block = vtn_cf_node_as_block(node);
1008
1009 const uint32_t *block_start = block->label;
1010 const uint32_t *block_end = block->merge ? block->merge :
1011 block->branch;
1012
1013 block_start = vtn_foreach_instruction(b, block_start, block_end,
1014 vtn_handle_phis_first_pass);
1015
1016 vtn_foreach_instruction(b, block_start, block_end, handler);
1017
1018 block->end_nop = nir_intrinsic_instr_create(b->nb.shader,
1019 nir_intrinsic_nop);
1020 nir_builder_instr_insert(&b->nb, &block->end_nop->instr);
1021
1022 if ((*block->branch & SpvOpCodeMask) == SpvOpReturnValue) {
1023 vtn_fail_if(b->func->type->return_type->base_type ==
1024 vtn_base_type_void,
1025 "Return with a value from a function returning void");
1026 struct vtn_ssa_value *src = vtn_ssa_value(b, block->branch[1]);
1027 const struct glsl_type *ret_type =
1028 glsl_get_bare_type(b->func->type->return_type->type);
1029 nir_deref_instr *ret_deref =
1030 nir_build_deref_cast(&b->nb, nir_load_param(&b->nb, 0),
1031 nir_var_function_temp, ret_type, 0);
1032 vtn_local_store(b, src, ret_deref, 0);
1033 }
1034
1035 if (block->branch_type != vtn_branch_type_none) {
1036 vtn_emit_branch(b, block->branch_type,
1037 switch_fall_var, has_switch_break);
1038 return;
1039 }
1040
1041 break;
1042 }
1043
1044 case vtn_cf_node_type_if: {
1045 struct vtn_if *vtn_if = vtn_cf_node_as_if(node);
1046 bool sw_break = false;
1047
1048 nir_if *nif =
1049 nir_push_if(&b->nb, vtn_get_nir_ssa(b, vtn_if->condition));
1050
1051 nif->control = vtn_selection_control(b, vtn_if);
1052
1053 if (vtn_if->then_type == vtn_branch_type_none) {
1054 vtn_emit_cf_list_structured(b, &vtn_if->then_body,
1055 switch_fall_var, &sw_break, handler);
1056 } else {
1057 vtn_emit_branch(b, vtn_if->then_type, switch_fall_var, &sw_break);
1058 }
1059
1060 nir_push_else(&b->nb, nif);
1061 if (vtn_if->else_type == vtn_branch_type_none) {
1062 vtn_emit_cf_list_structured(b, &vtn_if->else_body,
1063 switch_fall_var, &sw_break, handler);
1064 } else {
1065 vtn_emit_branch(b, vtn_if->else_type, switch_fall_var, &sw_break);
1066 }
1067
1068 nir_pop_if(&b->nb, nif);
1069
1070 /* If we encountered a switch break somewhere inside of the if,
1071 * then it would have been handled correctly by calling
1072 * emit_cf_list or emit_branch for the interrior. However, we
1073 * need to predicate everything following on wether or not we're
1074 * still going.
1075 */
1076 if (sw_break) {
1077 *has_switch_break = true;
1078 nir_push_if(&b->nb, nir_load_var(&b->nb, switch_fall_var));
1079 }
1080 break;
1081 }
1082
1083 case vtn_cf_node_type_loop: {
1084 struct vtn_loop *vtn_loop = vtn_cf_node_as_loop(node);
1085
1086 nir_loop *loop = nir_push_loop(&b->nb);
1087 loop->control = vtn_loop_control(b, vtn_loop);
1088
1089 vtn_emit_cf_list_structured(b, &vtn_loop->body, NULL, NULL, handler);
1090
1091 if (!list_is_empty(&vtn_loop->cont_body)) {
1092 /* If we have a non-trivial continue body then we need to put
1093 * it at the beginning of the loop with a flag to ensure that
1094 * it doesn't get executed in the first iteration.
1095 */
1096 nir_variable *do_cont =
1097 nir_local_variable_create(b->nb.impl, glsl_bool_type(), "cont");
1098
1099 b->nb.cursor = nir_before_cf_node(&loop->cf_node);
1100 nir_store_var(&b->nb, do_cont, nir_imm_false(&b->nb), 1);
1101
1102 b->nb.cursor = nir_before_cf_list(&loop->body);
1103
1104 nir_if *cont_if =
1105 nir_push_if(&b->nb, nir_load_var(&b->nb, do_cont));
1106
1107 vtn_emit_cf_list_structured(b, &vtn_loop->cont_body, NULL, NULL,
1108 handler);
1109
1110 nir_pop_if(&b->nb, cont_if);
1111
1112 nir_store_var(&b->nb, do_cont, nir_imm_true(&b->nb), 1);
1113
1114 b->has_loop_continue = true;
1115 }
1116
1117 nir_pop_loop(&b->nb, loop);
1118 break;
1119 }
1120
1121 case vtn_cf_node_type_switch: {
1122 struct vtn_switch *vtn_switch = vtn_cf_node_as_switch(node);
1123
1124 /* Before we can emit anything, we need to sort the list of cases in
1125 * fall-through order.
1126 */
1127 vtn_switch_order_cases(vtn_switch);
1128
1129 /* First, we create a variable to keep track of whether or not the
1130 * switch is still going at any given point. Any switch breaks
1131 * will set this variable to false.
1132 */
1133 nir_variable *fall_var =
1134 nir_local_variable_create(b->nb.impl, glsl_bool_type(), "fall");
1135 nir_store_var(&b->nb, fall_var, nir_imm_false(&b->nb), 1);
1136
1137 nir_ssa_def *sel = vtn_get_nir_ssa(b, vtn_switch->selector);
1138
1139 /* Now we can walk the list of cases and actually emit code */
1140 vtn_foreach_cf_node(case_node, &vtn_switch->cases) {
1141 struct vtn_case *cse = vtn_cf_node_as_case(case_node);
1142
1143 /* Figure out the condition */
1144 nir_ssa_def *cond =
1145 vtn_switch_case_condition(b, vtn_switch, sel, cse);
1146 /* Take fallthrough into account */
1147 cond = nir_ior(&b->nb, cond, nir_load_var(&b->nb, fall_var));
1148
1149 nir_if *case_if = nir_push_if(&b->nb, cond);
1150
1151 bool has_break = false;
1152 nir_store_var(&b->nb, fall_var, nir_imm_true(&b->nb), 1);
1153 vtn_emit_cf_list_structured(b, &cse->body, fall_var, &has_break,
1154 handler);
1155 (void)has_break; /* We don't care */
1156
1157 nir_pop_if(&b->nb, case_if);
1158 }
1159
1160 break;
1161 }
1162
1163 default:
1164 vtn_fail("Invalid CF node type");
1165 }
1166 }
1167 }
1168
1169 void
1170 vtn_function_emit(struct vtn_builder *b, struct vtn_function *func,
1171 vtn_instruction_handler instruction_handler)
1172 {
1173 nir_builder_init(&b->nb, func->impl);
1174 b->func = func;
1175 b->nb.cursor = nir_after_cf_list(&func->impl->body);
1176 b->nb.exact = b->exact;
1177 b->has_loop_continue = false;
1178 b->phi_table = _mesa_pointer_hash_table_create(b);
1179
1180 vtn_emit_cf_list_structured(b, &func->body, NULL, NULL, instruction_handler);
1181
1182 vtn_foreach_instruction(b, func->start_block->label, func->end,
1183 vtn_handle_phi_second_pass);
1184
1185 nir_rematerialize_derefs_in_use_blocks_impl(func->impl);
1186
1187 /* Continue blocks for loops get inserted before the body of the loop
1188 * but instructions in the continue may use SSA defs in the loop body.
1189 * Therefore, we need to repair SSA to insert the needed phi nodes.
1190 */
1191 if (b->has_loop_continue)
1192 nir_repair_ssa_impl(func->impl);
1193
1194 func->emitted = true;
1195 }