1/*
2 * Copyright © 2019 Valve 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
25#include "aco_builder.h"
26#include "aco_ir.h"
27
28#include <algorithm>
29#include <map>
30#include <vector>
31
32namespace aco {
33
34enum class pred_defined : uint8_t {
35   undef = 0,
36   const_1 = 1,
37   const_0 = 2,
38   temp = 3,
39   zero = 4, /* all disabled lanes are zero'd out */
40};
41MESA_DEFINE_CPP_ENUM_BITFIELD_OPERATORS(pred_defined);
42
43struct ssa_state {
44   bool checked_preds_for_uniform;
45   bool all_preds_uniform;
46   unsigned loop_nest_depth;
47
48   std::vector<pred_defined> any_pred_defined;
49   std::vector<bool> visited;
50   std::vector<Operand> outputs; /* the output per block */
51};
52
53Operand
54get_ssa(Program* program, unsigned block_idx, ssa_state* state, bool input)
55{
56   if (!input) {
57      if (state->visited[block_idx])
58         return state->outputs[block_idx];
59
60      /* otherwise, output == input */
61      Operand output = get_ssa(program, block_idx, state, true);
62      state->visited[block_idx] = true;
63      state->outputs[block_idx] = output;
64      return output;
65   }
66
67   /* retrieve the Operand by checking the predecessors */
68   if (state->any_pred_defined[block_idx] == pred_defined::undef)
69      return Operand(program->lane_mask);
70
71   Block& block = program->blocks[block_idx];
72   size_t pred = block.linear_preds.size();
73   Operand op;
74   if (block.loop_nest_depth < state->loop_nest_depth) {
75      /* loop-carried value for loop exit phis */
76      op = Operand::zero(program->lane_mask.bytes());
77   } else if (block.loop_nest_depth > state->loop_nest_depth || pred == 1 ||
78              block.kind & block_kind_loop_exit) {
79      op = get_ssa(program, block.linear_preds[0], state, false);
80   } else {
81      assert(pred > 1);
82      bool previously_visited = state->visited[block_idx];
83      /* potential recursion: anchor at loop header */
84      if (block.kind & block_kind_loop_header) {
85         assert(!previously_visited);
86         previously_visited = true;
87         state->visited[block_idx] = true;
88         state->outputs[block_idx] = Operand(Temp(program->allocateTmp(program->lane_mask)));
89      }
90
91      /* collect predecessor output operands */
92      std::vector<Operand> ops(pred);
93      for (unsigned i = 0; i < pred; i++)
94         ops[i] = get_ssa(program, block.linear_preds[i], state, false);
95
96      /* check triviality */
97      if (std::all_of(ops.begin() + 1, ops.end(), [&](Operand same) { return same == ops[0]; }))
98         return ops[0];
99
100      /* Return if this was handled in a recursive call by a loop header phi */
101      if (!previously_visited && state->visited[block_idx])
102         return state->outputs[block_idx];
103
104      if (block.kind & block_kind_loop_header)
105         op = state->outputs[block_idx];
106      else
107         op = Operand(Temp(program->allocateTmp(program->lane_mask)));
108
109      /* create phi */
110      aco_ptr<Pseudo_instruction> phi{
111         create_instruction<Pseudo_instruction>(aco_opcode::p_linear_phi, Format::PSEUDO, pred, 1)};
112      for (unsigned i = 0; i < pred; i++)
113         phi->operands[i] = ops[i];
114      phi->definitions[0] = Definition(op.getTemp());
115      block.instructions.emplace(block.instructions.begin(), std::move(phi));
116   }
117
118   assert(op.size() == program->lane_mask.size());
119   return op;
120}
121
122void
123insert_before_logical_end(Block* block, aco_ptr<Instruction> instr)
124{
125   auto IsLogicalEnd = [](const aco_ptr<Instruction>& inst) -> bool
126   { return inst->opcode == aco_opcode::p_logical_end; };
127   auto it = std::find_if(block->instructions.crbegin(), block->instructions.crend(), IsLogicalEnd);
128
129   if (it == block->instructions.crend()) {
130      assert(block->instructions.back()->isBranch());
131      block->instructions.insert(std::prev(block->instructions.end()), std::move(instr));
132   } else {
133      block->instructions.insert(std::prev(it.base()), std::move(instr));
134   }
135}
136
137void
138build_merge_code(Program* program, ssa_state* state, Block* block, Operand cur)
139{
140   unsigned block_idx = block->index;
141   Definition dst = Definition(state->outputs[block_idx].getTemp());
142   Operand prev = get_ssa(program, block_idx, state, true);
143   if (cur.isUndefined())
144      cur = Operand::zero(program->lane_mask.bytes());
145
146   Builder bld(program);
147   auto IsLogicalEnd = [](const aco_ptr<Instruction>& instr) -> bool
148   { return instr->opcode == aco_opcode::p_logical_end; };
149   auto it = std::find_if(block->instructions.rbegin(), block->instructions.rend(), IsLogicalEnd);
150   assert(it != block->instructions.rend());
151   bld.reset(&block->instructions, std::prev(it.base()));
152
153   pred_defined defined = state->any_pred_defined[block_idx];
154   if (defined == pred_defined::undef) {
155      return;
156   } else if (defined == pred_defined::const_0) {
157      bld.sop2(Builder::s_and, dst, bld.def(s1, scc), cur, Operand(exec, bld.lm));
158      return;
159   } else if (defined == pred_defined::const_1) {
160      bld.sop2(Builder::s_orn2, dst, bld.def(s1, scc), cur, Operand(exec, bld.lm));
161      return;
162   }
163
164   assert(prev.isTemp());
165   /* simpler sequence in case prev has only zeros in disabled lanes */
166   if ((defined & pred_defined::zero) == pred_defined::zero) {
167      if (cur.isConstant()) {
168         if (!cur.constantValue()) {
169            bld.copy(dst, prev);
170            return;
171         }
172         cur = Operand(exec, bld.lm);
173      } else {
174         cur =
175            bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), cur, Operand(exec, bld.lm));
176      }
177      bld.sop2(Builder::s_or, dst, bld.def(s1, scc), prev, cur);
178      return;
179   }
180
181   if (cur.isConstant()) {
182      if (cur.constantValue())
183         bld.sop2(Builder::s_or, dst, bld.def(s1, scc), prev, Operand(exec, bld.lm));
184      else
185         bld.sop2(Builder::s_andn2, dst, bld.def(s1, scc), prev, Operand(exec, bld.lm));
186      return;
187   }
188   prev =
189      bld.sop2(Builder::s_andn2, bld.def(bld.lm), bld.def(s1, scc), prev, Operand(exec, bld.lm));
190   cur = bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), cur, Operand(exec, bld.lm));
191   bld.sop2(Builder::s_or, dst, bld.def(s1, scc), prev, cur);
192   return;
193}
194
195void
196init_any_pred_defined(Program* program, ssa_state* state, Block* block, aco_ptr<Instruction>& phi)
197{
198   std::fill(state->any_pred_defined.begin(), state->any_pred_defined.end(), pred_defined::undef);
199   for (unsigned i = 0; i < block->logical_preds.size(); i++) {
200      if (phi->operands[i].isUndefined())
201         continue;
202      pred_defined defined = pred_defined::temp;
203      if (phi->operands[i].isConstant())
204         defined = phi->operands[i].constantValue() ? pred_defined::const_1 : pred_defined::const_0;
205      for (unsigned succ : program->blocks[block->logical_preds[i]].linear_succs)
206         state->any_pred_defined[succ] |= defined;
207   }
208
209   unsigned start = block->logical_preds[0];
210   unsigned end = block->index;
211
212   /* for loop exit phis, start at the loop header */
213   if (block->kind & block_kind_loop_exit) {
214      while (program->blocks[start - 1].loop_nest_depth >= state->loop_nest_depth)
215         start--;
216      /* If the loop-header has a back-edge, we need to insert a phi.
217       * This will contain a defined value */
218      if (program->blocks[start].linear_preds.size() > 1)
219         state->any_pred_defined[start] = pred_defined::temp;
220   }
221   /* for loop header phis, end at the loop exit */
222   if (block->kind & block_kind_loop_header) {
223      while (program->blocks[end].loop_nest_depth >= state->loop_nest_depth)
224         end++;
225      /* don't propagate the incoming value */
226      state->any_pred_defined[block->index] = pred_defined::undef;
227   }
228
229   /* add dominating zero: this allows to emit simpler merge sequences
230    * if we can ensure that all disabled lanes are always zero on incoming values */
231   // TODO: find more occasions where pred_defined::zero is beneficial (e.g. with 2+ temp merges)
232   if (block->kind & block_kind_loop_exit) {
233      /* zero the loop-carried variable */
234      if (program->blocks[start].linear_preds.size() > 1) {
235         state->any_pred_defined[start] |= pred_defined::zero;
236         // TODO: emit this zero explicitly
237         state->any_pred_defined[start - 1] = pred_defined::const_0;
238      }
239   }
240
241   for (unsigned j = start; j < end; j++) {
242      if (state->any_pred_defined[j] == pred_defined::undef)
243         continue;
244      for (unsigned succ : program->blocks[j].linear_succs)
245         state->any_pred_defined[succ] |= state->any_pred_defined[j];
246   }
247
248   state->any_pred_defined[block->index] = pred_defined::undef;
249}
250
251void
252lower_divergent_bool_phi(Program* program, ssa_state* state, Block* block,
253                         aco_ptr<Instruction>& phi)
254{
255   Builder bld(program);
256
257   if (!state->checked_preds_for_uniform) {
258      state->all_preds_uniform = !(block->kind & block_kind_merge) &&
259                                 block->linear_preds.size() == block->logical_preds.size();
260      for (unsigned pred : block->logical_preds)
261         state->all_preds_uniform =
262            state->all_preds_uniform && (program->blocks[pred].kind & block_kind_uniform);
263      state->checked_preds_for_uniform = true;
264   }
265
266   if (state->all_preds_uniform) {
267      phi->opcode = aco_opcode::p_linear_phi;
268      return;
269   }
270
271   /* do this here to avoid resizing in case of no boolean phis */
272   state->visited.resize(program->blocks.size());
273   state->outputs.resize(program->blocks.size());
274   state->any_pred_defined.resize(program->blocks.size());
275   state->loop_nest_depth = block->loop_nest_depth;
276   if (block->kind & block_kind_loop_exit)
277      state->loop_nest_depth += 1;
278   std::fill(state->visited.begin(), state->visited.end(), false);
279   init_any_pred_defined(program, state, block, phi);
280
281   for (unsigned i = 0; i < phi->operands.size(); i++) {
282      unsigned pred = block->logical_preds[i];
283      if (state->any_pred_defined[pred] != pred_defined::undef)
284         state->outputs[pred] = Operand(bld.tmp(bld.lm));
285      else
286         state->outputs[pred] = phi->operands[i];
287      assert(state->outputs[pred].size() == bld.lm.size());
288      state->visited[pred] = true;
289   }
290
291   for (unsigned i = 0; i < phi->operands.size(); i++)
292      build_merge_code(program, state, &program->blocks[block->logical_preds[i]], phi->operands[i]);
293
294   unsigned num_preds = block->linear_preds.size();
295   if (phi->operands.size() != num_preds) {
296      Pseudo_instruction* new_phi{create_instruction<Pseudo_instruction>(
297         aco_opcode::p_linear_phi, Format::PSEUDO, num_preds, 1)};
298      new_phi->definitions[0] = phi->definitions[0];
299      phi.reset(new_phi);
300   } else {
301      phi->opcode = aco_opcode::p_linear_phi;
302   }
303   assert(phi->operands.size() == num_preds);
304
305   for (unsigned i = 0; i < num_preds; i++)
306      phi->operands[i] = get_ssa(program, block->linear_preds[i], state, false);
307
308   return;
309}
310
311void
312lower_subdword_phis(Program* program, Block* block, aco_ptr<Instruction>& phi)
313{
314   Builder bld(program);
315   for (unsigned i = 0; i < phi->operands.size(); i++) {
316      if (phi->operands[i].isUndefined())
317         continue;
318      if (phi->operands[i].regClass() == phi->definitions[0].regClass())
319         continue;
320
321      assert(phi->operands[i].isTemp());
322      Block* pred = &program->blocks[block->logical_preds[i]];
323      Temp phi_src = phi->operands[i].getTemp();
324
325      assert(phi_src.regClass().type() == RegType::sgpr);
326      Temp tmp = bld.tmp(RegClass(RegType::vgpr, phi_src.size()));
327      insert_before_logical_end(pred, bld.copy(Definition(tmp), phi_src).get_ptr());
328      Temp new_phi_src = bld.tmp(phi->definitions[0].regClass());
329      insert_before_logical_end(pred, bld.pseudo(aco_opcode::p_extract_vector,
330                                                 Definition(new_phi_src), tmp, Operand::zero())
331                                         .get_ptr());
332
333      phi->operands[i].setTemp(new_phi_src);
334   }
335   return;
336}
337
338void
339lower_phis(Program* program)
340{
341   ssa_state state;
342
343   for (Block& block : program->blocks) {
344      state.checked_preds_for_uniform = false;
345      for (aco_ptr<Instruction>& phi : block.instructions) {
346         if (phi->opcode == aco_opcode::p_phi) {
347            assert(program->wave_size == 64 ? phi->definitions[0].regClass() != s1
348                                            : phi->definitions[0].regClass() != s2);
349            if (phi->definitions[0].regClass() == program->lane_mask)
350               lower_divergent_bool_phi(program, &state, &block, phi);
351            else if (phi->definitions[0].regClass().is_subdword())
352               lower_subdword_phis(program, &block, phi);
353         } else if (!is_phi(phi)) {
354            break;
355         }
356      }
357   }
358}
359
360} // namespace aco
361