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