radeonsi: use ctx->ac.builder
[mesa.git] / src / gallium / drivers / radeonsi / si_shader_tgsi_setup.c
1 /*
2 * Copyright 2016 Advanced Micro Devices, Inc.
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 * on the rights to use, copy, modify, merge, publish, distribute, sub
8 * license, and/or sell copies of the Software, and to permit persons to whom
9 * the 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 NON-INFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
19 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
20 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21 * USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23
24 #include "si_shader_internal.h"
25 #include "si_pipe.h"
26
27 #include "gallivm/lp_bld_const.h"
28 #include "gallivm/lp_bld_gather.h"
29 #include "gallivm/lp_bld_flow.h"
30 #include "gallivm/lp_bld_init.h"
31 #include "gallivm/lp_bld_intr.h"
32 #include "gallivm/lp_bld_misc.h"
33 #include "gallivm/lp_bld_swizzle.h"
34 #include "tgsi/tgsi_info.h"
35 #include "tgsi/tgsi_parse.h"
36 #include "util/u_math.h"
37 #include "util/u_memory.h"
38 #include "util/u_debug.h"
39
40 #include <stdio.h>
41 #include <llvm-c/Transforms/IPO.h>
42 #include <llvm-c/Transforms/Scalar.h>
43
44 /* Data for if/else/endif and bgnloop/endloop control flow structures.
45 */
46 struct si_llvm_flow {
47 /* Loop exit or next part of if/else/endif. */
48 LLVMBasicBlockRef next_block;
49 LLVMBasicBlockRef loop_entry_block;
50 };
51
52 enum si_llvm_calling_convention {
53 RADEON_LLVM_AMDGPU_VS = 87,
54 RADEON_LLVM_AMDGPU_GS = 88,
55 RADEON_LLVM_AMDGPU_PS = 89,
56 RADEON_LLVM_AMDGPU_CS = 90,
57 RADEON_LLVM_AMDGPU_HS = 93,
58 };
59
60 void si_llvm_add_attribute(LLVMValueRef F, const char *name, int value)
61 {
62 char str[16];
63
64 snprintf(str, sizeof(str), "%i", value);
65 LLVMAddTargetDependentFunctionAttr(F, name, str);
66 }
67
68 struct si_llvm_diagnostics {
69 struct pipe_debug_callback *debug;
70 unsigned retval;
71 };
72
73 static void si_diagnostic_handler(LLVMDiagnosticInfoRef di, void *context)
74 {
75 struct si_llvm_diagnostics *diag = (struct si_llvm_diagnostics *)context;
76 LLVMDiagnosticSeverity severity = LLVMGetDiagInfoSeverity(di);
77 char *description = LLVMGetDiagInfoDescription(di);
78 const char *severity_str = NULL;
79
80 switch (severity) {
81 case LLVMDSError:
82 severity_str = "error";
83 break;
84 case LLVMDSWarning:
85 severity_str = "warning";
86 break;
87 case LLVMDSRemark:
88 severity_str = "remark";
89 break;
90 case LLVMDSNote:
91 severity_str = "note";
92 break;
93 default:
94 severity_str = "unknown";
95 }
96
97 pipe_debug_message(diag->debug, SHADER_INFO,
98 "LLVM diagnostic (%s): %s", severity_str, description);
99
100 if (severity == LLVMDSError) {
101 diag->retval = 1;
102 fprintf(stderr,"LLVM triggered Diagnostic Handler: %s\n", description);
103 }
104
105 LLVMDisposeMessage(description);
106 }
107
108 /**
109 * Compile an LLVM module to machine code.
110 *
111 * @returns 0 for success, 1 for failure
112 */
113 unsigned si_llvm_compile(LLVMModuleRef M, struct ac_shader_binary *binary,
114 LLVMTargetMachineRef tm,
115 struct pipe_debug_callback *debug)
116 {
117 struct si_llvm_diagnostics diag;
118 char *err;
119 LLVMContextRef llvm_ctx;
120 LLVMMemoryBufferRef out_buffer;
121 unsigned buffer_size;
122 const char *buffer_data;
123 LLVMBool mem_err;
124
125 diag.debug = debug;
126 diag.retval = 0;
127
128 /* Setup Diagnostic Handler*/
129 llvm_ctx = LLVMGetModuleContext(M);
130
131 LLVMContextSetDiagnosticHandler(llvm_ctx, si_diagnostic_handler, &diag);
132
133 /* Compile IR*/
134 mem_err = LLVMTargetMachineEmitToMemoryBuffer(tm, M, LLVMObjectFile, &err,
135 &out_buffer);
136
137 /* Process Errors/Warnings */
138 if (mem_err) {
139 fprintf(stderr, "%s: %s", __FUNCTION__, err);
140 pipe_debug_message(debug, SHADER_INFO,
141 "LLVM emit error: %s", err);
142 FREE(err);
143 diag.retval = 1;
144 goto out;
145 }
146
147 /* Extract Shader Code*/
148 buffer_size = LLVMGetBufferSize(out_buffer);
149 buffer_data = LLVMGetBufferStart(out_buffer);
150
151 if (!ac_elf_read(buffer_data, buffer_size, binary)) {
152 fprintf(stderr, "radeonsi: cannot read an ELF shader binary\n");
153 diag.retval = 1;
154 }
155
156 /* Clean up */
157 LLVMDisposeMemoryBuffer(out_buffer);
158
159 out:
160 if (diag.retval != 0)
161 pipe_debug_message(debug, SHADER_INFO, "LLVM compile failed");
162 return diag.retval;
163 }
164
165 LLVMTypeRef tgsi2llvmtype(struct lp_build_tgsi_context *bld_base,
166 enum tgsi_opcode_type type)
167 {
168 LLVMContextRef ctx = bld_base->base.gallivm->context;
169
170 switch (type) {
171 case TGSI_TYPE_UNSIGNED:
172 case TGSI_TYPE_SIGNED:
173 return LLVMInt32TypeInContext(ctx);
174 case TGSI_TYPE_UNSIGNED64:
175 case TGSI_TYPE_SIGNED64:
176 return LLVMInt64TypeInContext(ctx);
177 case TGSI_TYPE_DOUBLE:
178 return LLVMDoubleTypeInContext(ctx);
179 case TGSI_TYPE_UNTYPED:
180 case TGSI_TYPE_FLOAT:
181 return LLVMFloatTypeInContext(ctx);
182 default: break;
183 }
184 return 0;
185 }
186
187 LLVMValueRef bitcast(struct lp_build_tgsi_context *bld_base,
188 enum tgsi_opcode_type type, LLVMValueRef value)
189 {
190 struct si_shader_context *ctx = si_shader_context(bld_base);
191 LLVMTypeRef dst_type = tgsi2llvmtype(bld_base, type);
192
193 if (dst_type)
194 return LLVMBuildBitCast(ctx->ac.builder, value, dst_type, "");
195 else
196 return value;
197 }
198
199 /**
200 * Return a value that is equal to the given i32 \p index if it lies in [0,num)
201 * or an undefined value in the same interval otherwise.
202 */
203 LLVMValueRef si_llvm_bound_index(struct si_shader_context *ctx,
204 LLVMValueRef index,
205 unsigned num)
206 {
207 LLVMBuilderRef builder = ctx->ac.builder;
208 LLVMValueRef c_max = LLVMConstInt(ctx->i32, num - 1, 0);
209 LLVMValueRef cc;
210
211 if (util_is_power_of_two(num)) {
212 index = LLVMBuildAnd(builder, index, c_max, "");
213 } else {
214 /* In theory, this MAX pattern should result in code that is
215 * as good as the bit-wise AND above.
216 *
217 * In practice, LLVM generates worse code (at the time of
218 * writing), because its value tracking is not strong enough.
219 */
220 cc = LLVMBuildICmp(builder, LLVMIntULE, index, c_max, "");
221 index = LLVMBuildSelect(builder, cc, index, c_max, "");
222 }
223
224 return index;
225 }
226
227 static struct si_llvm_flow *
228 get_current_flow(struct si_shader_context *ctx)
229 {
230 if (ctx->flow_depth > 0)
231 return &ctx->flow[ctx->flow_depth - 1];
232 return NULL;
233 }
234
235 static struct si_llvm_flow *
236 get_innermost_loop(struct si_shader_context *ctx)
237 {
238 for (unsigned i = ctx->flow_depth; i > 0; --i) {
239 if (ctx->flow[i - 1].loop_entry_block)
240 return &ctx->flow[i - 1];
241 }
242 return NULL;
243 }
244
245 static struct si_llvm_flow *
246 push_flow(struct si_shader_context *ctx)
247 {
248 struct si_llvm_flow *flow;
249
250 if (ctx->flow_depth >= ctx->flow_depth_max) {
251 unsigned new_max = MAX2(ctx->flow_depth << 1, RADEON_LLVM_INITIAL_CF_DEPTH);
252 ctx->flow = REALLOC(ctx->flow,
253 ctx->flow_depth_max * sizeof(*ctx->flow),
254 new_max * sizeof(*ctx->flow));
255 ctx->flow_depth_max = new_max;
256 }
257
258 flow = &ctx->flow[ctx->flow_depth];
259 ctx->flow_depth++;
260
261 flow->next_block = NULL;
262 flow->loop_entry_block = NULL;
263 return flow;
264 }
265
266 static LLVMValueRef emit_swizzle(struct lp_build_tgsi_context *bld_base,
267 LLVMValueRef value,
268 unsigned swizzle_x,
269 unsigned swizzle_y,
270 unsigned swizzle_z,
271 unsigned swizzle_w)
272 {
273 struct si_shader_context *ctx = si_shader_context(bld_base);
274 LLVMValueRef swizzles[4];
275 LLVMTypeRef i32t =
276 LLVMInt32TypeInContext(bld_base->base.gallivm->context);
277
278 swizzles[0] = LLVMConstInt(i32t, swizzle_x, 0);
279 swizzles[1] = LLVMConstInt(i32t, swizzle_y, 0);
280 swizzles[2] = LLVMConstInt(i32t, swizzle_z, 0);
281 swizzles[3] = LLVMConstInt(i32t, swizzle_w, 0);
282
283 return LLVMBuildShuffleVector(ctx->ac.builder,
284 value,
285 LLVMGetUndef(LLVMTypeOf(value)),
286 LLVMConstVector(swizzles, 4), "");
287 }
288
289 /**
290 * Return the description of the array covering the given temporary register
291 * index.
292 */
293 static unsigned
294 get_temp_array_id(struct lp_build_tgsi_context *bld_base,
295 unsigned reg_index,
296 const struct tgsi_ind_register *reg)
297 {
298 struct si_shader_context *ctx = si_shader_context(bld_base);
299 unsigned num_arrays = ctx->bld_base.info->array_max[TGSI_FILE_TEMPORARY];
300 unsigned i;
301
302 if (reg && reg->ArrayID > 0 && reg->ArrayID <= num_arrays)
303 return reg->ArrayID;
304
305 for (i = 0; i < num_arrays; i++) {
306 const struct tgsi_array_info *array = &ctx->temp_arrays[i];
307
308 if (reg_index >= array->range.First && reg_index <= array->range.Last)
309 return i + 1;
310 }
311
312 return 0;
313 }
314
315 static struct tgsi_declaration_range
316 get_array_range(struct lp_build_tgsi_context *bld_base,
317 unsigned File, unsigned reg_index,
318 const struct tgsi_ind_register *reg)
319 {
320 struct si_shader_context *ctx = si_shader_context(bld_base);
321 struct tgsi_declaration_range range;
322
323 if (File == TGSI_FILE_TEMPORARY) {
324 unsigned array_id = get_temp_array_id(bld_base, reg_index, reg);
325 if (array_id)
326 return ctx->temp_arrays[array_id - 1].range;
327 }
328
329 range.First = 0;
330 range.Last = bld_base->info->file_max[File];
331 return range;
332 }
333
334 /**
335 * For indirect registers, construct a pointer directly to the requested
336 * element using getelementptr if possible.
337 *
338 * Returns NULL if the insertelement/extractelement fallback for array access
339 * must be used.
340 */
341 static LLVMValueRef
342 get_pointer_into_array(struct si_shader_context *ctx,
343 unsigned file,
344 unsigned swizzle,
345 unsigned reg_index,
346 const struct tgsi_ind_register *reg_indirect)
347 {
348 unsigned array_id;
349 struct tgsi_array_info *array;
350 LLVMBuilderRef builder = ctx->ac.builder;
351 LLVMValueRef idxs[2];
352 LLVMValueRef index;
353 LLVMValueRef alloca;
354
355 if (file != TGSI_FILE_TEMPORARY)
356 return NULL;
357
358 array_id = get_temp_array_id(&ctx->bld_base, reg_index, reg_indirect);
359 if (!array_id)
360 return NULL;
361
362 alloca = ctx->temp_array_allocas[array_id - 1];
363 if (!alloca)
364 return NULL;
365
366 array = &ctx->temp_arrays[array_id - 1];
367
368 if (!(array->writemask & (1 << swizzle)))
369 return ctx->undef_alloca;
370
371 index = si_get_indirect_index(ctx, reg_indirect, 1,
372 reg_index - ctx->temp_arrays[array_id - 1].range.First);
373
374 /* Ensure that the index is within a valid range, to guard against
375 * VM faults and overwriting critical data (e.g. spilled resource
376 * descriptors).
377 *
378 * TODO It should be possible to avoid the additional instructions
379 * if LLVM is changed so that it guarantuees:
380 * 1. the scratch space descriptor isolates the current wave (this
381 * could even save the scratch offset SGPR at the cost of an
382 * additional SALU instruction)
383 * 2. the memory for allocas must be allocated at the _end_ of the
384 * scratch space (after spilled registers)
385 */
386 index = si_llvm_bound_index(ctx, index, array->range.Last - array->range.First + 1);
387
388 index = LLVMBuildMul(
389 builder, index,
390 LLVMConstInt(ctx->i32, util_bitcount(array->writemask), 0),
391 "");
392 index = LLVMBuildAdd(
393 builder, index,
394 LLVMConstInt(ctx->i32,
395 util_bitcount(array->writemask & ((1 << swizzle) - 1)), 0),
396 "");
397 idxs[0] = ctx->i32_0;
398 idxs[1] = index;
399 return LLVMBuildGEP(ctx->ac.builder, alloca, idxs, 2, "");
400 }
401
402 LLVMValueRef
403 si_llvm_emit_fetch_64bit(struct lp_build_tgsi_context *bld_base,
404 enum tgsi_opcode_type type,
405 LLVMValueRef ptr,
406 LLVMValueRef ptr2)
407 {
408 struct si_shader_context *ctx = si_shader_context(bld_base);
409 LLVMValueRef result;
410
411 result = LLVMGetUndef(LLVMVectorType(LLVMIntTypeInContext(bld_base->base.gallivm->context, 32), bld_base->base.type.length * 2));
412
413 result = LLVMBuildInsertElement(ctx->ac.builder,
414 result,
415 ac_to_integer(&ctx->ac, ptr),
416 ctx->i32_0, "");
417 result = LLVMBuildInsertElement(ctx->ac.builder,
418 result,
419 ac_to_integer(&ctx->ac, ptr2),
420 ctx->i32_1, "");
421 return bitcast(bld_base, type, result);
422 }
423
424 static LLVMValueRef
425 emit_array_fetch(struct lp_build_tgsi_context *bld_base,
426 unsigned File, enum tgsi_opcode_type type,
427 struct tgsi_declaration_range range,
428 unsigned swizzle)
429 {
430 struct si_shader_context *ctx = si_shader_context(bld_base);
431 unsigned i, size = range.Last - range.First + 1;
432 LLVMTypeRef vec = LLVMVectorType(tgsi2llvmtype(bld_base, type), size);
433 LLVMValueRef result = LLVMGetUndef(vec);
434
435 struct tgsi_full_src_register tmp_reg = {};
436 tmp_reg.Register.File = File;
437
438 for (i = 0; i < size; ++i) {
439 tmp_reg.Register.Index = i + range.First;
440 LLVMValueRef temp = si_llvm_emit_fetch(bld_base, &tmp_reg, type, swizzle);
441 result = LLVMBuildInsertElement(ctx->ac.builder, result, temp,
442 LLVMConstInt(ctx->i32, i, 0), "array_vector");
443 }
444 return result;
445 }
446
447 static LLVMValueRef
448 load_value_from_array(struct lp_build_tgsi_context *bld_base,
449 unsigned file,
450 enum tgsi_opcode_type type,
451 unsigned swizzle,
452 unsigned reg_index,
453 const struct tgsi_ind_register *reg_indirect)
454 {
455 struct si_shader_context *ctx = si_shader_context(bld_base);
456 LLVMBuilderRef builder = ctx->ac.builder;
457 LLVMValueRef ptr;
458
459 ptr = get_pointer_into_array(ctx, file, swizzle, reg_index, reg_indirect);
460 if (ptr) {
461 LLVMValueRef val = LLVMBuildLoad(builder, ptr, "");
462 if (tgsi_type_is_64bit(type)) {
463 LLVMValueRef ptr_hi, val_hi;
464 ptr_hi = LLVMBuildGEP(builder, ptr, &ctx->i32_1, 1, "");
465 val_hi = LLVMBuildLoad(builder, ptr_hi, "");
466 val = si_llvm_emit_fetch_64bit(bld_base, type, val, val_hi);
467 }
468
469 return val;
470 } else {
471 struct tgsi_declaration_range range =
472 get_array_range(bld_base, file, reg_index, reg_indirect);
473 LLVMValueRef index =
474 si_get_indirect_index(ctx, reg_indirect, 1, reg_index - range.First);
475 LLVMValueRef array =
476 emit_array_fetch(bld_base, file, type, range, swizzle);
477 return LLVMBuildExtractElement(builder, array, index, "");
478 }
479 }
480
481 static void
482 store_value_to_array(struct lp_build_tgsi_context *bld_base,
483 LLVMValueRef value,
484 unsigned file,
485 unsigned chan_index,
486 unsigned reg_index,
487 const struct tgsi_ind_register *reg_indirect)
488 {
489 struct si_shader_context *ctx = si_shader_context(bld_base);
490 LLVMBuilderRef builder = ctx->ac.builder;
491 LLVMValueRef ptr;
492
493 ptr = get_pointer_into_array(ctx, file, chan_index, reg_index, reg_indirect);
494 if (ptr) {
495 LLVMBuildStore(builder, value, ptr);
496 } else {
497 unsigned i, size;
498 struct tgsi_declaration_range range = get_array_range(bld_base, file, reg_index, reg_indirect);
499 LLVMValueRef index = si_get_indirect_index(ctx, reg_indirect, 1, reg_index - range.First);
500 LLVMValueRef array =
501 emit_array_fetch(bld_base, file, TGSI_TYPE_FLOAT, range, chan_index);
502 LLVMValueRef temp_ptr;
503
504 array = LLVMBuildInsertElement(builder, array, value, index, "");
505
506 size = range.Last - range.First + 1;
507 for (i = 0; i < size; ++i) {
508 switch(file) {
509 case TGSI_FILE_OUTPUT:
510 temp_ptr = ctx->outputs[i + range.First][chan_index];
511 break;
512
513 case TGSI_FILE_TEMPORARY:
514 if (range.First + i >= ctx->temps_count)
515 continue;
516 temp_ptr = ctx->temps[(i + range.First) * TGSI_NUM_CHANNELS + chan_index];
517 break;
518
519 default:
520 continue;
521 }
522 value = LLVMBuildExtractElement(builder, array,
523 LLVMConstInt(ctx->i32, i, 0), "");
524 LLVMBuildStore(builder, value, temp_ptr);
525 }
526 }
527 }
528
529 /* If this is true, preload FS inputs at the beginning of shaders. Otherwise,
530 * reload them at each use. This must be true if the shader is using
531 * derivatives and KILL, because KILL can leave the WQM and then a lazy
532 * input load isn't in the WQM anymore.
533 */
534 static bool si_preload_fs_inputs(struct si_shader_context *ctx)
535 {
536 struct si_shader_selector *sel = ctx->shader->selector;
537
538 return sel->info.uses_derivatives &&
539 sel->info.uses_kill;
540 }
541
542 static LLVMValueRef
543 get_output_ptr(struct lp_build_tgsi_context *bld_base, unsigned index,
544 unsigned chan)
545 {
546 struct si_shader_context *ctx = si_shader_context(bld_base);
547
548 assert(index <= ctx->bld_base.info->file_max[TGSI_FILE_OUTPUT]);
549 return ctx->outputs[index][chan];
550 }
551
552 LLVMValueRef si_llvm_emit_fetch(struct lp_build_tgsi_context *bld_base,
553 const struct tgsi_full_src_register *reg,
554 enum tgsi_opcode_type type,
555 unsigned swizzle)
556 {
557 struct si_shader_context *ctx = si_shader_context(bld_base);
558 LLVMBuilderRef builder = ctx->ac.builder;
559 LLVMValueRef result = NULL, ptr, ptr2;
560
561 if (swizzle == ~0) {
562 LLVMValueRef values[TGSI_NUM_CHANNELS];
563 unsigned chan;
564 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
565 values[chan] = si_llvm_emit_fetch(bld_base, reg, type, chan);
566 }
567 return lp_build_gather_values(&ctx->gallivm, values,
568 TGSI_NUM_CHANNELS);
569 }
570
571 if (reg->Register.Indirect) {
572 LLVMValueRef load = load_value_from_array(bld_base, reg->Register.File, type,
573 swizzle, reg->Register.Index, &reg->Indirect);
574 return bitcast(bld_base, type, load);
575 }
576
577 switch(reg->Register.File) {
578 case TGSI_FILE_IMMEDIATE: {
579 LLVMTypeRef ctype = tgsi2llvmtype(bld_base, type);
580 if (tgsi_type_is_64bit(type)) {
581 result = LLVMGetUndef(LLVMVectorType(ctx->i32, bld_base->base.type.length * 2));
582 result = LLVMConstInsertElement(result,
583 ctx->imms[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle],
584 ctx->i32_0);
585 result = LLVMConstInsertElement(result,
586 ctx->imms[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle + 1],
587 ctx->i32_1);
588 return LLVMConstBitCast(result, ctype);
589 } else {
590 return LLVMConstBitCast(ctx->imms[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle], ctype);
591 }
592 }
593
594 case TGSI_FILE_INPUT: {
595 unsigned index = reg->Register.Index;
596 LLVMValueRef input[4];
597
598 /* I don't think doing this for vertex shaders is beneficial.
599 * For those, we want to make sure the VMEM loads are executed
600 * only once. Fragment shaders don't care much, because
601 * v_interp instructions are much cheaper than VMEM loads.
602 */
603 if (!si_preload_fs_inputs(ctx) &&
604 ctx->bld_base.info->processor == PIPE_SHADER_FRAGMENT)
605 ctx->load_input(ctx, index, &ctx->input_decls[index], input);
606 else
607 memcpy(input, &ctx->inputs[index * 4], sizeof(input));
608
609 result = input[swizzle];
610
611 if (tgsi_type_is_64bit(type)) {
612 ptr = result;
613 ptr2 = input[swizzle + 1];
614 return si_llvm_emit_fetch_64bit(bld_base, type, ptr, ptr2);
615 }
616 break;
617 }
618
619 case TGSI_FILE_TEMPORARY:
620 if (reg->Register.Index >= ctx->temps_count)
621 return LLVMGetUndef(tgsi2llvmtype(bld_base, type));
622 ptr = ctx->temps[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle];
623 if (tgsi_type_is_64bit(type)) {
624 ptr2 = ctx->temps[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle + 1];
625 return si_llvm_emit_fetch_64bit(bld_base, type,
626 LLVMBuildLoad(builder, ptr, ""),
627 LLVMBuildLoad(builder, ptr2, ""));
628 }
629 result = LLVMBuildLoad(builder, ptr, "");
630 break;
631
632 case TGSI_FILE_OUTPUT:
633 ptr = get_output_ptr(bld_base, reg->Register.Index, swizzle);
634 if (tgsi_type_is_64bit(type)) {
635 ptr2 = get_output_ptr(bld_base, reg->Register.Index, swizzle + 1);
636 return si_llvm_emit_fetch_64bit(bld_base, type,
637 LLVMBuildLoad(builder, ptr, ""),
638 LLVMBuildLoad(builder, ptr2, ""));
639 }
640 result = LLVMBuildLoad(builder, ptr, "");
641 break;
642
643 default:
644 return LLVMGetUndef(tgsi2llvmtype(bld_base, type));
645 }
646
647 return bitcast(bld_base, type, result);
648 }
649
650 static LLVMValueRef fetch_system_value(struct lp_build_tgsi_context *bld_base,
651 const struct tgsi_full_src_register *reg,
652 enum tgsi_opcode_type type,
653 unsigned swizzle)
654 {
655 struct si_shader_context *ctx = si_shader_context(bld_base);
656 LLVMBuilderRef builder = ctx->ac.builder;
657 LLVMValueRef cval = ctx->system_values[reg->Register.Index];
658
659 if (tgsi_type_is_64bit(type)) {
660 LLVMValueRef lo, hi;
661
662 assert(swizzle == 0 || swizzle == 2);
663
664 lo = LLVMBuildExtractElement(
665 builder, cval, LLVMConstInt(ctx->i32, swizzle, 0), "");
666 hi = LLVMBuildExtractElement(
667 builder, cval, LLVMConstInt(ctx->i32, swizzle + 1, 0), "");
668
669 return si_llvm_emit_fetch_64bit(bld_base, type, lo, hi);
670 }
671
672 if (LLVMGetTypeKind(LLVMTypeOf(cval)) == LLVMVectorTypeKind) {
673 cval = LLVMBuildExtractElement(
674 builder, cval, LLVMConstInt(ctx->i32, swizzle, 0), "");
675 } else {
676 assert(swizzle == 0);
677 }
678
679 return bitcast(bld_base, type, cval);
680 }
681
682 static void emit_declaration(struct lp_build_tgsi_context *bld_base,
683 const struct tgsi_full_declaration *decl)
684 {
685 struct si_shader_context *ctx = si_shader_context(bld_base);
686 LLVMBuilderRef builder = ctx->ac.builder;
687 unsigned first, last, i;
688 switch(decl->Declaration.File) {
689 case TGSI_FILE_ADDRESS:
690 {
691 unsigned idx;
692 for (idx = decl->Range.First; idx <= decl->Range.Last; idx++) {
693 unsigned chan;
694 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
695 ctx->addrs[idx][chan] = lp_build_alloca_undef(
696 &ctx->gallivm,
697 ctx->i32, "");
698 }
699 }
700 break;
701 }
702
703 case TGSI_FILE_TEMPORARY:
704 {
705 char name[16] = "";
706 LLVMValueRef array_alloca = NULL;
707 unsigned decl_size;
708 unsigned writemask = decl->Declaration.UsageMask;
709 first = decl->Range.First;
710 last = decl->Range.Last;
711 decl_size = 4 * ((last - first) + 1);
712
713 if (decl->Declaration.Array) {
714 unsigned id = decl->Array.ArrayID - 1;
715 unsigned array_size;
716
717 writemask &= ctx->temp_arrays[id].writemask;
718 ctx->temp_arrays[id].writemask = writemask;
719 array_size = ((last - first) + 1) * util_bitcount(writemask);
720
721 /* If the array has more than 16 elements, store it
722 * in memory using an alloca that spans the entire
723 * array.
724 *
725 * Otherwise, store each array element individually.
726 * We will then generate vectors (per-channel, up to
727 * <16 x float> if the usagemask is a single bit) for
728 * indirect addressing.
729 *
730 * Note that 16 is the number of vector elements that
731 * LLVM will store in a register, so theoretically an
732 * array with up to 4 * 16 = 64 elements could be
733 * handled this way, but whether that's a good idea
734 * depends on VGPR register pressure elsewhere.
735 *
736 * FIXME: We shouldn't need to have the non-alloca
737 * code path for arrays. LLVM should be smart enough to
738 * promote allocas into registers when profitable.
739 */
740 if (array_size > 16 ||
741 !ctx->screen->llvm_has_working_vgpr_indexing) {
742 array_alloca = lp_build_alloca_undef(&ctx->gallivm,
743 LLVMArrayType(ctx->f32,
744 array_size), "array");
745 ctx->temp_array_allocas[id] = array_alloca;
746 }
747 }
748
749 if (!ctx->temps_count) {
750 ctx->temps_count = bld_base->info->file_max[TGSI_FILE_TEMPORARY] + 1;
751 ctx->temps = MALLOC(TGSI_NUM_CHANNELS * ctx->temps_count * sizeof(LLVMValueRef));
752 }
753 if (!array_alloca) {
754 for (i = 0; i < decl_size; ++i) {
755 #ifdef DEBUG
756 snprintf(name, sizeof(name), "TEMP%d.%c",
757 first + i / 4, "xyzw"[i % 4]);
758 #endif
759 ctx->temps[first * TGSI_NUM_CHANNELS + i] =
760 lp_build_alloca_undef(&ctx->gallivm,
761 ctx->f32,
762 name);
763 }
764 } else {
765 LLVMValueRef idxs[2] = {
766 ctx->i32_0,
767 NULL
768 };
769 unsigned j = 0;
770
771 if (writemask != TGSI_WRITEMASK_XYZW &&
772 !ctx->undef_alloca) {
773 /* Create a dummy alloca. We use it so that we
774 * have a pointer that is safe to load from if
775 * a shader ever reads from a channel that
776 * it never writes to.
777 */
778 ctx->undef_alloca = lp_build_alloca_undef(
779 &ctx->gallivm,
780 ctx->f32, "undef");
781 }
782
783 for (i = 0; i < decl_size; ++i) {
784 LLVMValueRef ptr;
785 if (writemask & (1 << (i % 4))) {
786 #ifdef DEBUG
787 snprintf(name, sizeof(name), "TEMP%d.%c",
788 first + i / 4, "xyzw"[i % 4]);
789 #endif
790 idxs[1] = LLVMConstInt(ctx->i32, j, 0);
791 ptr = LLVMBuildGEP(builder, array_alloca, idxs, 2, name);
792 j++;
793 } else {
794 ptr = ctx->undef_alloca;
795 }
796 ctx->temps[first * TGSI_NUM_CHANNELS + i] = ptr;
797 }
798 }
799 break;
800 }
801 case TGSI_FILE_INPUT:
802 {
803 unsigned idx;
804 for (idx = decl->Range.First; idx <= decl->Range.Last; idx++) {
805 if (ctx->load_input &&
806 ctx->input_decls[idx].Declaration.File != TGSI_FILE_INPUT) {
807 ctx->input_decls[idx] = *decl;
808 ctx->input_decls[idx].Range.First = idx;
809 ctx->input_decls[idx].Range.Last = idx;
810 ctx->input_decls[idx].Semantic.Index += idx - decl->Range.First;
811
812 if (si_preload_fs_inputs(ctx) ||
813 bld_base->info->processor != PIPE_SHADER_FRAGMENT)
814 ctx->load_input(ctx, idx, &ctx->input_decls[idx],
815 &ctx->inputs[idx * 4]);
816 }
817 }
818 }
819 break;
820
821 case TGSI_FILE_SYSTEM_VALUE:
822 {
823 unsigned idx;
824 for (idx = decl->Range.First; idx <= decl->Range.Last; idx++) {
825 si_load_system_value(ctx, idx, decl);
826 }
827 }
828 break;
829
830 case TGSI_FILE_OUTPUT:
831 {
832 char name[16] = "";
833 unsigned idx;
834 for (idx = decl->Range.First; idx <= decl->Range.Last; idx++) {
835 unsigned chan;
836 assert(idx < RADEON_LLVM_MAX_OUTPUTS);
837 if (ctx->outputs[idx][0])
838 continue;
839 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
840 #ifdef DEBUG
841 snprintf(name, sizeof(name), "OUT%d.%c",
842 idx, "xyzw"[chan % 4]);
843 #endif
844 ctx->outputs[idx][chan] = lp_build_alloca_undef(
845 &ctx->gallivm,
846 ctx->f32, name);
847 }
848 }
849 break;
850 }
851
852 case TGSI_FILE_MEMORY:
853 si_declare_compute_memory(ctx, decl);
854 break;
855
856 default:
857 break;
858 }
859 }
860
861 void si_llvm_emit_store(struct lp_build_tgsi_context *bld_base,
862 const struct tgsi_full_instruction *inst,
863 const struct tgsi_opcode_info *info,
864 unsigned index,
865 LLVMValueRef dst[4])
866 {
867 struct si_shader_context *ctx = si_shader_context(bld_base);
868 const struct tgsi_full_dst_register *reg = &inst->Dst[index];
869 LLVMBuilderRef builder = ctx->ac.builder;
870 LLVMValueRef temp_ptr, temp_ptr2 = NULL;
871 bool is_vec_store = false;
872 enum tgsi_opcode_type dtype = tgsi_opcode_infer_dst_type(inst->Instruction.Opcode, index);
873
874 if (dst[0]) {
875 LLVMTypeKind k = LLVMGetTypeKind(LLVMTypeOf(dst[0]));
876 is_vec_store = (k == LLVMVectorTypeKind);
877 }
878
879 if (is_vec_store) {
880 LLVMValueRef values[4] = {};
881 uint32_t writemask = reg->Register.WriteMask;
882 while (writemask) {
883 unsigned chan = u_bit_scan(&writemask);
884 LLVMValueRef index = LLVMConstInt(ctx->i32, chan, 0);
885 values[chan] = LLVMBuildExtractElement(ctx->ac.builder,
886 dst[0], index, "");
887 }
888 bld_base->emit_store(bld_base, inst, info, index, values);
889 return;
890 }
891
892 uint32_t writemask = reg->Register.WriteMask;
893 while (writemask) {
894 unsigned chan_index = u_bit_scan(&writemask);
895 LLVMValueRef value = dst[chan_index];
896
897 if (tgsi_type_is_64bit(dtype) && (chan_index == 1 || chan_index == 3))
898 continue;
899 if (inst->Instruction.Saturate)
900 value = ac_build_clamp(&ctx->ac, value);
901
902 if (reg->Register.File == TGSI_FILE_ADDRESS) {
903 temp_ptr = ctx->addrs[reg->Register.Index][chan_index];
904 LLVMBuildStore(builder, value, temp_ptr);
905 continue;
906 }
907
908 if (!tgsi_type_is_64bit(dtype))
909 value = ac_to_float(&ctx->ac, value);
910
911 if (reg->Register.Indirect) {
912 unsigned file = reg->Register.File;
913 unsigned reg_index = reg->Register.Index;
914 store_value_to_array(bld_base, value, file, chan_index,
915 reg_index, &reg->Indirect);
916 } else {
917 switch(reg->Register.File) {
918 case TGSI_FILE_OUTPUT:
919 temp_ptr = ctx->outputs[reg->Register.Index][chan_index];
920 if (tgsi_type_is_64bit(dtype))
921 temp_ptr2 = ctx->outputs[reg->Register.Index][chan_index + 1];
922 break;
923
924 case TGSI_FILE_TEMPORARY:
925 {
926 if (reg->Register.Index >= ctx->temps_count)
927 continue;
928
929 temp_ptr = ctx->temps[ TGSI_NUM_CHANNELS * reg->Register.Index + chan_index];
930 if (tgsi_type_is_64bit(dtype))
931 temp_ptr2 = ctx->temps[ TGSI_NUM_CHANNELS * reg->Register.Index + chan_index + 1];
932
933 break;
934 }
935 default:
936 return;
937 }
938 if (!tgsi_type_is_64bit(dtype))
939 LLVMBuildStore(builder, value, temp_ptr);
940 else {
941 LLVMValueRef ptr = LLVMBuildBitCast(builder, value,
942 LLVMVectorType(ctx->i32, 2), "");
943 LLVMValueRef val2;
944 value = LLVMBuildExtractElement(builder, ptr,
945 ctx->i32_0, "");
946 val2 = LLVMBuildExtractElement(builder, ptr,
947 ctx->i32_1, "");
948
949 LLVMBuildStore(builder, ac_to_float(&ctx->ac, value), temp_ptr);
950 LLVMBuildStore(builder, ac_to_float(&ctx->ac, val2), temp_ptr2);
951 }
952 }
953 }
954 }
955
956 static void set_basicblock_name(LLVMBasicBlockRef bb, const char *base, int pc)
957 {
958 char buf[32];
959 /* Subtract 1 so that the number shown is that of the corresponding
960 * opcode in the TGSI dump, e.g. an if block has the same suffix as
961 * the instruction number of the corresponding TGSI IF.
962 */
963 snprintf(buf, sizeof(buf), "%s%d", base, pc - 1);
964 LLVMSetValueName(LLVMBasicBlockAsValue(bb), buf);
965 }
966
967 /* Append a basic block at the level of the parent flow.
968 */
969 static LLVMBasicBlockRef append_basic_block(struct si_shader_context *ctx,
970 const char *name)
971 {
972 struct gallivm_state *gallivm = &ctx->gallivm;
973
974 assert(ctx->flow_depth >= 1);
975
976 if (ctx->flow_depth >= 2) {
977 struct si_llvm_flow *flow = &ctx->flow[ctx->flow_depth - 2];
978
979 return LLVMInsertBasicBlockInContext(gallivm->context,
980 flow->next_block, name);
981 }
982
983 return LLVMAppendBasicBlockInContext(gallivm->context, ctx->main_fn, name);
984 }
985
986 /* Emit a branch to the given default target for the current block if
987 * applicable -- that is, if the current block does not already contain a
988 * branch from a break or continue.
989 */
990 static void emit_default_branch(LLVMBuilderRef builder, LLVMBasicBlockRef target)
991 {
992 if (!LLVMGetBasicBlockTerminator(LLVMGetInsertBlock(builder)))
993 LLVMBuildBr(builder, target);
994 }
995
996 static void bgnloop_emit(const struct lp_build_tgsi_action *action,
997 struct lp_build_tgsi_context *bld_base,
998 struct lp_build_emit_data *emit_data)
999 {
1000 struct si_shader_context *ctx = si_shader_context(bld_base);
1001 struct si_llvm_flow *flow = push_flow(ctx);
1002 flow->loop_entry_block = append_basic_block(ctx, "LOOP");
1003 flow->next_block = append_basic_block(ctx, "ENDLOOP");
1004 set_basicblock_name(flow->loop_entry_block, "loop", bld_base->pc);
1005 LLVMBuildBr(ctx->ac.builder, flow->loop_entry_block);
1006 LLVMPositionBuilderAtEnd(ctx->ac.builder, flow->loop_entry_block);
1007 }
1008
1009 static void brk_emit(const struct lp_build_tgsi_action *action,
1010 struct lp_build_tgsi_context *bld_base,
1011 struct lp_build_emit_data *emit_data)
1012 {
1013 struct si_shader_context *ctx = si_shader_context(bld_base);
1014 struct si_llvm_flow *flow = get_innermost_loop(ctx);
1015
1016 LLVMBuildBr(ctx->ac.builder, flow->next_block);
1017 }
1018
1019 static void cont_emit(const struct lp_build_tgsi_action *action,
1020 struct lp_build_tgsi_context *bld_base,
1021 struct lp_build_emit_data *emit_data)
1022 {
1023 struct si_shader_context *ctx = si_shader_context(bld_base);
1024 struct si_llvm_flow *flow = get_innermost_loop(ctx);
1025
1026 LLVMBuildBr(ctx->ac.builder, flow->loop_entry_block);
1027 }
1028
1029 static void else_emit(const struct lp_build_tgsi_action *action,
1030 struct lp_build_tgsi_context *bld_base,
1031 struct lp_build_emit_data *emit_data)
1032 {
1033 struct si_shader_context *ctx = si_shader_context(bld_base);
1034 struct si_llvm_flow *current_branch = get_current_flow(ctx);
1035 LLVMBasicBlockRef endif_block;
1036
1037 assert(!current_branch->loop_entry_block);
1038
1039 endif_block = append_basic_block(ctx, "ENDIF");
1040 emit_default_branch(ctx->ac.builder, endif_block);
1041
1042 LLVMPositionBuilderAtEnd(ctx->ac.builder, current_branch->next_block);
1043 set_basicblock_name(current_branch->next_block, "else", bld_base->pc);
1044
1045 current_branch->next_block = endif_block;
1046 }
1047
1048 static void endif_emit(const struct lp_build_tgsi_action *action,
1049 struct lp_build_tgsi_context *bld_base,
1050 struct lp_build_emit_data *emit_data)
1051 {
1052 struct si_shader_context *ctx = si_shader_context(bld_base);
1053 struct si_llvm_flow *current_branch = get_current_flow(ctx);
1054
1055 assert(!current_branch->loop_entry_block);
1056
1057 emit_default_branch(ctx->ac.builder, current_branch->next_block);
1058 LLVMPositionBuilderAtEnd(ctx->ac.builder, current_branch->next_block);
1059 set_basicblock_name(current_branch->next_block, "endif", bld_base->pc);
1060
1061 ctx->flow_depth--;
1062 }
1063
1064 static void endloop_emit(const struct lp_build_tgsi_action *action,
1065 struct lp_build_tgsi_context *bld_base,
1066 struct lp_build_emit_data *emit_data)
1067 {
1068 struct si_shader_context *ctx = si_shader_context(bld_base);
1069 struct si_llvm_flow *current_loop = get_current_flow(ctx);
1070
1071 assert(current_loop->loop_entry_block);
1072
1073 emit_default_branch(ctx->ac.builder, current_loop->loop_entry_block);
1074
1075 LLVMPositionBuilderAtEnd(ctx->ac.builder, current_loop->next_block);
1076 set_basicblock_name(current_loop->next_block, "endloop", bld_base->pc);
1077 ctx->flow_depth--;
1078 }
1079
1080 static void if_cond_emit(const struct lp_build_tgsi_action *action,
1081 struct lp_build_tgsi_context *bld_base,
1082 struct lp_build_emit_data *emit_data,
1083 LLVMValueRef cond)
1084 {
1085 struct si_shader_context *ctx = si_shader_context(bld_base);
1086 struct si_llvm_flow *flow = push_flow(ctx);
1087 LLVMBasicBlockRef if_block;
1088
1089 if_block = append_basic_block(ctx, "IF");
1090 flow->next_block = append_basic_block(ctx, "ELSE");
1091 set_basicblock_name(if_block, "if", bld_base->pc);
1092 LLVMBuildCondBr(ctx->ac.builder, cond, if_block, flow->next_block);
1093 LLVMPositionBuilderAtEnd(ctx->ac.builder, if_block);
1094 }
1095
1096 static void if_emit(const struct lp_build_tgsi_action *action,
1097 struct lp_build_tgsi_context *bld_base,
1098 struct lp_build_emit_data *emit_data)
1099 {
1100 struct si_shader_context *ctx = si_shader_context(bld_base);
1101 LLVMValueRef cond;
1102
1103 cond = LLVMBuildFCmp(ctx->ac.builder, LLVMRealUNE,
1104 emit_data->args[0],
1105 bld_base->base.zero, "");
1106
1107 if_cond_emit(action, bld_base, emit_data, cond);
1108 }
1109
1110 static void uif_emit(const struct lp_build_tgsi_action *action,
1111 struct lp_build_tgsi_context *bld_base,
1112 struct lp_build_emit_data *emit_data)
1113 {
1114 struct si_shader_context *ctx = si_shader_context(bld_base);
1115 LLVMValueRef cond;
1116
1117 cond = LLVMBuildICmp(ctx->ac.builder, LLVMIntNE,
1118 ac_to_integer(&ctx->ac, emit_data->args[0]), ctx->i32_0, "");
1119
1120 if_cond_emit(action, bld_base, emit_data, cond);
1121 }
1122
1123 static void emit_immediate(struct lp_build_tgsi_context *bld_base,
1124 const struct tgsi_full_immediate *imm)
1125 {
1126 unsigned i;
1127 struct si_shader_context *ctx = si_shader_context(bld_base);
1128
1129 for (i = 0; i < 4; ++i) {
1130 ctx->imms[ctx->imms_num * TGSI_NUM_CHANNELS + i] =
1131 LLVMConstInt(ctx->i32, imm->u[i].Uint, false );
1132 }
1133
1134 ctx->imms_num++;
1135 }
1136
1137 void si_llvm_context_init(struct si_shader_context *ctx,
1138 struct si_screen *sscreen,
1139 LLVMTargetMachineRef tm)
1140 {
1141 struct lp_type type;
1142
1143 /* Initialize the gallivm object:
1144 * We are only using the module, context, and builder fields of this struct.
1145 * This should be enough for us to be able to pass our gallivm struct to the
1146 * helper functions in the gallivm module.
1147 */
1148 memset(ctx, 0, sizeof(*ctx));
1149 ctx->screen = sscreen;
1150 ctx->tm = tm;
1151
1152 ctx->gallivm.context = LLVMContextCreate();
1153 ctx->gallivm.module = LLVMModuleCreateWithNameInContext("tgsi",
1154 ctx->gallivm.context);
1155 LLVMSetTarget(ctx->gallivm.module, "amdgcn--");
1156
1157 LLVMTargetDataRef data_layout = LLVMCreateTargetDataLayout(tm);
1158 char *data_layout_str = LLVMCopyStringRepOfTargetData(data_layout);
1159 LLVMSetDataLayout(ctx->gallivm.module, data_layout_str);
1160 LLVMDisposeTargetData(data_layout);
1161 LLVMDisposeMessage(data_layout_str);
1162
1163 bool unsafe_fpmath = (sscreen->b.debug_flags & DBG_UNSAFE_MATH) != 0;
1164 enum lp_float_mode float_mode =
1165 unsafe_fpmath ? LP_FLOAT_MODE_UNSAFE_FP_MATH :
1166 LP_FLOAT_MODE_NO_SIGNED_ZEROS_FP_MATH;
1167
1168 ctx->gallivm.builder = lp_create_builder(ctx->gallivm.context,
1169 float_mode);
1170
1171 ac_llvm_context_init(&ctx->ac, ctx->gallivm.context, sscreen->b.chip_class);
1172 ctx->ac.module = ctx->gallivm.module;
1173 ctx->ac.builder = ctx->gallivm.builder;
1174
1175 struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
1176
1177 type.floating = true;
1178 type.fixed = false;
1179 type.sign = true;
1180 type.norm = false;
1181 type.width = 32;
1182 type.length = 1;
1183
1184 lp_build_context_init(&bld_base->base, &ctx->gallivm, type);
1185 lp_build_context_init(&ctx->bld_base.uint_bld, &ctx->gallivm, lp_uint_type(type));
1186 lp_build_context_init(&ctx->bld_base.int_bld, &ctx->gallivm, lp_int_type(type));
1187 type.width *= 2;
1188 lp_build_context_init(&ctx->bld_base.dbl_bld, &ctx->gallivm, type);
1189 lp_build_context_init(&ctx->bld_base.uint64_bld, &ctx->gallivm, lp_uint_type(type));
1190 lp_build_context_init(&ctx->bld_base.int64_bld, &ctx->gallivm, lp_int_type(type));
1191
1192 bld_base->soa = 1;
1193 bld_base->emit_swizzle = emit_swizzle;
1194 bld_base->emit_declaration = emit_declaration;
1195 bld_base->emit_immediate = emit_immediate;
1196
1197 /* metadata allowing 2.5 ULP */
1198 ctx->fpmath_md_kind = LLVMGetMDKindIDInContext(ctx->gallivm.context,
1199 "fpmath", 6);
1200 LLVMValueRef arg = lp_build_const_float(&ctx->gallivm, 2.5);
1201 ctx->fpmath_md_2p5_ulp = LLVMMDNodeInContext(ctx->gallivm.context,
1202 &arg, 1);
1203
1204 bld_base->op_actions[TGSI_OPCODE_BGNLOOP].emit = bgnloop_emit;
1205 bld_base->op_actions[TGSI_OPCODE_BRK].emit = brk_emit;
1206 bld_base->op_actions[TGSI_OPCODE_CONT].emit = cont_emit;
1207 bld_base->op_actions[TGSI_OPCODE_IF].emit = if_emit;
1208 bld_base->op_actions[TGSI_OPCODE_UIF].emit = uif_emit;
1209 bld_base->op_actions[TGSI_OPCODE_ELSE].emit = else_emit;
1210 bld_base->op_actions[TGSI_OPCODE_ENDIF].emit = endif_emit;
1211 bld_base->op_actions[TGSI_OPCODE_ENDLOOP].emit = endloop_emit;
1212
1213 si_shader_context_init_alu(&ctx->bld_base);
1214 si_shader_context_init_mem(ctx);
1215
1216 ctx->voidt = LLVMVoidTypeInContext(ctx->gallivm.context);
1217 ctx->i1 = LLVMInt1TypeInContext(ctx->gallivm.context);
1218 ctx->i8 = LLVMInt8TypeInContext(ctx->gallivm.context);
1219 ctx->i32 = LLVMInt32TypeInContext(ctx->gallivm.context);
1220 ctx->i64 = LLVMInt64TypeInContext(ctx->gallivm.context);
1221 ctx->i128 = LLVMIntTypeInContext(ctx->gallivm.context, 128);
1222 ctx->f32 = LLVMFloatTypeInContext(ctx->gallivm.context);
1223 ctx->v2i32 = LLVMVectorType(ctx->i32, 2);
1224 ctx->v4i32 = LLVMVectorType(ctx->i32, 4);
1225 ctx->v4f32 = LLVMVectorType(ctx->f32, 4);
1226 ctx->v8i32 = LLVMVectorType(ctx->i32, 8);
1227
1228 ctx->i32_0 = LLVMConstInt(ctx->i32, 0, 0);
1229 ctx->i32_1 = LLVMConstInt(ctx->i32, 1, 0);
1230 }
1231
1232 /* Set the context to a certain TGSI shader. Can be called repeatedly
1233 * to change the shader. */
1234 void si_llvm_context_set_tgsi(struct si_shader_context *ctx,
1235 struct si_shader *shader)
1236 {
1237 const struct tgsi_shader_info *info = NULL;
1238 const struct tgsi_token *tokens = NULL;
1239
1240 if (shader && shader->selector) {
1241 info = &shader->selector->info;
1242 tokens = shader->selector->tokens;
1243 }
1244
1245 ctx->shader = shader;
1246 ctx->type = info ? info->processor : -1;
1247 ctx->bld_base.info = info;
1248
1249 /* Clean up the old contents. */
1250 FREE(ctx->temp_arrays);
1251 ctx->temp_arrays = NULL;
1252 FREE(ctx->temp_array_allocas);
1253 ctx->temp_array_allocas = NULL;
1254
1255 FREE(ctx->imms);
1256 ctx->imms = NULL;
1257 ctx->imms_num = 0;
1258
1259 FREE(ctx->temps);
1260 ctx->temps = NULL;
1261 ctx->temps_count = 0;
1262
1263 if (!info || !tokens)
1264 return;
1265
1266 if (info->array_max[TGSI_FILE_TEMPORARY] > 0) {
1267 int size = info->array_max[TGSI_FILE_TEMPORARY];
1268
1269 ctx->temp_arrays = CALLOC(size, sizeof(ctx->temp_arrays[0]));
1270 ctx->temp_array_allocas = CALLOC(size, sizeof(ctx->temp_array_allocas[0]));
1271
1272 tgsi_scan_arrays(tokens, TGSI_FILE_TEMPORARY, size,
1273 ctx->temp_arrays);
1274 }
1275 if (info->file_max[TGSI_FILE_IMMEDIATE] >= 0) {
1276 int size = info->file_max[TGSI_FILE_IMMEDIATE] + 1;
1277 ctx->imms = MALLOC(size * TGSI_NUM_CHANNELS * sizeof(LLVMValueRef));
1278 }
1279
1280 /* Re-set these to start with a clean slate. */
1281 ctx->bld_base.num_instructions = 0;
1282 ctx->bld_base.pc = 0;
1283 memset(ctx->outputs, 0, sizeof(ctx->outputs));
1284
1285 ctx->bld_base.emit_store = si_llvm_emit_store;
1286 ctx->bld_base.emit_fetch_funcs[TGSI_FILE_IMMEDIATE] = si_llvm_emit_fetch;
1287 ctx->bld_base.emit_fetch_funcs[TGSI_FILE_INPUT] = si_llvm_emit_fetch;
1288 ctx->bld_base.emit_fetch_funcs[TGSI_FILE_TEMPORARY] = si_llvm_emit_fetch;
1289 ctx->bld_base.emit_fetch_funcs[TGSI_FILE_OUTPUT] = si_llvm_emit_fetch;
1290 ctx->bld_base.emit_fetch_funcs[TGSI_FILE_SYSTEM_VALUE] = fetch_system_value;
1291
1292 ctx->num_const_buffers = util_last_bit(info->const_buffers_declared);
1293 ctx->num_shader_buffers = util_last_bit(info->shader_buffers_declared);
1294 ctx->num_samplers = util_last_bit(info->samplers_declared);
1295 ctx->num_images = util_last_bit(info->images_declared);
1296 }
1297
1298 void si_llvm_create_func(struct si_shader_context *ctx,
1299 const char *name,
1300 LLVMTypeRef *return_types, unsigned num_return_elems,
1301 LLVMTypeRef *ParamTypes, unsigned ParamCount)
1302 {
1303 LLVMTypeRef main_fn_type, ret_type;
1304 LLVMBasicBlockRef main_fn_body;
1305 enum si_llvm_calling_convention call_conv;
1306 unsigned real_shader_type;
1307
1308 if (num_return_elems)
1309 ret_type = LLVMStructTypeInContext(ctx->gallivm.context,
1310 return_types,
1311 num_return_elems, true);
1312 else
1313 ret_type = LLVMVoidTypeInContext(ctx->gallivm.context);
1314
1315 /* Setup the function */
1316 ctx->return_type = ret_type;
1317 main_fn_type = LLVMFunctionType(ret_type, ParamTypes, ParamCount, 0);
1318 ctx->main_fn = LLVMAddFunction(ctx->gallivm.module, name, main_fn_type);
1319 main_fn_body = LLVMAppendBasicBlockInContext(ctx->gallivm.context,
1320 ctx->main_fn, "main_body");
1321 LLVMPositionBuilderAtEnd(ctx->ac.builder, main_fn_body);
1322
1323 real_shader_type = ctx->type;
1324
1325 /* LS is merged into HS (TCS), and ES is merged into GS. */
1326 if (ctx->screen->b.chip_class >= GFX9) {
1327 if (ctx->shader->key.as_ls)
1328 real_shader_type = PIPE_SHADER_TESS_CTRL;
1329 else if (ctx->shader->key.as_es)
1330 real_shader_type = PIPE_SHADER_GEOMETRY;
1331 }
1332
1333 switch (real_shader_type) {
1334 case PIPE_SHADER_VERTEX:
1335 case PIPE_SHADER_TESS_EVAL:
1336 call_conv = RADEON_LLVM_AMDGPU_VS;
1337 break;
1338 case PIPE_SHADER_TESS_CTRL:
1339 call_conv = HAVE_LLVM >= 0x0500 ? RADEON_LLVM_AMDGPU_HS :
1340 RADEON_LLVM_AMDGPU_VS;
1341 break;
1342 case PIPE_SHADER_GEOMETRY:
1343 call_conv = RADEON_LLVM_AMDGPU_GS;
1344 break;
1345 case PIPE_SHADER_FRAGMENT:
1346 call_conv = RADEON_LLVM_AMDGPU_PS;
1347 break;
1348 case PIPE_SHADER_COMPUTE:
1349 call_conv = RADEON_LLVM_AMDGPU_CS;
1350 break;
1351 default:
1352 unreachable("Unhandle shader type");
1353 }
1354
1355 LLVMSetFunctionCallConv(ctx->main_fn, call_conv);
1356 }
1357
1358 void si_llvm_optimize_module(struct si_shader_context *ctx)
1359 {
1360 struct gallivm_state *gallivm = &ctx->gallivm;
1361 const char *triple = LLVMGetTarget(gallivm->module);
1362 LLVMTargetLibraryInfoRef target_library_info;
1363
1364 /* Dump LLVM IR before any optimization passes */
1365 if (ctx->screen->b.debug_flags & DBG_PREOPT_IR &&
1366 si_can_dump_shader(&ctx->screen->b, ctx->type))
1367 LLVMDumpModule(ctx->gallivm.module);
1368
1369 /* Create the pass manager */
1370 gallivm->passmgr = LLVMCreatePassManager();
1371
1372 target_library_info = gallivm_create_target_library_info(triple);
1373 LLVMAddTargetLibraryInfo(target_library_info, gallivm->passmgr);
1374
1375 if (si_extra_shader_checks(&ctx->screen->b, ctx->type))
1376 LLVMAddVerifierPass(gallivm->passmgr);
1377
1378 LLVMAddAlwaysInlinerPass(gallivm->passmgr);
1379
1380 /* This pass should eliminate all the load and store instructions */
1381 LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
1382
1383 /* Add some optimization passes */
1384 LLVMAddScalarReplAggregatesPass(gallivm->passmgr);
1385 LLVMAddLICMPass(gallivm->passmgr);
1386 LLVMAddAggressiveDCEPass(gallivm->passmgr);
1387 LLVMAddCFGSimplificationPass(gallivm->passmgr);
1388 #if HAVE_LLVM >= 0x0400
1389 /* This is recommended by the instruction combining pass. */
1390 LLVMAddEarlyCSEMemSSAPass(gallivm->passmgr);
1391 #endif
1392 LLVMAddInstructionCombiningPass(gallivm->passmgr);
1393
1394 /* Run the pass */
1395 LLVMRunPassManager(gallivm->passmgr, ctx->gallivm.module);
1396
1397 LLVMDisposeBuilder(ctx->ac.builder);
1398 LLVMDisposePassManager(gallivm->passmgr);
1399 gallivm_dispose_target_library_info(target_library_info);
1400 }
1401
1402 void si_llvm_dispose(struct si_shader_context *ctx)
1403 {
1404 LLVMDisposeModule(ctx->gallivm.module);
1405 LLVMContextDispose(ctx->gallivm.context);
1406 FREE(ctx->temp_arrays);
1407 ctx->temp_arrays = NULL;
1408 FREE(ctx->temp_array_allocas);
1409 ctx->temp_array_allocas = NULL;
1410 FREE(ctx->temps);
1411 ctx->temps = NULL;
1412 ctx->temps_count = 0;
1413 FREE(ctx->imms);
1414 ctx->imms = NULL;
1415 ctx->imms_num = 0;
1416 FREE(ctx->flow);
1417 ctx->flow = NULL;
1418 ctx->flow_depth_max = 0;
1419 }