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