nvc0: fix up image support for allowing multiple samples
[mesa.git] / src / gallium / drivers / nouveau / codegen / nv50_ir_lowering_nvc0.cpp
1 /*
2 * Copyright 2011 Christoph Bumiller
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
18 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20 * OTHER DEALINGS IN THE SOFTWARE.
21 */
22
23 #include "codegen/nv50_ir.h"
24 #include "codegen/nv50_ir_build_util.h"
25
26 #include "codegen/nv50_ir_target_nvc0.h"
27 #include "codegen/nv50_ir_lowering_nvc0.h"
28
29 #include <limits>
30
31 namespace nv50_ir {
32
33 #define QOP_ADD 0
34 #define QOP_SUBR 1
35 #define QOP_SUB 2
36 #define QOP_MOV2 3
37
38 // UL UR LL LR
39 #define QUADOP(q, r, s, t) \
40 ((QOP_##q << 6) | (QOP_##r << 4) | \
41 (QOP_##s << 2) | (QOP_##t << 0))
42
43 void
44 NVC0LegalizeSSA::handleDIV(Instruction *i)
45 {
46 FlowInstruction *call;
47 int builtin;
48 Value *def[2];
49
50 bld.setPosition(i, false);
51 def[0] = bld.mkMovToReg(0, i->getSrc(0))->getDef(0);
52 def[1] = bld.mkMovToReg(1, i->getSrc(1))->getDef(0);
53 switch (i->dType) {
54 case TYPE_U32: builtin = NVC0_BUILTIN_DIV_U32; break;
55 case TYPE_S32: builtin = NVC0_BUILTIN_DIV_S32; break;
56 default:
57 return;
58 }
59 call = bld.mkFlow(OP_CALL, NULL, CC_ALWAYS, NULL);
60 bld.mkMov(i->getDef(0), def[(i->op == OP_DIV) ? 0 : 1]);
61 bld.mkClobber(FILE_GPR, (i->op == OP_DIV) ? 0xe : 0xd, 2);
62 bld.mkClobber(FILE_PREDICATE, (i->dType == TYPE_S32) ? 0xf : 0x3, 0);
63
64 call->fixed = 1;
65 call->absolute = call->builtin = 1;
66 call->target.builtin = builtin;
67 delete_Instruction(prog, i);
68 }
69
70 void
71 NVC0LegalizeSSA::handleRCPRSQ(Instruction *i)
72 {
73 assert(i->dType == TYPE_F64);
74 // There are instructions that will compute the high 32 bits of the 64-bit
75 // float. We will just stick 0 in the bottom 32 bits.
76
77 bld.setPosition(i, false);
78
79 // 1. Take the source and it up.
80 Value *src[2], *dst[2], *def = i->getDef(0);
81 bld.mkSplit(src, 4, i->getSrc(0));
82
83 // 2. We don't care about the low 32 bits of the destination. Stick a 0 in.
84 dst[0] = bld.loadImm(NULL, 0);
85 dst[1] = bld.getSSA();
86
87 // 3. The new version of the instruction takes the high 32 bits of the
88 // source and outputs the high 32 bits of the destination.
89 i->setSrc(0, src[1]);
90 i->setDef(0, dst[1]);
91 i->setType(TYPE_F32);
92 i->subOp = NV50_IR_SUBOP_RCPRSQ_64H;
93
94 // 4. Recombine the two dst pieces back into the original destination.
95 bld.setPosition(i, true);
96 bld.mkOp2(OP_MERGE, TYPE_U64, def, dst[0], dst[1]);
97 }
98
99 void
100 NVC0LegalizeSSA::handleFTZ(Instruction *i)
101 {
102 // Only want to flush float inputs
103 assert(i->sType == TYPE_F32);
104
105 // If we're already flushing denorms (and NaN's) to zero, no need for this.
106 if (i->dnz)
107 return;
108
109 // Only certain classes of operations can flush
110 OpClass cls = prog->getTarget()->getOpClass(i->op);
111 if (cls != OPCLASS_ARITH && cls != OPCLASS_COMPARE &&
112 cls != OPCLASS_CONVERT)
113 return;
114
115 i->ftz = true;
116 }
117
118 bool
119 NVC0LegalizeSSA::visit(Function *fn)
120 {
121 bld.setProgram(fn->getProgram());
122 return true;
123 }
124
125 bool
126 NVC0LegalizeSSA::visit(BasicBlock *bb)
127 {
128 Instruction *next;
129 for (Instruction *i = bb->getEntry(); i; i = next) {
130 next = i->next;
131 if (i->sType == TYPE_F32) {
132 if (prog->getType() != Program::TYPE_COMPUTE)
133 handleFTZ(i);
134 continue;
135 }
136 switch (i->op) {
137 case OP_DIV:
138 case OP_MOD:
139 handleDIV(i);
140 break;
141 case OP_RCP:
142 case OP_RSQ:
143 if (i->dType == TYPE_F64)
144 handleRCPRSQ(i);
145 break;
146 default:
147 break;
148 }
149 }
150 return true;
151 }
152
153 NVC0LegalizePostRA::NVC0LegalizePostRA(const Program *prog)
154 : rZero(NULL),
155 carry(NULL),
156 pOne(NULL),
157 needTexBar(prog->getTarget()->getChipset() >= 0xe0)
158 {
159 }
160
161 bool
162 NVC0LegalizePostRA::insnDominatedBy(const Instruction *later,
163 const Instruction *early) const
164 {
165 if (early->bb == later->bb)
166 return early->serial < later->serial;
167 return later->bb->dominatedBy(early->bb);
168 }
169
170 void
171 NVC0LegalizePostRA::addTexUse(std::list<TexUse> &uses,
172 Instruction *usei, const Instruction *texi)
173 {
174 bool add = true;
175 bool dominated = insnDominatedBy(usei, texi);
176 // Uses before the tex have to all be included. Just because an earlier
177 // instruction dominates another instruction doesn't mean that there's no
178 // way to get from the tex to the later instruction. For example you could
179 // have nested loops, with the tex in the inner loop, and uses before it in
180 // both loops - even though the outer loop's instruction would dominate the
181 // inner's, we still want a texbar before the inner loop's instruction.
182 //
183 // However we can still use the eliding logic between uses dominated by the
184 // tex instruction, as that is unambiguously correct.
185 if (dominated) {
186 for (std::list<TexUse>::iterator it = uses.begin(); it != uses.end();) {
187 if (it->after) {
188 if (insnDominatedBy(usei, it->insn)) {
189 add = false;
190 break;
191 }
192 if (insnDominatedBy(it->insn, usei)) {
193 it = uses.erase(it);
194 continue;
195 }
196 }
197 ++it;
198 }
199 }
200 if (add)
201 uses.push_back(TexUse(usei, texi, dominated));
202 }
203
204 // While it might be tempting to use the an algorithm that just looks at tex
205 // uses, not all texture results are guaranteed to be used on all paths. In
206 // the case where along some control flow path a texture result is never used,
207 // we might reuse that register for something else, creating a
208 // write-after-write hazard. So we have to manually look through all
209 // instructions looking for ones that reference the registers in question.
210 void
211 NVC0LegalizePostRA::findFirstUses(
212 Instruction *texi, std::list<TexUse> &uses)
213 {
214 int minGPR = texi->def(0).rep()->reg.data.id;
215 int maxGPR = minGPR + texi->def(0).rep()->reg.size / 4 - 1;
216
217 unordered_set<const BasicBlock *> visited;
218 findFirstUsesBB(minGPR, maxGPR, texi->next, texi, uses, visited);
219 }
220
221 void
222 NVC0LegalizePostRA::findFirstUsesBB(
223 int minGPR, int maxGPR, Instruction *start,
224 const Instruction *texi, std::list<TexUse> &uses,
225 unordered_set<const BasicBlock *> &visited)
226 {
227 const BasicBlock *bb = start->bb;
228
229 // We don't process the whole bb the first time around. This is correct,
230 // however we might be in a loop and hit this BB again, and need to process
231 // the full thing. So only mark a bb as visited if we processed it from the
232 // beginning.
233 if (start == bb->getEntry()) {
234 if (visited.find(bb) != visited.end())
235 return;
236 visited.insert(bb);
237 }
238
239 for (Instruction *insn = start; insn != bb->getExit(); insn = insn->next) {
240 if (insn->isNop())
241 continue;
242
243 for (int d = 0; insn->defExists(d); ++d) {
244 const Value *def = insn->def(d).rep();
245 if (insn->def(d).getFile() != FILE_GPR ||
246 def->reg.data.id + def->reg.size / 4 - 1 < minGPR ||
247 def->reg.data.id > maxGPR)
248 continue;
249 addTexUse(uses, insn, texi);
250 return;
251 }
252
253 for (int s = 0; insn->srcExists(s); ++s) {
254 const Value *src = insn->src(s).rep();
255 if (insn->src(s).getFile() != FILE_GPR ||
256 src->reg.data.id + src->reg.size / 4 - 1 < minGPR ||
257 src->reg.data.id > maxGPR)
258 continue;
259 addTexUse(uses, insn, texi);
260 return;
261 }
262 }
263
264 for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {
265 findFirstUsesBB(minGPR, maxGPR, BasicBlock::get(ei.getNode())->getEntry(),
266 texi, uses, visited);
267 }
268 }
269
270 // Texture barriers:
271 // This pass is a bit long and ugly and can probably be optimized.
272 //
273 // 1. obtain a list of TEXes and their outputs' first use(s)
274 // 2. calculate the barrier level of each first use (minimal number of TEXes,
275 // over all paths, between the TEX and the use in question)
276 // 3. for each barrier, if all paths from the source TEX to that barrier
277 // contain a barrier of lesser level, it can be culled
278 bool
279 NVC0LegalizePostRA::insertTextureBarriers(Function *fn)
280 {
281 std::list<TexUse> *uses;
282 std::vector<Instruction *> texes;
283 std::vector<int> bbFirstTex;
284 std::vector<int> bbFirstUse;
285 std::vector<int> texCounts;
286 std::vector<TexUse> useVec;
287 ArrayList insns;
288
289 fn->orderInstructions(insns);
290
291 texCounts.resize(fn->allBBlocks.getSize(), 0);
292 bbFirstTex.resize(fn->allBBlocks.getSize(), insns.getSize());
293 bbFirstUse.resize(fn->allBBlocks.getSize(), insns.getSize());
294
295 // tag BB CFG nodes by their id for later
296 for (ArrayList::Iterator i = fn->allBBlocks.iterator(); !i.end(); i.next()) {
297 BasicBlock *bb = reinterpret_cast<BasicBlock *>(i.get());
298 if (bb)
299 bb->cfg.tag = bb->getId();
300 }
301
302 // gather the first uses for each TEX
303 for (int i = 0; i < insns.getSize(); ++i) {
304 Instruction *tex = reinterpret_cast<Instruction *>(insns.get(i));
305 if (isTextureOp(tex->op)) {
306 texes.push_back(tex);
307 if (!texCounts.at(tex->bb->getId()))
308 bbFirstTex[tex->bb->getId()] = texes.size() - 1;
309 texCounts[tex->bb->getId()]++;
310 }
311 }
312 insns.clear();
313 if (texes.empty())
314 return false;
315 uses = new std::list<TexUse>[texes.size()];
316 if (!uses)
317 return false;
318 for (size_t i = 0; i < texes.size(); ++i) {
319 findFirstUses(texes[i], uses[i]);
320 }
321
322 // determine the barrier level at each use
323 for (size_t i = 0; i < texes.size(); ++i) {
324 for (std::list<TexUse>::iterator u = uses[i].begin(); u != uses[i].end();
325 ++u) {
326 BasicBlock *tb = texes[i]->bb;
327 BasicBlock *ub = u->insn->bb;
328 if (tb == ub) {
329 u->level = 0;
330 for (size_t j = i + 1; j < texes.size() &&
331 texes[j]->bb == tb && texes[j]->serial < u->insn->serial;
332 ++j)
333 u->level++;
334 } else {
335 u->level = fn->cfg.findLightestPathWeight(&tb->cfg,
336 &ub->cfg, texCounts);
337 if (u->level < 0) {
338 WARN("Failed to find path TEX -> TEXBAR\n");
339 u->level = 0;
340 continue;
341 }
342 // this counted all TEXes in the origin block, correct that
343 u->level -= i - bbFirstTex.at(tb->getId()) + 1 /* this TEX */;
344 // and did not count the TEXes in the destination block, add those
345 for (size_t j = bbFirstTex.at(ub->getId()); j < texes.size() &&
346 texes[j]->bb == ub && texes[j]->serial < u->insn->serial;
347 ++j)
348 u->level++;
349 }
350 assert(u->level >= 0);
351 useVec.push_back(*u);
352 }
353 }
354 delete[] uses;
355
356 // insert the barriers
357 for (size_t i = 0; i < useVec.size(); ++i) {
358 Instruction *prev = useVec[i].insn->prev;
359 if (useVec[i].level < 0)
360 continue;
361 if (prev && prev->op == OP_TEXBAR) {
362 if (prev->subOp > useVec[i].level)
363 prev->subOp = useVec[i].level;
364 prev->setSrc(prev->srcCount(), useVec[i].tex->getDef(0));
365 } else {
366 Instruction *bar = new_Instruction(func, OP_TEXBAR, TYPE_NONE);
367 bar->fixed = 1;
368 bar->subOp = useVec[i].level;
369 // make use explicit to ease latency calculation
370 bar->setSrc(bar->srcCount(), useVec[i].tex->getDef(0));
371 useVec[i].insn->bb->insertBefore(useVec[i].insn, bar);
372 }
373 }
374
375 if (fn->getProgram()->optLevel < 3)
376 return true;
377
378 std::vector<Limits> limitT, limitB, limitS; // entry, exit, single
379
380 limitT.resize(fn->allBBlocks.getSize(), Limits(0, 0));
381 limitB.resize(fn->allBBlocks.getSize(), Limits(0, 0));
382 limitS.resize(fn->allBBlocks.getSize());
383
384 // cull unneeded barriers (should do that earlier, but for simplicity)
385 IteratorRef bi = fn->cfg.iteratorCFG();
386 // first calculate min/max outstanding TEXes for each BB
387 for (bi->reset(); !bi->end(); bi->next()) {
388 Graph::Node *n = reinterpret_cast<Graph::Node *>(bi->get());
389 BasicBlock *bb = BasicBlock::get(n);
390 int min = 0;
391 int max = std::numeric_limits<int>::max();
392 for (Instruction *i = bb->getFirst(); i; i = i->next) {
393 if (isTextureOp(i->op)) {
394 min++;
395 if (max < std::numeric_limits<int>::max())
396 max++;
397 } else
398 if (i->op == OP_TEXBAR) {
399 min = MIN2(min, i->subOp);
400 max = MIN2(max, i->subOp);
401 }
402 }
403 // limits when looking at an isolated block
404 limitS[bb->getId()].min = min;
405 limitS[bb->getId()].max = max;
406 }
407 // propagate the min/max values
408 for (unsigned int l = 0; l <= fn->loopNestingBound; ++l) {
409 for (bi->reset(); !bi->end(); bi->next()) {
410 Graph::Node *n = reinterpret_cast<Graph::Node *>(bi->get());
411 BasicBlock *bb = BasicBlock::get(n);
412 const int bbId = bb->getId();
413 for (Graph::EdgeIterator ei = n->incident(); !ei.end(); ei.next()) {
414 BasicBlock *in = BasicBlock::get(ei.getNode());
415 const int inId = in->getId();
416 limitT[bbId].min = MAX2(limitT[bbId].min, limitB[inId].min);
417 limitT[bbId].max = MAX2(limitT[bbId].max, limitB[inId].max);
418 }
419 // I just hope this is correct ...
420 if (limitS[bbId].max == std::numeric_limits<int>::max()) {
421 // no barrier
422 limitB[bbId].min = limitT[bbId].min + limitS[bbId].min;
423 limitB[bbId].max = limitT[bbId].max + limitS[bbId].min;
424 } else {
425 // block contained a barrier
426 limitB[bbId].min = MIN2(limitS[bbId].max,
427 limitT[bbId].min + limitS[bbId].min);
428 limitB[bbId].max = MIN2(limitS[bbId].max,
429 limitT[bbId].max + limitS[bbId].min);
430 }
431 }
432 }
433 // finally delete unnecessary barriers
434 for (bi->reset(); !bi->end(); bi->next()) {
435 Graph::Node *n = reinterpret_cast<Graph::Node *>(bi->get());
436 BasicBlock *bb = BasicBlock::get(n);
437 Instruction *prev = NULL;
438 Instruction *next;
439 int max = limitT[bb->getId()].max;
440 for (Instruction *i = bb->getFirst(); i; i = next) {
441 next = i->next;
442 if (i->op == OP_TEXBAR) {
443 if (i->subOp >= max) {
444 delete_Instruction(prog, i);
445 i = NULL;
446 } else {
447 max = i->subOp;
448 if (prev && prev->op == OP_TEXBAR && prev->subOp >= max) {
449 delete_Instruction(prog, prev);
450 prev = NULL;
451 }
452 }
453 } else
454 if (isTextureOp(i->op)) {
455 max++;
456 }
457 if (i && !i->isNop())
458 prev = i;
459 }
460 }
461 return true;
462 }
463
464 bool
465 NVC0LegalizePostRA::visit(Function *fn)
466 {
467 if (needTexBar)
468 insertTextureBarriers(fn);
469
470 rZero = new_LValue(fn, FILE_GPR);
471 pOne = new_LValue(fn, FILE_PREDICATE);
472 carry = new_LValue(fn, FILE_FLAGS);
473
474 rZero->reg.data.id = (prog->getTarget()->getChipset() >= NVISA_GK20A_CHIPSET) ? 255 : 63;
475 carry->reg.data.id = 0;
476 pOne->reg.data.id = 7;
477
478 return true;
479 }
480
481 void
482 NVC0LegalizePostRA::replaceZero(Instruction *i)
483 {
484 for (int s = 0; i->srcExists(s); ++s) {
485 if (s == 2 && i->op == OP_SUCLAMP)
486 continue;
487 ImmediateValue *imm = i->getSrc(s)->asImm();
488 if (imm) {
489 if (i->op == OP_SELP && s == 2) {
490 i->setSrc(s, pOne);
491 if (imm->reg.data.u64 == 0)
492 i->src(s).mod = i->src(s).mod ^ Modifier(NV50_IR_MOD_NOT);
493 } else if (imm->reg.data.u64 == 0) {
494 i->setSrc(s, rZero);
495 }
496 }
497 }
498 }
499
500 // replace CONT with BRA for single unconditional continue
501 bool
502 NVC0LegalizePostRA::tryReplaceContWithBra(BasicBlock *bb)
503 {
504 if (bb->cfg.incidentCount() != 2 || bb->getEntry()->op != OP_PRECONT)
505 return false;
506 Graph::EdgeIterator ei = bb->cfg.incident();
507 if (ei.getType() != Graph::Edge::BACK)
508 ei.next();
509 if (ei.getType() != Graph::Edge::BACK)
510 return false;
511 BasicBlock *contBB = BasicBlock::get(ei.getNode());
512
513 if (!contBB->getExit() || contBB->getExit()->op != OP_CONT ||
514 contBB->getExit()->getPredicate())
515 return false;
516 contBB->getExit()->op = OP_BRA;
517 bb->remove(bb->getEntry()); // delete PRECONT
518
519 ei.next();
520 assert(ei.end() || ei.getType() != Graph::Edge::BACK);
521 return true;
522 }
523
524 // replace branches to join blocks with join ops
525 void
526 NVC0LegalizePostRA::propagateJoin(BasicBlock *bb)
527 {
528 if (bb->getEntry()->op != OP_JOIN || bb->getEntry()->asFlow()->limit)
529 return;
530 for (Graph::EdgeIterator ei = bb->cfg.incident(); !ei.end(); ei.next()) {
531 BasicBlock *in = BasicBlock::get(ei.getNode());
532 Instruction *exit = in->getExit();
533 if (!exit) {
534 in->insertTail(new FlowInstruction(func, OP_JOIN, bb));
535 // there should always be a terminator instruction
536 WARN("inserted missing terminator in BB:%i\n", in->getId());
537 } else
538 if (exit->op == OP_BRA) {
539 exit->op = OP_JOIN;
540 exit->asFlow()->limit = 1; // must-not-propagate marker
541 }
542 }
543 bb->remove(bb->getEntry());
544 }
545
546 bool
547 NVC0LegalizePostRA::visit(BasicBlock *bb)
548 {
549 Instruction *i, *next;
550
551 // remove pseudo operations and non-fixed no-ops, split 64 bit operations
552 for (i = bb->getFirst(); i; i = next) {
553 next = i->next;
554 if (i->op == OP_EMIT || i->op == OP_RESTART) {
555 if (!i->getDef(0)->refCount())
556 i->setDef(0, NULL);
557 if (i->src(0).getFile() == FILE_IMMEDIATE)
558 i->setSrc(0, rZero); // initial value must be 0
559 replaceZero(i);
560 } else
561 if (i->isNop()) {
562 bb->remove(i);
563 } else
564 if (i->op == OP_BAR && i->subOp == NV50_IR_SUBOP_BAR_SYNC &&
565 prog->getType() != Program::TYPE_COMPUTE) {
566 // It seems like barriers are never required for tessellation since
567 // the warp size is 32, and there are always at most 32 tcs threads.
568 bb->remove(i);
569 } else
570 if (i->op == OP_LOAD && i->subOp == NV50_IR_SUBOP_LDC_IS) {
571 int offset = i->src(0).get()->reg.data.offset;
572 if (abs(offset) > 0x10000)
573 i->src(0).get()->reg.fileIndex += offset >> 16;
574 i->src(0).get()->reg.data.offset = (int)(short)offset;
575 } else {
576 // TODO: Move this to before register allocation for operations that
577 // need the $c register !
578 if (typeSizeof(i->dType) == 8) {
579 Instruction *hi;
580 hi = BuildUtil::split64BitOpPostRA(func, i, rZero, carry);
581 if (hi)
582 next = hi;
583 }
584
585 if (i->op != OP_MOV && i->op != OP_PFETCH)
586 replaceZero(i);
587 }
588 }
589 if (!bb->getEntry())
590 return true;
591
592 if (!tryReplaceContWithBra(bb))
593 propagateJoin(bb);
594
595 return true;
596 }
597
598 NVC0LoweringPass::NVC0LoweringPass(Program *prog) : targ(prog->getTarget())
599 {
600 bld.setProgram(prog);
601 gMemBase = NULL;
602 }
603
604 bool
605 NVC0LoweringPass::visit(Function *fn)
606 {
607 if (prog->getType() == Program::TYPE_GEOMETRY) {
608 assert(!strncmp(fn->getName(), "MAIN", 4));
609 // TODO: when we generate actual functions pass this value along somehow
610 bld.setPosition(BasicBlock::get(fn->cfg.getRoot()), false);
611 gpEmitAddress = bld.loadImm(NULL, 0)->asLValue();
612 if (fn->cfgExit) {
613 bld.setPosition(BasicBlock::get(fn->cfgExit)->getExit(), false);
614 bld.mkMovToReg(0, gpEmitAddress);
615 }
616 }
617 return true;
618 }
619
620 bool
621 NVC0LoweringPass::visit(BasicBlock *bb)
622 {
623 return true;
624 }
625
626 inline Value *
627 NVC0LoweringPass::loadTexHandle(Value *ptr, unsigned int slot)
628 {
629 uint8_t b = prog->driver->io.auxCBSlot;
630 uint32_t off = prog->driver->io.texBindBase + slot * 4;
631 return bld.
632 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U32, off), ptr);
633 }
634
635 // move array source to first slot, convert to u16, add indirections
636 bool
637 NVC0LoweringPass::handleTEX(TexInstruction *i)
638 {
639 const int dim = i->tex.target.getDim() + i->tex.target.isCube();
640 const int arg = i->tex.target.getArgCount();
641 const int lyr = arg - (i->tex.target.isMS() ? 2 : 1);
642 const int chipset = prog->getTarget()->getChipset();
643
644 /* Only normalize in the non-explicit derivatives case. For explicit
645 * derivatives, this is handled in handleManualTXD.
646 */
647 if (i->tex.target.isCube() && i->dPdx[0].get() == NULL) {
648 Value *src[3], *val;
649 int c;
650 for (c = 0; c < 3; ++c)
651 src[c] = bld.mkOp1v(OP_ABS, TYPE_F32, bld.getSSA(), i->getSrc(c));
652 val = bld.getScratch();
653 bld.mkOp2(OP_MAX, TYPE_F32, val, src[0], src[1]);
654 bld.mkOp2(OP_MAX, TYPE_F32, val, src[2], val);
655 bld.mkOp1(OP_RCP, TYPE_F32, val, val);
656 for (c = 0; c < 3; ++c) {
657 i->setSrc(c, bld.mkOp2v(OP_MUL, TYPE_F32, bld.getSSA(),
658 i->getSrc(c), val));
659 }
660 }
661
662 // Arguments to the TEX instruction are a little insane. Even though the
663 // encoding is identical between SM20 and SM30, the arguments mean
664 // different things between Fermi and Kepler+. A lot of arguments are
665 // optional based on flags passed to the instruction. This summarizes the
666 // order of things.
667 //
668 // Fermi:
669 // array/indirect
670 // coords
671 // sample
672 // lod bias
673 // depth compare
674 // offsets:
675 // - tg4: 8 bits each, either 2 (1 offset reg) or 8 (2 offset reg)
676 // - other: 4 bits each, single reg
677 //
678 // Kepler+:
679 // indirect handle
680 // array (+ offsets for txd in upper 16 bits)
681 // coords
682 // sample
683 // lod bias
684 // depth compare
685 // offsets (same as fermi, except txd which takes it with array)
686 //
687 // Maxwell (tex):
688 // array
689 // coords
690 // indirect handle
691 // sample
692 // lod bias
693 // depth compare
694 // offsets
695 //
696 // Maxwell (txd):
697 // indirect handle
698 // coords
699 // array + offsets
700 // derivatives
701
702 if (chipset >= NVISA_GK104_CHIPSET) {
703 if (i->tex.rIndirectSrc >= 0 || i->tex.sIndirectSrc >= 0) {
704 // XXX this ignores tsc, and assumes a 1:1 mapping
705 assert(i->tex.rIndirectSrc >= 0);
706 Value *hnd = loadTexHandle(
707 bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
708 i->getIndirectR(), bld.mkImm(2)),
709 i->tex.r);
710 i->tex.r = 0xff;
711 i->tex.s = 0x1f;
712 i->setIndirectR(hnd);
713 i->setIndirectS(NULL);
714 } else if (i->tex.r == i->tex.s || i->op == OP_TXF) {
715 i->tex.r += prog->driver->io.texBindBase / 4;
716 i->tex.s = 0; // only a single cX[] value possible here
717 } else {
718 Value *hnd = bld.getScratch();
719 Value *rHnd = loadTexHandle(NULL, i->tex.r);
720 Value *sHnd = loadTexHandle(NULL, i->tex.s);
721
722 bld.mkOp3(OP_INSBF, TYPE_U32, hnd, rHnd, bld.mkImm(0x1400), sHnd);
723
724 i->tex.r = 0; // not used for indirect tex
725 i->tex.s = 0;
726 i->setIndirectR(hnd);
727 }
728 if (i->tex.target.isArray()) {
729 LValue *layer = new_LValue(func, FILE_GPR);
730 Value *src = i->getSrc(lyr);
731 const int sat = (i->op == OP_TXF) ? 1 : 0;
732 DataType sTy = (i->op == OP_TXF) ? TYPE_U32 : TYPE_F32;
733 bld.mkCvt(OP_CVT, TYPE_U16, layer, sTy, src)->saturate = sat;
734 if (i->op != OP_TXD || chipset < NVISA_GM107_CHIPSET) {
735 for (int s = dim; s >= 1; --s)
736 i->setSrc(s, i->getSrc(s - 1));
737 i->setSrc(0, layer);
738 } else {
739 i->setSrc(dim, layer);
740 }
741 }
742 // Move the indirect reference to the first place
743 if (i->tex.rIndirectSrc >= 0 && (
744 i->op == OP_TXD || chipset < NVISA_GM107_CHIPSET)) {
745 Value *hnd = i->getIndirectR();
746
747 i->setIndirectR(NULL);
748 i->moveSources(0, 1);
749 i->setSrc(0, hnd);
750 i->tex.rIndirectSrc = 0;
751 i->tex.sIndirectSrc = -1;
752 }
753 } else
754 // (nvc0) generate and move the tsc/tic/array source to the front
755 if (i->tex.target.isArray() || i->tex.rIndirectSrc >= 0 || i->tex.sIndirectSrc >= 0) {
756 LValue *src = new_LValue(func, FILE_GPR); // 0xttxsaaaa
757
758 Value *ticRel = i->getIndirectR();
759 Value *tscRel = i->getIndirectS();
760
761 if (ticRel) {
762 i->setSrc(i->tex.rIndirectSrc, NULL);
763 if (i->tex.r)
764 ticRel = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getScratch(),
765 ticRel, bld.mkImm(i->tex.r));
766 }
767 if (tscRel) {
768 i->setSrc(i->tex.sIndirectSrc, NULL);
769 if (i->tex.s)
770 tscRel = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getScratch(),
771 tscRel, bld.mkImm(i->tex.s));
772 }
773
774 Value *arrayIndex = i->tex.target.isArray() ? i->getSrc(lyr) : NULL;
775 if (arrayIndex) {
776 for (int s = dim; s >= 1; --s)
777 i->setSrc(s, i->getSrc(s - 1));
778 i->setSrc(0, arrayIndex);
779 } else {
780 i->moveSources(0, 1);
781 }
782
783 if (arrayIndex) {
784 int sat = (i->op == OP_TXF) ? 1 : 0;
785 DataType sTy = (i->op == OP_TXF) ? TYPE_U32 : TYPE_F32;
786 bld.mkCvt(OP_CVT, TYPE_U16, src, sTy, arrayIndex)->saturate = sat;
787 } else {
788 bld.loadImm(src, 0);
789 }
790
791 if (ticRel)
792 bld.mkOp3(OP_INSBF, TYPE_U32, src, ticRel, bld.mkImm(0x0917), src);
793 if (tscRel)
794 bld.mkOp3(OP_INSBF, TYPE_U32, src, tscRel, bld.mkImm(0x0710), src);
795
796 i->setSrc(0, src);
797 }
798
799 // For nvc0, the sample id has to be in the second operand, as the offset
800 // does. Right now we don't know how to pass both in, and this case can't
801 // happen with OpenGL. On nve0, the sample id is part of the texture
802 // coordinate argument.
803 assert(chipset >= NVISA_GK104_CHIPSET ||
804 !i->tex.useOffsets || !i->tex.target.isMS());
805
806 // offset is between lod and dc
807 if (i->tex.useOffsets) {
808 int n, c;
809 int s = i->srcCount(0xff, true);
810 if (i->op != OP_TXD || chipset < NVISA_GK104_CHIPSET) {
811 if (i->tex.target.isShadow())
812 s--;
813 if (i->srcExists(s)) // move potential predicate out of the way
814 i->moveSources(s, 1);
815 if (i->tex.useOffsets == 4 && i->srcExists(s + 1))
816 i->moveSources(s + 1, 1);
817 }
818 if (i->op == OP_TXG) {
819 // Either there is 1 offset, which goes into the 2 low bytes of the
820 // first source, or there are 4 offsets, which go into 2 sources (8
821 // values, 1 byte each).
822 Value *offs[2] = {NULL, NULL};
823 for (n = 0; n < i->tex.useOffsets; n++) {
824 for (c = 0; c < 2; ++c) {
825 if ((n % 2) == 0 && c == 0)
826 offs[n / 2] = i->offset[n][c].get();
827 else
828 bld.mkOp3(OP_INSBF, TYPE_U32,
829 offs[n / 2],
830 i->offset[n][c].get(),
831 bld.mkImm(0x800 | ((n * 16 + c * 8) % 32)),
832 offs[n / 2]);
833 }
834 }
835 i->setSrc(s, offs[0]);
836 if (offs[1])
837 i->setSrc(s + 1, offs[1]);
838 } else {
839 unsigned imm = 0;
840 assert(i->tex.useOffsets == 1);
841 for (c = 0; c < 3; ++c) {
842 ImmediateValue val;
843 if (!i->offset[0][c].getImmediate(val))
844 assert(!"non-immediate offset passed to non-TXG");
845 imm |= (val.reg.data.u32 & 0xf) << (c * 4);
846 }
847 if (i->op == OP_TXD && chipset >= NVISA_GK104_CHIPSET) {
848 // The offset goes into the upper 16 bits of the array index. So
849 // create it if it's not already there, and INSBF it if it already
850 // is.
851 s = (i->tex.rIndirectSrc >= 0) ? 1 : 0;
852 if (chipset >= NVISA_GM107_CHIPSET)
853 s += dim;
854 if (i->tex.target.isArray()) {
855 bld.mkOp3(OP_INSBF, TYPE_U32, i->getSrc(s),
856 bld.loadImm(NULL, imm), bld.mkImm(0xc10),
857 i->getSrc(s));
858 } else {
859 i->moveSources(s, 1);
860 i->setSrc(s, bld.loadImm(NULL, imm << 16));
861 }
862 } else {
863 i->setSrc(s, bld.loadImm(NULL, imm));
864 }
865 }
866 }
867
868 if (chipset >= NVISA_GK104_CHIPSET) {
869 //
870 // If TEX requires more than 4 sources, the 2nd register tuple must be
871 // aligned to 4, even if it consists of just a single 4-byte register.
872 //
873 // XXX HACK: We insert 0 sources to avoid the 5 or 6 regs case.
874 //
875 int s = i->srcCount(0xff, true);
876 if (s > 4 && s < 7) {
877 if (i->srcExists(s)) // move potential predicate out of the way
878 i->moveSources(s, 7 - s);
879 while (s < 7)
880 i->setSrc(s++, bld.loadImm(NULL, 0));
881 }
882 }
883
884 return true;
885 }
886
887 bool
888 NVC0LoweringPass::handleManualTXD(TexInstruction *i)
889 {
890 static const uint8_t qOps[4][2] =
891 {
892 { QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(MOV2, MOV2, ADD, ADD) }, // l0
893 { QUADOP(SUBR, MOV2, SUBR, MOV2), QUADOP(MOV2, MOV2, ADD, ADD) }, // l1
894 { QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(SUBR, SUBR, MOV2, MOV2) }, // l2
895 { QUADOP(SUBR, MOV2, SUBR, MOV2), QUADOP(SUBR, SUBR, MOV2, MOV2) }, // l3
896 };
897 Value *def[4][4];
898 Value *crd[3];
899 Instruction *tex;
900 Value *zero = bld.loadImm(bld.getSSA(), 0);
901 int l, c;
902 const int dim = i->tex.target.getDim() + i->tex.target.isCube();
903
904 // This function is invoked after handleTEX lowering, so we have to expect
905 // the arguments in the order that the hw wants them. For Fermi, array and
906 // indirect are both in the leading arg, while for Kepler, array and
907 // indirect are separate (and both precede the coordinates). Maxwell is
908 // handled in a separate function.
909 unsigned array;
910 if (targ->getChipset() < NVISA_GK104_CHIPSET)
911 array = i->tex.target.isArray() || i->tex.rIndirectSrc >= 0;
912 else
913 array = i->tex.target.isArray() + (i->tex.rIndirectSrc >= 0);
914
915 i->op = OP_TEX; // no need to clone dPdx/dPdy later
916
917 for (c = 0; c < dim; ++c)
918 crd[c] = bld.getScratch();
919
920 bld.mkOp(OP_QUADON, TYPE_NONE, NULL);
921 for (l = 0; l < 4; ++l) {
922 Value *src[3], *val;
923 // mov coordinates from lane l to all lanes
924 for (c = 0; c < dim; ++c)
925 bld.mkQuadop(0x00, crd[c], l, i->getSrc(c + array), zero);
926 // add dPdx from lane l to lanes dx
927 for (c = 0; c < dim; ++c)
928 bld.mkQuadop(qOps[l][0], crd[c], l, i->dPdx[c].get(), crd[c]);
929 // add dPdy from lane l to lanes dy
930 for (c = 0; c < dim; ++c)
931 bld.mkQuadop(qOps[l][1], crd[c], l, i->dPdy[c].get(), crd[c]);
932 // normalize cube coordinates
933 if (i->tex.target.isCube()) {
934 for (c = 0; c < 3; ++c)
935 src[c] = bld.mkOp1v(OP_ABS, TYPE_F32, bld.getSSA(), crd[c]);
936 val = bld.getScratch();
937 bld.mkOp2(OP_MAX, TYPE_F32, val, src[0], src[1]);
938 bld.mkOp2(OP_MAX, TYPE_F32, val, src[2], val);
939 bld.mkOp1(OP_RCP, TYPE_F32, val, val);
940 for (c = 0; c < 3; ++c)
941 src[c] = bld.mkOp2v(OP_MUL, TYPE_F32, bld.getSSA(), crd[c], val);
942 } else {
943 for (c = 0; c < dim; ++c)
944 src[c] = crd[c];
945 }
946 // texture
947 bld.insert(tex = cloneForward(func, i));
948 for (c = 0; c < dim; ++c)
949 tex->setSrc(c + array, src[c]);
950 // save results
951 for (c = 0; i->defExists(c); ++c) {
952 Instruction *mov;
953 def[c][l] = bld.getSSA();
954 mov = bld.mkMov(def[c][l], tex->getDef(c));
955 mov->fixed = 1;
956 mov->lanes = 1 << l;
957 }
958 }
959 bld.mkOp(OP_QUADPOP, TYPE_NONE, NULL);
960
961 for (c = 0; i->defExists(c); ++c) {
962 Instruction *u = bld.mkOp(OP_UNION, TYPE_U32, i->getDef(c));
963 for (l = 0; l < 4; ++l)
964 u->setSrc(l, def[c][l]);
965 }
966
967 i->bb->remove(i);
968 return true;
969 }
970
971 bool
972 NVC0LoweringPass::handleTXD(TexInstruction *txd)
973 {
974 int dim = txd->tex.target.getDim() + txd->tex.target.isCube();
975 unsigned arg = txd->tex.target.getArgCount();
976 unsigned expected_args = arg;
977 const int chipset = prog->getTarget()->getChipset();
978
979 if (chipset >= NVISA_GK104_CHIPSET) {
980 if (!txd->tex.target.isArray() && txd->tex.useOffsets)
981 expected_args++;
982 if (txd->tex.rIndirectSrc >= 0 || txd->tex.sIndirectSrc >= 0)
983 expected_args++;
984 } else {
985 if (txd->tex.useOffsets)
986 expected_args++;
987 if (!txd->tex.target.isArray() && (
988 txd->tex.rIndirectSrc >= 0 || txd->tex.sIndirectSrc >= 0))
989 expected_args++;
990 }
991
992 if (expected_args > 4 ||
993 dim > 2 ||
994 txd->tex.target.isShadow())
995 txd->op = OP_TEX;
996
997 handleTEX(txd);
998 while (txd->srcExists(arg))
999 ++arg;
1000
1001 txd->tex.derivAll = true;
1002 if (txd->op == OP_TEX)
1003 return handleManualTXD(txd);
1004
1005 assert(arg == expected_args);
1006 for (int c = 0; c < dim; ++c) {
1007 txd->setSrc(arg + c * 2 + 0, txd->dPdx[c]);
1008 txd->setSrc(arg + c * 2 + 1, txd->dPdy[c]);
1009 txd->dPdx[c].set(NULL);
1010 txd->dPdy[c].set(NULL);
1011 }
1012
1013 // In this case we have fewer than 4 "real" arguments, which means that
1014 // handleTEX didn't apply any padding. However we have to make sure that
1015 // the second "group" of arguments still gets padded up to 4.
1016 if (chipset >= NVISA_GK104_CHIPSET) {
1017 int s = arg + 2 * dim;
1018 if (s >= 4 && s < 7) {
1019 if (txd->srcExists(s)) // move potential predicate out of the way
1020 txd->moveSources(s, 7 - s);
1021 while (s < 7)
1022 txd->setSrc(s++, bld.loadImm(NULL, 0));
1023 }
1024 }
1025
1026 return true;
1027 }
1028
1029 bool
1030 NVC0LoweringPass::handleTXQ(TexInstruction *txq)
1031 {
1032 const int chipset = prog->getTarget()->getChipset();
1033 if (chipset >= NVISA_GK104_CHIPSET && txq->tex.rIndirectSrc < 0)
1034 txq->tex.r += prog->driver->io.texBindBase / 4;
1035
1036 if (txq->tex.rIndirectSrc < 0)
1037 return true;
1038
1039 Value *ticRel = txq->getIndirectR();
1040
1041 txq->setIndirectS(NULL);
1042 txq->tex.sIndirectSrc = -1;
1043
1044 assert(ticRel);
1045
1046 if (chipset < NVISA_GK104_CHIPSET) {
1047 LValue *src = new_LValue(func, FILE_GPR); // 0xttxsaaaa
1048
1049 txq->setSrc(txq->tex.rIndirectSrc, NULL);
1050 if (txq->tex.r)
1051 ticRel = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getScratch(),
1052 ticRel, bld.mkImm(txq->tex.r));
1053
1054 bld.mkOp2(OP_SHL, TYPE_U32, src, ticRel, bld.mkImm(0x17));
1055
1056 txq->moveSources(0, 1);
1057 txq->setSrc(0, src);
1058 } else {
1059 Value *hnd = loadTexHandle(
1060 bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
1061 txq->getIndirectR(), bld.mkImm(2)),
1062 txq->tex.r);
1063 txq->tex.r = 0xff;
1064 txq->tex.s = 0x1f;
1065
1066 txq->setIndirectR(NULL);
1067 txq->moveSources(0, 1);
1068 txq->setSrc(0, hnd);
1069 txq->tex.rIndirectSrc = 0;
1070 }
1071
1072 return true;
1073 }
1074
1075 bool
1076 NVC0LoweringPass::handleTXLQ(TexInstruction *i)
1077 {
1078 /* The outputs are inverted compared to what the TGSI instruction
1079 * expects. Take that into account in the mask.
1080 */
1081 assert((i->tex.mask & ~3) == 0);
1082 if (i->tex.mask == 1)
1083 i->tex.mask = 2;
1084 else if (i->tex.mask == 2)
1085 i->tex.mask = 1;
1086 handleTEX(i);
1087 bld.setPosition(i, true);
1088
1089 /* The returned values are not quite what we want:
1090 * (a) convert from s16/u16 to f32
1091 * (b) multiply by 1/256
1092 */
1093 for (int def = 0; def < 2; ++def) {
1094 if (!i->defExists(def))
1095 continue;
1096 enum DataType type = TYPE_S16;
1097 if (i->tex.mask == 2 || def > 0)
1098 type = TYPE_U16;
1099 bld.mkCvt(OP_CVT, TYPE_F32, i->getDef(def), type, i->getDef(def));
1100 bld.mkOp2(OP_MUL, TYPE_F32, i->getDef(def),
1101 i->getDef(def), bld.loadImm(NULL, 1.0f / 256));
1102 }
1103 if (i->tex.mask == 3) {
1104 LValue *t = new_LValue(func, FILE_GPR);
1105 bld.mkMov(t, i->getDef(0));
1106 bld.mkMov(i->getDef(0), i->getDef(1));
1107 bld.mkMov(i->getDef(1), t);
1108 }
1109 return true;
1110 }
1111
1112 bool
1113 NVC0LoweringPass::handleBUFQ(Instruction *bufq)
1114 {
1115 bufq->op = OP_MOV;
1116 bufq->setSrc(0, loadBufLength32(bufq->getIndirect(0, 1),
1117 bufq->getSrc(0)->reg.fileIndex * 16));
1118 bufq->setIndirect(0, 0, NULL);
1119 bufq->setIndirect(0, 1, NULL);
1120 return true;
1121 }
1122
1123 void
1124 NVC0LoweringPass::handleSharedATOMNVE4(Instruction *atom)
1125 {
1126 assert(atom->src(0).getFile() == FILE_MEMORY_SHARED);
1127
1128 BasicBlock *currBB = atom->bb;
1129 BasicBlock *tryLockBB = atom->bb->splitBefore(atom, false);
1130 BasicBlock *joinBB = atom->bb->splitAfter(atom);
1131 BasicBlock *setAndUnlockBB = new BasicBlock(func);
1132 BasicBlock *failLockBB = new BasicBlock(func);
1133
1134 bld.setPosition(currBB, true);
1135 assert(!currBB->joinAt);
1136 currBB->joinAt = bld.mkFlow(OP_JOINAT, joinBB, CC_ALWAYS, NULL);
1137
1138 CmpInstruction *pred =
1139 bld.mkCmp(OP_SET, CC_EQ, TYPE_U32, bld.getSSA(1, FILE_PREDICATE),
1140 TYPE_U32, bld.mkImm(0), bld.mkImm(1));
1141
1142 bld.mkFlow(OP_BRA, tryLockBB, CC_ALWAYS, NULL);
1143 currBB->cfg.attach(&tryLockBB->cfg, Graph::Edge::TREE);
1144
1145 bld.setPosition(tryLockBB, true);
1146
1147 Instruction *ld =
1148 bld.mkLoad(TYPE_U32, atom->getDef(0), atom->getSrc(0)->asSym(),
1149 atom->getIndirect(0, 0));
1150 ld->setDef(1, bld.getSSA(1, FILE_PREDICATE));
1151 ld->subOp = NV50_IR_SUBOP_LOAD_LOCKED;
1152
1153 bld.mkFlow(OP_BRA, setAndUnlockBB, CC_P, ld->getDef(1));
1154 bld.mkFlow(OP_BRA, failLockBB, CC_ALWAYS, NULL);
1155 tryLockBB->cfg.attach(&failLockBB->cfg, Graph::Edge::CROSS);
1156 tryLockBB->cfg.attach(&setAndUnlockBB->cfg, Graph::Edge::TREE);
1157
1158 tryLockBB->cfg.detach(&joinBB->cfg);
1159 bld.remove(atom);
1160
1161 bld.setPosition(setAndUnlockBB, true);
1162 Value *stVal;
1163 if (atom->subOp == NV50_IR_SUBOP_ATOM_EXCH) {
1164 // Read the old value, and write the new one.
1165 stVal = atom->getSrc(1);
1166 } else if (atom->subOp == NV50_IR_SUBOP_ATOM_CAS) {
1167 CmpInstruction *set =
1168 bld.mkCmp(OP_SET, CC_EQ, TYPE_U32, bld.getSSA(),
1169 TYPE_U32, ld->getDef(0), atom->getSrc(1));
1170
1171 bld.mkCmp(OP_SLCT, CC_NE, TYPE_U32, (stVal = bld.getSSA()),
1172 TYPE_U32, atom->getSrc(2), ld->getDef(0), set->getDef(0));
1173 } else {
1174 operation op;
1175
1176 switch (atom->subOp) {
1177 case NV50_IR_SUBOP_ATOM_ADD:
1178 op = OP_ADD;
1179 break;
1180 case NV50_IR_SUBOP_ATOM_AND:
1181 op = OP_AND;
1182 break;
1183 case NV50_IR_SUBOP_ATOM_OR:
1184 op = OP_OR;
1185 break;
1186 case NV50_IR_SUBOP_ATOM_XOR:
1187 op = OP_XOR;
1188 break;
1189 case NV50_IR_SUBOP_ATOM_MIN:
1190 op = OP_MIN;
1191 break;
1192 case NV50_IR_SUBOP_ATOM_MAX:
1193 op = OP_MAX;
1194 break;
1195 default:
1196 assert(0);
1197 return;
1198 }
1199
1200 stVal = bld.mkOp2v(op, atom->dType, bld.getSSA(), ld->getDef(0),
1201 atom->getSrc(1));
1202 }
1203
1204 Instruction *st =
1205 bld.mkStore(OP_STORE, TYPE_U32, atom->getSrc(0)->asSym(),
1206 atom->getIndirect(0, 0), stVal);
1207 st->setDef(0, pred->getDef(0));
1208 st->subOp = NV50_IR_SUBOP_STORE_UNLOCKED;
1209
1210 bld.mkFlow(OP_BRA, failLockBB, CC_ALWAYS, NULL);
1211 setAndUnlockBB->cfg.attach(&failLockBB->cfg, Graph::Edge::TREE);
1212
1213 // Lock until the store has not been performed.
1214 bld.setPosition(failLockBB, true);
1215 bld.mkFlow(OP_BRA, tryLockBB, CC_NOT_P, pred->getDef(0));
1216 bld.mkFlow(OP_BRA, joinBB, CC_ALWAYS, NULL);
1217 failLockBB->cfg.attach(&tryLockBB->cfg, Graph::Edge::BACK);
1218 failLockBB->cfg.attach(&joinBB->cfg, Graph::Edge::TREE);
1219
1220 bld.setPosition(joinBB, false);
1221 bld.mkFlow(OP_JOIN, NULL, CC_ALWAYS, NULL)->fixed = 1;
1222 }
1223
1224 void
1225 NVC0LoweringPass::handleSharedATOM(Instruction *atom)
1226 {
1227 assert(atom->src(0).getFile() == FILE_MEMORY_SHARED);
1228
1229 BasicBlock *currBB = atom->bb;
1230 BasicBlock *tryLockAndSetBB = atom->bb->splitBefore(atom, false);
1231 BasicBlock *joinBB = atom->bb->splitAfter(atom);
1232
1233 bld.setPosition(currBB, true);
1234 assert(!currBB->joinAt);
1235 currBB->joinAt = bld.mkFlow(OP_JOINAT, joinBB, CC_ALWAYS, NULL);
1236
1237 bld.mkFlow(OP_BRA, tryLockAndSetBB, CC_ALWAYS, NULL);
1238 currBB->cfg.attach(&tryLockAndSetBB->cfg, Graph::Edge::TREE);
1239
1240 bld.setPosition(tryLockAndSetBB, true);
1241
1242 Instruction *ld =
1243 bld.mkLoad(TYPE_U32, atom->getDef(0), atom->getSrc(0)->asSym(),
1244 atom->getIndirect(0, 0));
1245 ld->setDef(1, bld.getSSA(1, FILE_PREDICATE));
1246 ld->subOp = NV50_IR_SUBOP_LOAD_LOCKED;
1247
1248 Value *stVal;
1249 if (atom->subOp == NV50_IR_SUBOP_ATOM_EXCH) {
1250 // Read the old value, and write the new one.
1251 stVal = atom->getSrc(1);
1252 } else if (atom->subOp == NV50_IR_SUBOP_ATOM_CAS) {
1253 CmpInstruction *set =
1254 bld.mkCmp(OP_SET, CC_EQ, TYPE_U32, bld.getSSA(1, FILE_PREDICATE),
1255 TYPE_U32, ld->getDef(0), atom->getSrc(1));
1256 set->setPredicate(CC_P, ld->getDef(1));
1257
1258 Instruction *selp =
1259 bld.mkOp3(OP_SELP, TYPE_U32, bld.getSSA(), ld->getDef(0),
1260 atom->getSrc(2), set->getDef(0));
1261 selp->src(2).mod = Modifier(NV50_IR_MOD_NOT);
1262 selp->setPredicate(CC_P, ld->getDef(1));
1263
1264 stVal = selp->getDef(0);
1265 } else {
1266 operation op;
1267
1268 switch (atom->subOp) {
1269 case NV50_IR_SUBOP_ATOM_ADD:
1270 op = OP_ADD;
1271 break;
1272 case NV50_IR_SUBOP_ATOM_AND:
1273 op = OP_AND;
1274 break;
1275 case NV50_IR_SUBOP_ATOM_OR:
1276 op = OP_OR;
1277 break;
1278 case NV50_IR_SUBOP_ATOM_XOR:
1279 op = OP_XOR;
1280 break;
1281 case NV50_IR_SUBOP_ATOM_MIN:
1282 op = OP_MIN;
1283 break;
1284 case NV50_IR_SUBOP_ATOM_MAX:
1285 op = OP_MAX;
1286 break;
1287 default:
1288 assert(0);
1289 return;
1290 }
1291
1292 Instruction *i =
1293 bld.mkOp2(op, atom->dType, bld.getSSA(), ld->getDef(0),
1294 atom->getSrc(1));
1295 i->setPredicate(CC_P, ld->getDef(1));
1296
1297 stVal = i->getDef(0);
1298 }
1299
1300 Instruction *st =
1301 bld.mkStore(OP_STORE, TYPE_U32, atom->getSrc(0)->asSym(),
1302 atom->getIndirect(0, 0), stVal);
1303 st->setPredicate(CC_P, ld->getDef(1));
1304 st->subOp = NV50_IR_SUBOP_STORE_UNLOCKED;
1305
1306 // Loop until the lock is acquired.
1307 bld.mkFlow(OP_BRA, tryLockAndSetBB, CC_NOT_P, ld->getDef(1));
1308 tryLockAndSetBB->cfg.attach(&tryLockAndSetBB->cfg, Graph::Edge::BACK);
1309 tryLockAndSetBB->cfg.attach(&joinBB->cfg, Graph::Edge::CROSS);
1310 bld.mkFlow(OP_BRA, joinBB, CC_ALWAYS, NULL);
1311
1312 bld.remove(atom);
1313
1314 bld.setPosition(joinBB, false);
1315 bld.mkFlow(OP_JOIN, NULL, CC_ALWAYS, NULL)->fixed = 1;
1316 }
1317
1318 bool
1319 NVC0LoweringPass::handleATOM(Instruction *atom)
1320 {
1321 SVSemantic sv;
1322 Value *ptr = atom->getIndirect(0, 0), *ind = atom->getIndirect(0, 1), *base;
1323
1324 switch (atom->src(0).getFile()) {
1325 case FILE_MEMORY_LOCAL:
1326 sv = SV_LBASE;
1327 break;
1328 case FILE_MEMORY_SHARED:
1329 // For Fermi/Kepler, we have to use ld lock/st unlock to perform atomic
1330 // operations on shared memory. For Maxwell, ATOMS is enough.
1331 if (targ->getChipset() < NVISA_GK104_CHIPSET)
1332 handleSharedATOM(atom);
1333 else if (targ->getChipset() < NVISA_GM107_CHIPSET)
1334 handleSharedATOMNVE4(atom);
1335 return true;
1336 default:
1337 assert(atom->src(0).getFile() == FILE_MEMORY_BUFFER);
1338 base = loadBufInfo64(ind, atom->getSrc(0)->reg.fileIndex * 16);
1339 assert(base->reg.size == 8);
1340 if (ptr)
1341 base = bld.mkOp2v(OP_ADD, TYPE_U64, base, base, ptr);
1342 assert(base->reg.size == 8);
1343 atom->setIndirect(0, 0, base);
1344 atom->getSrc(0)->reg.file = FILE_MEMORY_GLOBAL;
1345
1346 // Harden against out-of-bounds accesses
1347 Value *offset = bld.loadImm(NULL, atom->getSrc(0)->reg.data.offset + typeSizeof(atom->sType));
1348 Value *length = loadBufLength32(ind, atom->getSrc(0)->reg.fileIndex * 16);
1349 Value *pred = new_LValue(func, FILE_PREDICATE);
1350 if (ptr)
1351 bld.mkOp2(OP_ADD, TYPE_U32, offset, offset, ptr);
1352 bld.mkCmp(OP_SET, CC_GT, TYPE_U32, pred, TYPE_U32, offset, length);
1353 atom->setPredicate(CC_NOT_P, pred);
1354 if (atom->defExists(0)) {
1355 Value *zero, *dst = atom->getDef(0);
1356 atom->setDef(0, bld.getSSA());
1357
1358 bld.setPosition(atom, true);
1359 bld.mkMov((zero = bld.getSSA()), bld.mkImm(0))
1360 ->setPredicate(CC_P, pred);
1361 bld.mkOp2(OP_UNION, TYPE_U32, dst, atom->getDef(0), zero);
1362 }
1363
1364 return true;
1365 }
1366 base =
1367 bld.mkOp1v(OP_RDSV, TYPE_U32, bld.getScratch(), bld.mkSysVal(sv, 0));
1368
1369 atom->setSrc(0, cloneShallow(func, atom->getSrc(0)));
1370 atom->getSrc(0)->reg.file = FILE_MEMORY_GLOBAL;
1371 if (ptr)
1372 base = bld.mkOp2v(OP_ADD, TYPE_U32, base, base, ptr);
1373 atom->setIndirect(0, 1, NULL);
1374 atom->setIndirect(0, 0, base);
1375
1376 return true;
1377 }
1378
1379 bool
1380 NVC0LoweringPass::handleCasExch(Instruction *cas, bool needCctl)
1381 {
1382 if (targ->getChipset() < NVISA_GM107_CHIPSET) {
1383 if (cas->src(0).getFile() == FILE_MEMORY_SHARED) {
1384 // ATOM_CAS and ATOM_EXCH are handled in handleSharedATOM().
1385 return false;
1386 }
1387 }
1388
1389 if (cas->subOp != NV50_IR_SUBOP_ATOM_CAS &&
1390 cas->subOp != NV50_IR_SUBOP_ATOM_EXCH)
1391 return false;
1392 bld.setPosition(cas, true);
1393
1394 if (needCctl) {
1395 Instruction *cctl = bld.mkOp1(OP_CCTL, TYPE_NONE, NULL, cas->getSrc(0));
1396 cctl->setIndirect(0, 0, cas->getIndirect(0, 0));
1397 cctl->fixed = 1;
1398 cctl->subOp = NV50_IR_SUBOP_CCTL_IV;
1399 if (cas->isPredicated())
1400 cctl->setPredicate(cas->cc, cas->getPredicate());
1401 }
1402
1403 if (cas->subOp == NV50_IR_SUBOP_ATOM_CAS) {
1404 // CAS is crazy. It's 2nd source is a double reg, and the 3rd source
1405 // should be set to the high part of the double reg or bad things will
1406 // happen elsewhere in the universe.
1407 // Also, it sometimes returns the new value instead of the old one
1408 // under mysterious circumstances.
1409 Value *dreg = bld.getSSA(8);
1410 bld.setPosition(cas, false);
1411 bld.mkOp2(OP_MERGE, TYPE_U64, dreg, cas->getSrc(1), cas->getSrc(2));
1412 cas->setSrc(1, dreg);
1413 cas->setSrc(2, dreg);
1414 }
1415
1416 return true;
1417 }
1418
1419 inline Value *
1420 NVC0LoweringPass::loadResInfo32(Value *ptr, uint32_t off, uint16_t base)
1421 {
1422 uint8_t b = prog->driver->io.auxCBSlot;
1423 off += base;
1424
1425 return bld.
1426 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U32, off), ptr);
1427 }
1428
1429 inline Value *
1430 NVC0LoweringPass::loadResInfo64(Value *ptr, uint32_t off, uint16_t base)
1431 {
1432 uint8_t b = prog->driver->io.auxCBSlot;
1433 off += base;
1434
1435 if (ptr)
1436 ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getScratch(), ptr, bld.mkImm(4));
1437
1438 return bld.
1439 mkLoadv(TYPE_U64, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U64, off), ptr);
1440 }
1441
1442 inline Value *
1443 NVC0LoweringPass::loadResLength32(Value *ptr, uint32_t off, uint16_t base)
1444 {
1445 uint8_t b = prog->driver->io.auxCBSlot;
1446 off += base;
1447
1448 if (ptr)
1449 ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getScratch(), ptr, bld.mkImm(4));
1450
1451 return bld.
1452 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U64, off + 8), ptr);
1453 }
1454
1455 inline Value *
1456 NVC0LoweringPass::loadSuInfo32(Value *ptr, uint32_t off)
1457 {
1458 return loadResInfo32(ptr, off, prog->driver->io.suInfoBase);
1459 }
1460
1461 inline Value *
1462 NVC0LoweringPass::loadSuInfo64(Value *ptr, uint32_t off)
1463 {
1464 return loadResInfo64(ptr, off, prog->driver->io.suInfoBase);
1465 }
1466
1467 inline Value *
1468 NVC0LoweringPass::loadSuLength32(Value *ptr, uint32_t off)
1469 {
1470 return loadResLength32(ptr, off, prog->driver->io.suInfoBase);
1471 }
1472
1473 inline Value *
1474 NVC0LoweringPass::loadBufInfo32(Value *ptr, uint32_t off)
1475 {
1476 return loadResInfo32(ptr, off, prog->driver->io.bufInfoBase);
1477 }
1478
1479 inline Value *
1480 NVC0LoweringPass::loadBufInfo64(Value *ptr, uint32_t off)
1481 {
1482 return loadResInfo64(ptr, off, prog->driver->io.bufInfoBase);
1483 }
1484
1485 inline Value *
1486 NVC0LoweringPass::loadBufLength32(Value *ptr, uint32_t off)
1487 {
1488 return loadResLength32(ptr, off, prog->driver->io.bufInfoBase);
1489 }
1490
1491 inline Value *
1492 NVC0LoweringPass::loadUboInfo32(Value *ptr, uint32_t off)
1493 {
1494 return loadResInfo32(ptr, off, prog->driver->io.uboInfoBase);
1495 }
1496
1497 inline Value *
1498 NVC0LoweringPass::loadUboInfo64(Value *ptr, uint32_t off)
1499 {
1500 return loadResInfo64(ptr, off, prog->driver->io.uboInfoBase);
1501 }
1502
1503 inline Value *
1504 NVC0LoweringPass::loadUboLength32(Value *ptr, uint32_t off)
1505 {
1506 return loadResLength32(ptr, off, prog->driver->io.uboInfoBase);
1507 }
1508
1509 inline Value *
1510 NVC0LoweringPass::loadMsInfo32(Value *ptr, uint32_t off)
1511 {
1512 uint8_t b = prog->driver->io.msInfoCBSlot;
1513 off += prog->driver->io.msInfoBase;
1514 return bld.
1515 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U32, off), ptr);
1516 }
1517
1518 /* On nvc0, surface info is obtained via the surface binding points passed
1519 * to the SULD/SUST instructions.
1520 * On nve4, surface info is stored in c[] and is used by various special
1521 * instructions, e.g. for clamping coordiantes or generating an address.
1522 * They couldn't just have added an equivalent to TIC now, couldn't they ?
1523 */
1524 #define NVE4_SU_INFO_ADDR 0x00
1525 #define NVE4_SU_INFO_FMT 0x04
1526 #define NVE4_SU_INFO_DIM_X 0x08
1527 #define NVE4_SU_INFO_PITCH 0x0c
1528 #define NVE4_SU_INFO_DIM_Y 0x10
1529 #define NVE4_SU_INFO_ARRAY 0x14
1530 #define NVE4_SU_INFO_DIM_Z 0x18
1531 #define NVE4_SU_INFO_UNK1C 0x1c
1532 #define NVE4_SU_INFO_WIDTH 0x20
1533 #define NVE4_SU_INFO_HEIGHT 0x24
1534 #define NVE4_SU_INFO_DEPTH 0x28
1535 #define NVE4_SU_INFO_TARGET 0x2c
1536 #define NVE4_SU_INFO_BSIZE 0x30
1537 #define NVE4_SU_INFO_RAW_X 0x34
1538 #define NVE4_SU_INFO_MS_X 0x38
1539 #define NVE4_SU_INFO_MS_Y 0x3c
1540
1541 #define NVE4_SU_INFO__STRIDE 0x40
1542
1543 #define NVE4_SU_INFO_DIM(i) (0x08 + (i) * 8)
1544 #define NVE4_SU_INFO_SIZE(i) (0x20 + (i) * 4)
1545 #define NVE4_SU_INFO_MS(i) (0x38 + (i) * 4)
1546
1547 static inline uint16_t getSuClampSubOp(const TexInstruction *su, int c)
1548 {
1549 switch (su->tex.target.getEnum()) {
1550 case TEX_TARGET_BUFFER: return NV50_IR_SUBOP_SUCLAMP_PL(0, 1);
1551 case TEX_TARGET_RECT: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1552 case TEX_TARGET_1D: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1553 case TEX_TARGET_1D_ARRAY: return (c == 1) ?
1554 NV50_IR_SUBOP_SUCLAMP_PL(0, 2) :
1555 NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1556 case TEX_TARGET_2D: return NV50_IR_SUBOP_SUCLAMP_BL(0, 2);
1557 case TEX_TARGET_2D_MS: return NV50_IR_SUBOP_SUCLAMP_BL(0, 2);
1558 case TEX_TARGET_2D_ARRAY: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1559 case TEX_TARGET_2D_MS_ARRAY: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1560 case TEX_TARGET_3D: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1561 case TEX_TARGET_CUBE: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1562 case TEX_TARGET_CUBE_ARRAY: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1563 default:
1564 assert(0);
1565 return 0;
1566 }
1567 }
1568
1569 bool
1570 NVC0LoweringPass::handleSUQ(TexInstruction *suq)
1571 {
1572 int mask = suq->tex.mask;
1573 int dim = suq->tex.target.getDim();
1574 int arg = dim + (suq->tex.target.isArray() || suq->tex.target.isCube());
1575 Value *ind = suq->getIndirectR();
1576 uint32_t base;
1577 int c, d;
1578
1579 if (ind) {
1580 ind = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getSSA(),
1581 ind, bld.mkImm(suq->tex.r));
1582 ind = bld.mkOp2v(OP_AND, TYPE_U32, bld.getSSA(),
1583 ind, bld.mkImm(7));
1584 ind = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
1585 ind, bld.mkImm(6));
1586 base = 0;
1587 } else {
1588 base = suq->tex.r * NVE4_SU_INFO__STRIDE;
1589 }
1590
1591 for (c = 0, d = 0; c < 3; ++c, mask >>= 1) {
1592 if (c >= arg || !(mask & 1))
1593 continue;
1594
1595 int offset;
1596
1597 if (c == 1 && suq->tex.target == TEX_TARGET_1D_ARRAY) {
1598 offset = NVE4_SU_INFO_SIZE(2);
1599 } else {
1600 offset = NVE4_SU_INFO_SIZE(c);
1601 }
1602 bld.mkMov(suq->getDef(d++), loadSuInfo32(ind, base + offset));
1603 if (c == 2 && suq->tex.target.isCube())
1604 bld.mkOp2(OP_DIV, TYPE_U32, suq->getDef(d - 1), suq->getDef(d - 1),
1605 bld.loadImm(NULL, 6));
1606 }
1607
1608 if (mask & 1) {
1609 if (suq->tex.target.isMS()) {
1610 Value *ms_x = loadSuInfo32(ind, base + NVE4_SU_INFO_MS(0));
1611 Value *ms_y = loadSuInfo32(ind, base + NVE4_SU_INFO_MS(1));
1612 Value *ms = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getScratch(), ms_x, ms_y);
1613 bld.mkOp2(OP_SHL, TYPE_U32, suq->getDef(d++), bld.loadImm(NULL, 1), ms);
1614 } else {
1615 bld.mkMov(suq->getDef(d++), bld.loadImm(NULL, 1));
1616 }
1617 }
1618
1619 bld.remove(suq);
1620 return true;
1621 }
1622
1623 void
1624 NVC0LoweringPass::adjustCoordinatesMS(TexInstruction *tex)
1625 {
1626 uint16_t base;
1627 const int arg = tex->tex.target.getArgCount();
1628
1629 if (tex->tex.target == TEX_TARGET_2D_MS)
1630 tex->tex.target = TEX_TARGET_2D;
1631 else
1632 if (tex->tex.target == TEX_TARGET_2D_MS_ARRAY)
1633 tex->tex.target = TEX_TARGET_2D_ARRAY;
1634 else
1635 return;
1636
1637 Value *x = tex->getSrc(0);
1638 Value *y = tex->getSrc(1);
1639 Value *s = tex->getSrc(arg - 1);
1640
1641 Value *tx = bld.getSSA(), *ty = bld.getSSA(), *ts = bld.getSSA();
1642 Value *ind = tex->getIndirectR();
1643
1644 if (ind) {
1645 ind = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getSSA(),
1646 ind, bld.mkImm(tex->tex.r));
1647 ind = bld.mkOp2v(OP_AND, TYPE_U32, bld.getSSA(),
1648 ind, bld.mkImm(7));
1649 ind = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
1650 ind, bld.mkImm(6));
1651 base = 0;
1652 } else {
1653 base = tex->tex.r * NVE4_SU_INFO__STRIDE;
1654 }
1655
1656 Value *ms_x = loadSuInfo32(ind, base + NVE4_SU_INFO_MS(0));
1657 Value *ms_y = loadSuInfo32(ind, base + NVE4_SU_INFO_MS(1));
1658
1659 bld.mkOp2(OP_SHL, TYPE_U32, tx, x, ms_x);
1660 bld.mkOp2(OP_SHL, TYPE_U32, ty, y, ms_y);
1661
1662 s = bld.mkOp2v(OP_AND, TYPE_U32, ts, s, bld.loadImm(NULL, 0x7));
1663 s = bld.mkOp2v(OP_SHL, TYPE_U32, ts, ts, bld.mkImm(3));
1664
1665 Value *dx = loadMsInfo32(ts, 0x0);
1666 Value *dy = loadMsInfo32(ts, 0x4);
1667
1668 bld.mkOp2(OP_ADD, TYPE_U32, tx, tx, dx);
1669 bld.mkOp2(OP_ADD, TYPE_U32, ty, ty, dy);
1670
1671 tex->setSrc(0, tx);
1672 tex->setSrc(1, ty);
1673 tex->moveSources(arg, -1);
1674 }
1675
1676 // Sets 64-bit "generic address", predicate and format sources for SULD/SUST.
1677 // They're computed from the coordinates using the surface info in c[] space.
1678 void
1679 NVC0LoweringPass::processSurfaceCoordsNVE4(TexInstruction *su)
1680 {
1681 Instruction *insn;
1682 const bool atom = su->op == OP_SUREDB || su->op == OP_SUREDP;
1683 const bool raw =
1684 su->op == OP_SULDB || su->op == OP_SUSTB || su->op == OP_SUREDB;
1685 const int idx = su->tex.r;
1686 const int dim = su->tex.target.getDim();
1687 const int arg = dim + (su->tex.target.isArray() || su->tex.target.isCube());
1688 const uint16_t base = idx * NVE4_SU_INFO__STRIDE;
1689 int c;
1690 Value *zero = bld.mkImm(0);
1691 Value *p1 = NULL;
1692 Value *v;
1693 Value *src[3];
1694 Value *bf, *eau, *off;
1695 Value *addr, *pred;
1696 Value *ind = NULL;
1697
1698 off = bld.getScratch(4);
1699 bf = bld.getScratch(4);
1700 addr = bld.getSSA(8);
1701 pred = bld.getScratch(1, FILE_PREDICATE);
1702
1703 bld.setPosition(su, false);
1704
1705 adjustCoordinatesMS(su);
1706
1707 if (su->tex.rIndirectSrc >= 0) {
1708 ind = su->getIndirectR();
1709 if (su->tex.r > 0) {
1710 ind = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getSSA(), ind,
1711 bld.loadImm(NULL, su->tex.r));
1712 }
1713 ind = bld.mkOp2v(OP_AND, TYPE_U32, bld.getSSA(), ind, bld.mkImm(7));
1714 ind = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(), ind, bld.mkImm(6));
1715 }
1716
1717 // calculate clamped coordinates
1718 for (c = 0; c < arg; ++c) {
1719 int dimc = c;
1720
1721 if (c == 1 && su->tex.target == TEX_TARGET_1D_ARRAY) {
1722 // The array index is stored in the Z component for 1D arrays.
1723 dimc = 2;
1724 }
1725
1726 src[c] = bld.getScratch();
1727 if (c == 0 && raw)
1728 v = loadSuInfo32(ind, base + NVE4_SU_INFO_RAW_X);
1729 else
1730 v = loadSuInfo32(ind, base + NVE4_SU_INFO_DIM(dimc));
1731 bld.mkOp3(OP_SUCLAMP, TYPE_S32, src[c], su->getSrc(c), v, zero)
1732 ->subOp = getSuClampSubOp(su, dimc);
1733 }
1734 for (; c < 3; ++c)
1735 src[c] = zero;
1736
1737 // set predicate output
1738 if (su->tex.target == TEX_TARGET_BUFFER) {
1739 src[0]->getInsn()->setFlagsDef(1, pred);
1740 } else
1741 if (su->tex.target.isArray() || su->tex.target.isCube()) {
1742 p1 = bld.getSSA(1, FILE_PREDICATE);
1743 src[dim]->getInsn()->setFlagsDef(1, p1);
1744 }
1745
1746 // calculate pixel offset
1747 if (dim == 1) {
1748 if (su->tex.target != TEX_TARGET_BUFFER)
1749 bld.mkOp2(OP_AND, TYPE_U32, off, src[0], bld.loadImm(NULL, 0xffff));
1750 } else
1751 if (dim == 3) {
1752 v = loadSuInfo32(ind, base + NVE4_SU_INFO_UNK1C);
1753 bld.mkOp3(OP_MADSP, TYPE_U32, off, src[2], v, src[1])
1754 ->subOp = NV50_IR_SUBOP_MADSP(4,2,8); // u16l u16l u16l
1755
1756 v = loadSuInfo32(ind, base + NVE4_SU_INFO_PITCH);
1757 bld.mkOp3(OP_MADSP, TYPE_U32, off, off, v, src[0])
1758 ->subOp = NV50_IR_SUBOP_MADSP(0,2,8); // u32 u16l u16l
1759 } else {
1760 assert(dim == 2);
1761 v = loadSuInfo32(ind, base + NVE4_SU_INFO_PITCH);
1762 bld.mkOp3(OP_MADSP, TYPE_U32, off, src[1], v, src[0])
1763 ->subOp = (su->tex.target.isArray() || su->tex.target.isCube()) ?
1764 NV50_IR_SUBOP_MADSP_SD : NV50_IR_SUBOP_MADSP(4,2,8); // u16l u16l u16l
1765 }
1766
1767 // calculate effective address part 1
1768 if (su->tex.target == TEX_TARGET_BUFFER) {
1769 if (raw) {
1770 bf = src[0];
1771 } else {
1772 v = loadSuInfo32(ind, base + NVE4_SU_INFO_FMT);
1773 bld.mkOp3(OP_VSHL, TYPE_U32, bf, src[0], v, zero)
1774 ->subOp = NV50_IR_SUBOP_V1(7,6,8|2);
1775 }
1776 } else {
1777 Value *y = src[1];
1778 Value *z = src[2];
1779 uint16_t subOp = 0;
1780
1781 switch (dim) {
1782 case 1:
1783 y = zero;
1784 z = zero;
1785 break;
1786 case 2:
1787 z = off;
1788 if (!su->tex.target.isArray() && !su->tex.target.isCube()) {
1789 z = loadSuInfo32(ind, base + NVE4_SU_INFO_UNK1C);
1790 subOp = NV50_IR_SUBOP_SUBFM_3D;
1791 }
1792 break;
1793 default:
1794 subOp = NV50_IR_SUBOP_SUBFM_3D;
1795 assert(dim == 3);
1796 break;
1797 }
1798 insn = bld.mkOp3(OP_SUBFM, TYPE_U32, bf, src[0], y, z);
1799 insn->subOp = subOp;
1800 insn->setFlagsDef(1, pred);
1801 }
1802
1803 // part 2
1804 v = loadSuInfo32(ind, base + NVE4_SU_INFO_ADDR);
1805
1806 if (su->tex.target == TEX_TARGET_BUFFER) {
1807 eau = v;
1808 } else {
1809 eau = bld.mkOp3v(OP_SUEAU, TYPE_U32, bld.getScratch(4), off, bf, v);
1810 }
1811 // add array layer offset
1812 if (su->tex.target.isArray() || su->tex.target.isCube()) {
1813 v = loadSuInfo32(ind, base + NVE4_SU_INFO_ARRAY);
1814 if (dim == 1)
1815 bld.mkOp3(OP_MADSP, TYPE_U32, eau, src[1], v, eau)
1816 ->subOp = NV50_IR_SUBOP_MADSP(4,0,0); // u16 u24 u32
1817 else
1818 bld.mkOp3(OP_MADSP, TYPE_U32, eau, v, src[2], eau)
1819 ->subOp = NV50_IR_SUBOP_MADSP(0,0,0); // u32 u24 u32
1820 // combine predicates
1821 assert(p1);
1822 bld.mkOp2(OP_OR, TYPE_U8, pred, pred, p1);
1823 }
1824
1825 if (atom) {
1826 Value *lo = bf;
1827 if (su->tex.target == TEX_TARGET_BUFFER) {
1828 lo = zero;
1829 bld.mkMov(off, bf);
1830 }
1831 // bf == g[] address & 0xff
1832 // eau == g[] address >> 8
1833 bld.mkOp3(OP_PERMT, TYPE_U32, bf, lo, bld.loadImm(NULL, 0x6540), eau);
1834 bld.mkOp3(OP_PERMT, TYPE_U32, eau, zero, bld.loadImm(NULL, 0x0007), eau);
1835 } else
1836 if (su->op == OP_SULDP && su->tex.target == TEX_TARGET_BUFFER) {
1837 // Convert from u32 to u8 address format, which is what the library code
1838 // doing SULDP currently uses.
1839 // XXX: can SUEAU do this ?
1840 // XXX: does it matter that we don't mask high bytes in bf ?
1841 // Grrr.
1842 bld.mkOp2(OP_SHR, TYPE_U32, off, bf, bld.mkImm(8));
1843 bld.mkOp2(OP_ADD, TYPE_U32, eau, eau, off);
1844 }
1845
1846 bld.mkOp2(OP_MERGE, TYPE_U64, addr, bf, eau);
1847
1848 if (atom && su->tex.target == TEX_TARGET_BUFFER)
1849 bld.mkOp2(OP_ADD, TYPE_U64, addr, addr, off);
1850
1851 // let's just set it 0 for raw access and hope it works
1852 v = raw ?
1853 bld.mkImm(0) : loadSuInfo32(ind, base + NVE4_SU_INFO_FMT);
1854
1855 // get rid of old coordinate sources, make space for fmt info and predicate
1856 su->moveSources(arg, 3 - arg);
1857 // set 64 bit address and 32-bit format sources
1858 su->setSrc(0, addr);
1859 su->setSrc(1, v);
1860 su->setSrc(2, pred);
1861
1862 // prevent read fault when the image is not actually bound
1863 CmpInstruction *pred1 =
1864 bld.mkCmp(OP_SET, CC_EQ, TYPE_U32, bld.getSSA(1, FILE_PREDICATE),
1865 TYPE_U32, bld.mkImm(0),
1866 loadSuInfo32(ind, base + NVE4_SU_INFO_ADDR));
1867
1868 if (su->op != OP_SUSTP && su->tex.format) {
1869 const TexInstruction::ImgFormatDesc *format = su->tex.format;
1870 int blockwidth = format->bits[0] + format->bits[1] +
1871 format->bits[2] + format->bits[3];
1872
1873 // make sure that the format doesn't mismatch
1874 assert(format->components != 0);
1875 bld.mkCmp(OP_SET_OR, CC_NE, TYPE_U32, pred1->getDef(0),
1876 TYPE_U32, bld.loadImm(NULL, blockwidth / 8),
1877 loadSuInfo32(ind, base + NVE4_SU_INFO_BSIZE),
1878 pred1->getDef(0));
1879 }
1880 su->setPredicate(CC_NOT_P, pred1->getDef(0));
1881
1882 // TODO: initialize def values to 0 when the surface operation is not
1883 // performed (not needed for stores). Also, fix the "address bounds test"
1884 // subtests from arb_shader_image_load_store-invalid for buffers, because it
1885 // seems like that the predicate is not correctly set by suclamp.
1886 }
1887
1888 static DataType
1889 getSrcType(const TexInstruction::ImgFormatDesc *t, int c)
1890 {
1891 switch (t->type) {
1892 case FLOAT: return t->bits[c] == 16 ? TYPE_F16 : TYPE_F32;
1893 case UNORM: return t->bits[c] == 8 ? TYPE_U8 : TYPE_U16;
1894 case SNORM: return t->bits[c] == 8 ? TYPE_S8 : TYPE_S16;
1895 case UINT:
1896 return (t->bits[c] == 8 ? TYPE_U8 :
1897 (t->bits[c] == 16 ? TYPE_U16 : TYPE_U32));
1898 case SINT:
1899 return (t->bits[c] == 8 ? TYPE_S8 :
1900 (t->bits[c] == 16 ? TYPE_S16 : TYPE_S32));
1901 }
1902 return TYPE_NONE;
1903 }
1904
1905 static DataType
1906 getDestType(const ImgType type) {
1907 switch (type) {
1908 case FLOAT:
1909 case UNORM:
1910 case SNORM:
1911 return TYPE_F32;
1912 case UINT:
1913 return TYPE_U32;
1914 case SINT:
1915 return TYPE_S32;
1916 default:
1917 assert(!"Impossible type");
1918 return TYPE_NONE;
1919 }
1920 }
1921
1922 void
1923 NVC0LoweringPass::convertSurfaceFormat(TexInstruction *su)
1924 {
1925 const TexInstruction::ImgFormatDesc *format = su->tex.format;
1926 int width = format->bits[0] + format->bits[1] +
1927 format->bits[2] + format->bits[3];
1928 Value *untypedDst[4] = {};
1929 Value *typedDst[4] = {};
1930
1931 // We must convert this to a generic load.
1932 su->op = OP_SULDB;
1933
1934 su->dType = typeOfSize(width / 8);
1935 su->sType = TYPE_U8;
1936
1937 for (int i = 0; i < width / 32; i++)
1938 untypedDst[i] = bld.getSSA();
1939 if (width < 32)
1940 untypedDst[0] = bld.getSSA();
1941
1942 for (int i = 0; i < 4; i++) {
1943 typedDst[i] = su->getDef(i);
1944 }
1945
1946 // Set the untyped dsts as the su's destinations
1947 for (int i = 0; i < 4; i++)
1948 su->setDef(i, untypedDst[i]);
1949
1950 bld.setPosition(su, true);
1951
1952 // Unpack each component into the typed dsts
1953 int bits = 0;
1954 for (int i = 0; i < 4; bits += format->bits[i], i++) {
1955 if (!typedDst[i])
1956 continue;
1957 if (i >= format->components) {
1958 if (format->type == FLOAT ||
1959 format->type == UNORM ||
1960 format->type == SNORM)
1961 bld.loadImm(typedDst[i], i == 3 ? 1.0f : 0.0f);
1962 else
1963 bld.loadImm(typedDst[i], i == 3 ? 1 : 0);
1964 continue;
1965 }
1966
1967 // Get just that component's data into the relevant place
1968 if (format->bits[i] == 32)
1969 bld.mkMov(typedDst[i], untypedDst[i]);
1970 else if (format->bits[i] == 16)
1971 bld.mkCvt(OP_CVT, getDestType(format->type), typedDst[i],
1972 getSrcType(format, i), untypedDst[i / 2])
1973 ->subOp = (i & 1) << (format->type == FLOAT ? 0 : 1);
1974 else if (format->bits[i] == 8)
1975 bld.mkCvt(OP_CVT, getDestType(format->type), typedDst[i],
1976 getSrcType(format, i), untypedDst[0])->subOp = i;
1977 else {
1978 bld.mkOp2(OP_EXTBF, TYPE_U32, typedDst[i], untypedDst[bits / 32],
1979 bld.mkImm((bits % 32) | (format->bits[i] << 8)));
1980 if (format->type == UNORM || format->type == SNORM)
1981 bld.mkCvt(OP_CVT, TYPE_F32, typedDst[i], getSrcType(format, i), typedDst[i]);
1982 }
1983
1984 // Normalize / convert as necessary
1985 if (format->type == UNORM)
1986 bld.mkOp2(OP_MUL, TYPE_F32, typedDst[i], typedDst[i], bld.loadImm(NULL, 1.0f / ((1 << format->bits[i]) - 1)));
1987 else if (format->type == SNORM)
1988 bld.mkOp2(OP_MUL, TYPE_F32, typedDst[i], typedDst[i], bld.loadImm(NULL, 1.0f / ((1 << (format->bits[i] - 1)) - 1)));
1989 else if (format->type == FLOAT && format->bits[i] < 16) {
1990 bld.mkOp2(OP_SHL, TYPE_U32, typedDst[i], typedDst[i], bld.loadImm(NULL, 15 - format->bits[i]));
1991 bld.mkCvt(OP_CVT, TYPE_F32, typedDst[i], TYPE_F16, typedDst[i]);
1992 }
1993 }
1994 }
1995
1996 void
1997 NVC0LoweringPass::handleSurfaceOpNVE4(TexInstruction *su)
1998 {
1999 processSurfaceCoordsNVE4(su);
2000
2001 if (su->op == OP_SULDP)
2002 convertSurfaceFormat(su);
2003
2004 if (su->op == OP_SUREDB || su->op == OP_SUREDP) {
2005 Value *pred = su->getSrc(2);
2006 CondCode cc = CC_NOT_P;
2007 if (su->getPredicate()) {
2008 pred = bld.getScratch(1, FILE_PREDICATE);
2009 cc = su->cc;
2010 if (cc == CC_NOT_P) {
2011 bld.mkOp2(OP_OR, TYPE_U8, pred, su->getPredicate(), su->getSrc(2));
2012 } else {
2013 bld.mkOp2(OP_AND, TYPE_U8, pred, su->getPredicate(), su->getSrc(2));
2014 pred->getInsn()->src(1).mod = Modifier(NV50_IR_MOD_NOT);
2015 }
2016 }
2017 Instruction *red = bld.mkOp(OP_ATOM, su->dType, bld.getSSA());
2018 red->subOp = su->subOp;
2019 if (!gMemBase)
2020 gMemBase = bld.mkSymbol(FILE_MEMORY_GLOBAL, 0, TYPE_U32, 0);
2021 red->setSrc(0, gMemBase);
2022 red->setSrc(1, su->getSrc(3));
2023 if (su->subOp == NV50_IR_SUBOP_ATOM_CAS)
2024 red->setSrc(2, su->getSrc(4));
2025 red->setIndirect(0, 0, su->getSrc(0));
2026
2027 // make sure to initialize dst value when the atomic operation is not
2028 // performed
2029 Instruction *mov = bld.mkMov(bld.getSSA(), bld.loadImm(NULL, 0));
2030
2031 assert(cc == CC_NOT_P);
2032 red->setPredicate(cc, pred);
2033 mov->setPredicate(CC_P, pred);
2034
2035 bld.mkOp2(OP_UNION, TYPE_U32, su->getDef(0),
2036 red->getDef(0), mov->getDef(0));
2037
2038 delete_Instruction(bld.getProgram(), su);
2039 handleCasExch(red, true);
2040 }
2041
2042 if (su->op == OP_SUSTB || su->op == OP_SUSTP)
2043 su->sType = (su->tex.target == TEX_TARGET_BUFFER) ? TYPE_U32 : TYPE_U8;
2044 }
2045
2046 void
2047 NVC0LoweringPass::processSurfaceCoordsNVC0(TexInstruction *su)
2048 {
2049 const int idx = su->tex.r;
2050 const int dim = su->tex.target.getDim();
2051 const int arg = dim + (su->tex.target.isArray() || su->tex.target.isCube());
2052 const uint16_t base = idx * NVE4_SU_INFO__STRIDE;
2053 int c;
2054 Value *zero = bld.mkImm(0);
2055 Value *src[3];
2056 Value *v;
2057 Value *ind = NULL;
2058
2059 bld.setPosition(su, false);
2060
2061 adjustCoordinatesMS(su);
2062
2063 if (su->tex.rIndirectSrc >= 0) {
2064 ind = su->getIndirectR();
2065 if (su->tex.r > 0) {
2066 ind = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getSSA(), ind,
2067 bld.loadImm(NULL, su->tex.r));
2068 }
2069 ind = bld.mkOp2v(OP_AND, TYPE_U32, bld.getSSA(), ind, bld.mkImm(7));
2070 ind = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(), ind, bld.mkImm(6));
2071 }
2072
2073 // get surface coordinates
2074 for (c = 0; c < arg; ++c)
2075 src[c] = su->getSrc(c);
2076 for (; c < 3; ++c)
2077 src[c] = zero;
2078
2079 // calculate pixel offset
2080 if (su->op == OP_SULDP || su->op == OP_SUREDP) {
2081 v = loadSuInfo32(ind, base + NVE4_SU_INFO_BSIZE);
2082 su->setSrc(0, bld.mkOp2v(OP_MUL, TYPE_U32, bld.getSSA(), src[0], v));
2083 }
2084
2085 // add array layer offset
2086 if (su->tex.target.isArray() || su->tex.target.isCube()) {
2087 v = loadSuInfo32(ind, base + NVE4_SU_INFO_ARRAY);
2088 assert(dim > 1);
2089 su->setSrc(2, bld.mkOp2v(OP_MUL, TYPE_U32, bld.getSSA(), src[2], v));
2090 }
2091
2092 // prevent read fault when the image is not actually bound
2093 CmpInstruction *pred =
2094 bld.mkCmp(OP_SET, CC_EQ, TYPE_U32, bld.getSSA(1, FILE_PREDICATE),
2095 TYPE_U32, bld.mkImm(0),
2096 loadSuInfo32(ind, base + NVE4_SU_INFO_ADDR));
2097 if (su->op != OP_SUSTP && su->tex.format) {
2098 const TexInstruction::ImgFormatDesc *format = su->tex.format;
2099 int blockwidth = format->bits[0] + format->bits[1] +
2100 format->bits[2] + format->bits[3];
2101
2102 assert(format->components != 0);
2103 // make sure that the format doesn't mismatch when it's not FMT_NONE
2104 bld.mkCmp(OP_SET_OR, CC_NE, TYPE_U32, pred->getDef(0),
2105 TYPE_U32, bld.loadImm(NULL, blockwidth / 8),
2106 loadSuInfo32(ind, base + NVE4_SU_INFO_BSIZE),
2107 pred->getDef(0));
2108 }
2109 su->setPredicate(CC_NOT_P, pred->getDef(0));
2110 }
2111
2112 void
2113 NVC0LoweringPass::handleSurfaceOpNVC0(TexInstruction *su)
2114 {
2115 if (su->tex.target == TEX_TARGET_1D_ARRAY) {
2116 /* As 1d arrays also need 3 coordinates, switching to TEX_TARGET_2D_ARRAY
2117 * will simplify the lowering pass and the texture constraints. */
2118 su->moveSources(1, 1);
2119 su->setSrc(1, bld.loadImm(NULL, 0));
2120 su->tex.target = TEX_TARGET_2D_ARRAY;
2121 }
2122
2123 processSurfaceCoordsNVC0(su);
2124
2125 if (su->op == OP_SULDP)
2126 convertSurfaceFormat(su);
2127
2128 if (su->op == OP_SUREDB || su->op == OP_SUREDP) {
2129 const int dim = su->tex.target.getDim();
2130 const int arg = dim + (su->tex.target.isArray() || su->tex.target.isCube());
2131 LValue *addr = bld.getSSA(8);
2132 Value *def = su->getDef(0);
2133
2134 su->op = OP_SULEA;
2135
2136 // Set the destination to the address
2137 su->dType = TYPE_U64;
2138 su->setDef(0, addr);
2139 su->setDef(1, su->getPredicate());
2140
2141 bld.setPosition(su, true);
2142
2143 // Perform the atomic op
2144 Instruction *red = bld.mkOp(OP_ATOM, su->sType, bld.getSSA());
2145 red->subOp = su->subOp;
2146 red->setSrc(0, bld.mkSymbol(FILE_MEMORY_GLOBAL, 0, su->sType, 0));
2147 red->setSrc(1, su->getSrc(arg));
2148 if (red->subOp == NV50_IR_SUBOP_ATOM_CAS)
2149 red->setSrc(2, su->getSrc(arg + 1));
2150 red->setIndirect(0, 0, addr);
2151
2152 // make sure to initialize dst value when the atomic operation is not
2153 // performed
2154 Instruction *mov = bld.mkMov(bld.getSSA(), bld.loadImm(NULL, 0));
2155
2156 assert(su->cc == CC_NOT_P);
2157 red->setPredicate(su->cc, su->getPredicate());
2158 mov->setPredicate(CC_P, su->getPredicate());
2159
2160 bld.mkOp2(OP_UNION, TYPE_U32, def, red->getDef(0), mov->getDef(0));
2161
2162 handleCasExch(red, false);
2163 }
2164 }
2165
2166 bool
2167 NVC0LoweringPass::handleWRSV(Instruction *i)
2168 {
2169 Instruction *st;
2170 Symbol *sym;
2171 uint32_t addr;
2172
2173 // must replace, $sreg are not writeable
2174 addr = targ->getSVAddress(FILE_SHADER_OUTPUT, i->getSrc(0)->asSym());
2175 if (addr >= 0x400)
2176 return false;
2177 sym = bld.mkSymbol(FILE_SHADER_OUTPUT, 0, i->sType, addr);
2178
2179 st = bld.mkStore(OP_EXPORT, i->dType, sym, i->getIndirect(0, 0),
2180 i->getSrc(1));
2181 st->perPatch = i->perPatch;
2182
2183 bld.getBB()->remove(i);
2184 return true;
2185 }
2186
2187 void
2188 NVC0LoweringPass::handleLDST(Instruction *i)
2189 {
2190 if (i->src(0).getFile() == FILE_SHADER_INPUT) {
2191 if (prog->getType() == Program::TYPE_COMPUTE) {
2192 i->getSrc(0)->reg.file = FILE_MEMORY_CONST;
2193 i->getSrc(0)->reg.fileIndex = 0;
2194 } else
2195 if (prog->getType() == Program::TYPE_GEOMETRY &&
2196 i->src(0).isIndirect(0)) {
2197 // XXX: this assumes vec4 units
2198 Value *ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
2199 i->getIndirect(0, 0), bld.mkImm(4));
2200 i->setIndirect(0, 0, ptr);
2201 i->op = OP_VFETCH;
2202 } else {
2203 i->op = OP_VFETCH;
2204 assert(prog->getType() != Program::TYPE_FRAGMENT); // INTERP
2205 }
2206 } else if (i->src(0).getFile() == FILE_MEMORY_CONST) {
2207 if (targ->getChipset() >= NVISA_GK104_CHIPSET &&
2208 prog->getType() == Program::TYPE_COMPUTE) {
2209 // The launch descriptor only allows to set up 8 CBs, but OpenGL
2210 // requires at least 12 UBOs. To bypass this limitation, we store the
2211 // addrs into the driver constbuf and we directly load from the global
2212 // memory.
2213 int8_t fileIndex = i->getSrc(0)->reg.fileIndex - 1;
2214 Value *ind = i->getIndirect(0, 1);
2215
2216 if (ind) {
2217 // Clamp the UBO index when an indirect access is used to avoid
2218 // loading information from the wrong place in the driver cb.
2219 ind = bld.mkOp2v(OP_MIN, TYPE_U32, ind,
2220 bld.mkOp2v(OP_ADD, TYPE_U32, bld.getSSA(),
2221 ind, bld.loadImm(NULL, fileIndex)),
2222 bld.loadImm(NULL, 12));
2223 }
2224
2225 if (i->src(0).isIndirect(1)) {
2226 Value *offset = bld.loadImm(NULL, i->getSrc(0)->reg.data.offset + typeSizeof(i->sType));
2227 Value *ptr = loadUboInfo64(ind, fileIndex * 16);
2228 Value *length = loadUboLength32(ind, fileIndex * 16);
2229 Value *pred = new_LValue(func, FILE_PREDICATE);
2230 if (i->src(0).isIndirect(0)) {
2231 bld.mkOp2(OP_ADD, TYPE_U64, ptr, ptr, i->getIndirect(0, 0));
2232 bld.mkOp2(OP_ADD, TYPE_U32, offset, offset, i->getIndirect(0, 0));
2233 }
2234 i->getSrc(0)->reg.file = FILE_MEMORY_GLOBAL;
2235 i->setIndirect(0, 1, NULL);
2236 i->setIndirect(0, 0, ptr);
2237 bld.mkCmp(OP_SET, CC_GT, TYPE_U32, pred, TYPE_U32, offset, length);
2238 i->setPredicate(CC_NOT_P, pred);
2239 if (i->defExists(0)) {
2240 bld.mkMov(i->getDef(0), bld.mkImm(0));
2241 }
2242 } else if (fileIndex >= 0) {
2243 Value *ptr = loadUboInfo64(ind, fileIndex * 16);
2244 if (i->src(0).isIndirect(0)) {
2245 bld.mkOp2(OP_ADD, TYPE_U64, ptr, ptr, i->getIndirect(0, 0));
2246 }
2247 i->getSrc(0)->reg.file = FILE_MEMORY_GLOBAL;
2248 i->setIndirect(0, 1, NULL);
2249 i->setIndirect(0, 0, ptr);
2250 }
2251 } else if (i->src(0).isIndirect(1)) {
2252 Value *ptr;
2253 if (i->src(0).isIndirect(0))
2254 ptr = bld.mkOp3v(OP_INSBF, TYPE_U32, bld.getSSA(),
2255 i->getIndirect(0, 1), bld.mkImm(0x1010),
2256 i->getIndirect(0, 0));
2257 else
2258 ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
2259 i->getIndirect(0, 1), bld.mkImm(16));
2260 i->setIndirect(0, 1, NULL);
2261 i->setIndirect(0, 0, ptr);
2262 i->subOp = NV50_IR_SUBOP_LDC_IS;
2263 }
2264 } else if (i->src(0).getFile() == FILE_SHADER_OUTPUT) {
2265 assert(prog->getType() == Program::TYPE_TESSELLATION_CONTROL);
2266 i->op = OP_VFETCH;
2267 } else if (i->src(0).getFile() == FILE_MEMORY_BUFFER) {
2268 Value *ind = i->getIndirect(0, 1);
2269 Value *ptr = loadBufInfo64(ind, i->getSrc(0)->reg.fileIndex * 16);
2270 // XXX come up with a way not to do this for EVERY little access but
2271 // rather to batch these up somehow. Unfortunately we've lost the
2272 // information about the field width by the time we get here.
2273 Value *offset = bld.loadImm(NULL, i->getSrc(0)->reg.data.offset + typeSizeof(i->sType));
2274 Value *length = loadBufLength32(ind, i->getSrc(0)->reg.fileIndex * 16);
2275 Value *pred = new_LValue(func, FILE_PREDICATE);
2276 if (i->src(0).isIndirect(0)) {
2277 bld.mkOp2(OP_ADD, TYPE_U64, ptr, ptr, i->getIndirect(0, 0));
2278 bld.mkOp2(OP_ADD, TYPE_U32, offset, offset, i->getIndirect(0, 0));
2279 }
2280 i->setIndirect(0, 1, NULL);
2281 i->setIndirect(0, 0, ptr);
2282 i->getSrc(0)->reg.file = FILE_MEMORY_GLOBAL;
2283 bld.mkCmp(OP_SET, CC_GT, TYPE_U32, pred, TYPE_U32, offset, length);
2284 i->setPredicate(CC_NOT_P, pred);
2285 if (i->defExists(0)) {
2286 Value *zero, *dst = i->getDef(0);
2287 i->setDef(0, bld.getSSA());
2288
2289 bld.setPosition(i, true);
2290 bld.mkMov((zero = bld.getSSA()), bld.mkImm(0))
2291 ->setPredicate(CC_P, pred);
2292 bld.mkOp2(OP_UNION, TYPE_U32, dst, i->getDef(0), zero);
2293 }
2294 }
2295 }
2296
2297 void
2298 NVC0LoweringPass::readTessCoord(LValue *dst, int c)
2299 {
2300 Value *laneid = bld.getSSA();
2301 Value *x, *y;
2302
2303 bld.mkOp1(OP_RDSV, TYPE_U32, laneid, bld.mkSysVal(SV_LANEID, 0));
2304
2305 if (c == 0) {
2306 x = dst;
2307 y = NULL;
2308 } else
2309 if (c == 1) {
2310 x = NULL;
2311 y = dst;
2312 } else {
2313 assert(c == 2);
2314 if (prog->driver->prop.tp.domain != PIPE_PRIM_TRIANGLES) {
2315 bld.mkMov(dst, bld.loadImm(NULL, 0));
2316 return;
2317 }
2318 x = bld.getSSA();
2319 y = bld.getSSA();
2320 }
2321 if (x)
2322 bld.mkFetch(x, TYPE_F32, FILE_SHADER_OUTPUT, 0x2f0, NULL, laneid);
2323 if (y)
2324 bld.mkFetch(y, TYPE_F32, FILE_SHADER_OUTPUT, 0x2f4, NULL, laneid);
2325
2326 if (c == 2) {
2327 bld.mkOp2(OP_ADD, TYPE_F32, dst, x, y);
2328 bld.mkOp2(OP_SUB, TYPE_F32, dst, bld.loadImm(NULL, 1.0f), dst);
2329 }
2330 }
2331
2332 bool
2333 NVC0LoweringPass::handleRDSV(Instruction *i)
2334 {
2335 Symbol *sym = i->getSrc(0)->asSym();
2336 const SVSemantic sv = sym->reg.data.sv.sv;
2337 Value *vtx = NULL;
2338 Instruction *ld;
2339 uint32_t addr = targ->getSVAddress(FILE_SHADER_INPUT, sym);
2340
2341 if (addr >= 0x400) {
2342 // mov $sreg
2343 if (sym->reg.data.sv.index == 3) {
2344 // TGSI backend may use 4th component of TID,NTID,CTAID,NCTAID
2345 i->op = OP_MOV;
2346 i->setSrc(0, bld.mkImm((sv == SV_NTID || sv == SV_NCTAID) ? 1 : 0));
2347 }
2348 if (sv == SV_VERTEX_COUNT) {
2349 bld.setPosition(i, true);
2350 bld.mkOp2(OP_EXTBF, TYPE_U32, i->getDef(0), i->getDef(0), bld.mkImm(0x808));
2351 }
2352 return true;
2353 }
2354
2355 switch (sv) {
2356 case SV_POSITION:
2357 assert(prog->getType() == Program::TYPE_FRAGMENT);
2358 if (i->srcExists(1)) {
2359 // Pass offset through to the interpolation logic
2360 ld = bld.mkInterp(NV50_IR_INTERP_LINEAR | NV50_IR_INTERP_OFFSET,
2361 i->getDef(0), addr, NULL);
2362 ld->setSrc(1, i->getSrc(1));
2363 } else {
2364 bld.mkInterp(NV50_IR_INTERP_LINEAR, i->getDef(0), addr, NULL);
2365 }
2366 break;
2367 case SV_FACE:
2368 {
2369 Value *face = i->getDef(0);
2370 bld.mkInterp(NV50_IR_INTERP_FLAT, face, addr, NULL);
2371 if (i->dType == TYPE_F32) {
2372 bld.mkOp2(OP_OR, TYPE_U32, face, face, bld.mkImm(0x00000001));
2373 bld.mkOp1(OP_NEG, TYPE_S32, face, face);
2374 bld.mkCvt(OP_CVT, TYPE_F32, face, TYPE_S32, face);
2375 }
2376 }
2377 break;
2378 case SV_TESS_COORD:
2379 assert(prog->getType() == Program::TYPE_TESSELLATION_EVAL);
2380 readTessCoord(i->getDef(0)->asLValue(), i->getSrc(0)->reg.data.sv.index);
2381 break;
2382 case SV_NTID:
2383 case SV_NCTAID:
2384 case SV_GRIDID:
2385 assert(targ->getChipset() >= NVISA_GK104_CHIPSET); // mov $sreg otherwise
2386 if (sym->reg.data.sv.index == 3) {
2387 i->op = OP_MOV;
2388 i->setSrc(0, bld.mkImm(sv == SV_GRIDID ? 0 : 1));
2389 return true;
2390 }
2391 addr += prog->driver->prop.cp.gridInfoBase;
2392 bld.mkLoad(TYPE_U32, i->getDef(0),
2393 bld.mkSymbol(FILE_MEMORY_CONST, prog->driver->io.auxCBSlot,
2394 TYPE_U32, addr), NULL);
2395 break;
2396 case SV_SAMPLE_INDEX:
2397 // TODO: Properly pass source as an address in the PIX address space
2398 // (which can be of the form [r0+offset]). But this is currently
2399 // unnecessary.
2400 ld = bld.mkOp1(OP_PIXLD, TYPE_U32, i->getDef(0), bld.mkImm(0));
2401 ld->subOp = NV50_IR_SUBOP_PIXLD_SAMPLEID;
2402 break;
2403 case SV_SAMPLE_POS: {
2404 Value *off = new_LValue(func, FILE_GPR);
2405 ld = bld.mkOp1(OP_PIXLD, TYPE_U32, i->getDef(0), bld.mkImm(0));
2406 ld->subOp = NV50_IR_SUBOP_PIXLD_SAMPLEID;
2407 bld.mkOp2(OP_SHL, TYPE_U32, off, i->getDef(0), bld.mkImm(3));
2408 bld.mkLoad(TYPE_F32,
2409 i->getDef(0),
2410 bld.mkSymbol(
2411 FILE_MEMORY_CONST, prog->driver->io.auxCBSlot,
2412 TYPE_U32, prog->driver->io.sampleInfoBase +
2413 4 * sym->reg.data.sv.index),
2414 off);
2415 break;
2416 }
2417 case SV_SAMPLE_MASK: {
2418 ld = bld.mkOp1(OP_PIXLD, TYPE_U32, i->getDef(0), bld.mkImm(0));
2419 ld->subOp = NV50_IR_SUBOP_PIXLD_COVMASK;
2420 Instruction *sampleid =
2421 bld.mkOp1(OP_PIXLD, TYPE_U32, bld.getSSA(), bld.mkImm(0));
2422 sampleid->subOp = NV50_IR_SUBOP_PIXLD_SAMPLEID;
2423 Value *masked =
2424 bld.mkOp2v(OP_AND, TYPE_U32, bld.getSSA(), ld->getDef(0),
2425 bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
2426 bld.loadImm(NULL, 1), sampleid->getDef(0)));
2427 if (prog->driver->prop.fp.persampleInvocation) {
2428 bld.mkMov(i->getDef(0), masked);
2429 } else {
2430 bld.mkOp3(OP_SELP, TYPE_U32, i->getDef(0), ld->getDef(0), masked,
2431 bld.mkImm(0))
2432 ->subOp = 1;
2433 }
2434 break;
2435 }
2436 case SV_BASEVERTEX:
2437 case SV_BASEINSTANCE:
2438 case SV_DRAWID:
2439 ld = bld.mkLoad(TYPE_U32, i->getDef(0),
2440 bld.mkSymbol(FILE_MEMORY_CONST,
2441 prog->driver->io.auxCBSlot,
2442 TYPE_U32,
2443 prog->driver->io.drawInfoBase +
2444 4 * (sv - SV_BASEVERTEX)),
2445 NULL);
2446 break;
2447 default:
2448 if (prog->getType() == Program::TYPE_TESSELLATION_EVAL && !i->perPatch)
2449 vtx = bld.mkOp1v(OP_PFETCH, TYPE_U32, bld.getSSA(), bld.mkImm(0));
2450 ld = bld.mkFetch(i->getDef(0), i->dType,
2451 FILE_SHADER_INPUT, addr, i->getIndirect(0, 0), vtx);
2452 ld->perPatch = i->perPatch;
2453 break;
2454 }
2455 bld.getBB()->remove(i);
2456 return true;
2457 }
2458
2459 bool
2460 NVC0LoweringPass::handleDIV(Instruction *i)
2461 {
2462 if (!isFloatType(i->dType))
2463 return true;
2464 bld.setPosition(i, false);
2465 Instruction *rcp = bld.mkOp1(OP_RCP, i->dType, bld.getSSA(typeSizeof(i->dType)), i->getSrc(1));
2466 i->op = OP_MUL;
2467 i->setSrc(1, rcp->getDef(0));
2468 return true;
2469 }
2470
2471 bool
2472 NVC0LoweringPass::handleMOD(Instruction *i)
2473 {
2474 if (!isFloatType(i->dType))
2475 return true;
2476 LValue *value = bld.getScratch(typeSizeof(i->dType));
2477 bld.mkOp1(OP_RCP, i->dType, value, i->getSrc(1));
2478 bld.mkOp2(OP_MUL, i->dType, value, i->getSrc(0), value);
2479 bld.mkOp1(OP_TRUNC, i->dType, value, value);
2480 bld.mkOp2(OP_MUL, i->dType, value, i->getSrc(1), value);
2481 i->op = OP_SUB;
2482 i->setSrc(1, value);
2483 return true;
2484 }
2485
2486 bool
2487 NVC0LoweringPass::handleSQRT(Instruction *i)
2488 {
2489 if (i->dType == TYPE_F64) {
2490 Value *pred = bld.getSSA(1, FILE_PREDICATE);
2491 Value *zero = bld.loadImm(NULL, 0.0);
2492 Value *dst = bld.getSSA(8);
2493 bld.mkOp1(OP_RSQ, i->dType, dst, i->getSrc(0));
2494 bld.mkCmp(OP_SET, CC_LE, i->dType, pred, i->dType, i->getSrc(0), zero);
2495 bld.mkOp3(OP_SELP, TYPE_U64, dst, zero, dst, pred);
2496 i->op = OP_MUL;
2497 i->setSrc(1, dst);
2498 // TODO: Handle this properly with a library function
2499 } else {
2500 bld.setPosition(i, true);
2501 i->op = OP_RSQ;
2502 bld.mkOp1(OP_RCP, i->dType, i->getDef(0), i->getDef(0));
2503 }
2504
2505 return true;
2506 }
2507
2508 bool
2509 NVC0LoweringPass::handlePOW(Instruction *i)
2510 {
2511 LValue *val = bld.getScratch();
2512
2513 bld.mkOp1(OP_LG2, TYPE_F32, val, i->getSrc(0));
2514 bld.mkOp2(OP_MUL, TYPE_F32, val, i->getSrc(1), val)->dnz = 1;
2515 bld.mkOp1(OP_PREEX2, TYPE_F32, val, val);
2516
2517 i->op = OP_EX2;
2518 i->setSrc(0, val);
2519 i->setSrc(1, NULL);
2520
2521 return true;
2522 }
2523
2524 bool
2525 NVC0LoweringPass::handleEXPORT(Instruction *i)
2526 {
2527 if (prog->getType() == Program::TYPE_FRAGMENT) {
2528 int id = i->getSrc(0)->reg.data.offset / 4;
2529
2530 if (i->src(0).isIndirect(0)) // TODO, ugly
2531 return false;
2532 i->op = OP_MOV;
2533 i->subOp = NV50_IR_SUBOP_MOV_FINAL;
2534 i->src(0).set(i->src(1));
2535 i->setSrc(1, NULL);
2536 i->setDef(0, new_LValue(func, FILE_GPR));
2537 i->getDef(0)->reg.data.id = id;
2538
2539 prog->maxGPR = MAX2(prog->maxGPR, id);
2540 } else
2541 if (prog->getType() == Program::TYPE_GEOMETRY) {
2542 i->setIndirect(0, 1, gpEmitAddress);
2543 }
2544 return true;
2545 }
2546
2547 bool
2548 NVC0LoweringPass::handleOUT(Instruction *i)
2549 {
2550 Instruction *prev = i->prev;
2551 ImmediateValue stream, prevStream;
2552
2553 // Only merge if the stream ids match. Also, note that the previous
2554 // instruction would have already been lowered, so we take arg1 from it.
2555 if (i->op == OP_RESTART && prev && prev->op == OP_EMIT &&
2556 i->src(0).getImmediate(stream) &&
2557 prev->src(1).getImmediate(prevStream) &&
2558 stream.reg.data.u32 == prevStream.reg.data.u32) {
2559 i->prev->subOp = NV50_IR_SUBOP_EMIT_RESTART;
2560 delete_Instruction(prog, i);
2561 } else {
2562 assert(gpEmitAddress);
2563 i->setDef(0, gpEmitAddress);
2564 i->setSrc(1, i->getSrc(0));
2565 i->setSrc(0, gpEmitAddress);
2566 }
2567 return true;
2568 }
2569
2570 // Generate a binary predicate if an instruction is predicated by
2571 // e.g. an f32 value.
2572 void
2573 NVC0LoweringPass::checkPredicate(Instruction *insn)
2574 {
2575 Value *pred = insn->getPredicate();
2576 Value *pdst;
2577
2578 if (!pred || pred->reg.file == FILE_PREDICATE)
2579 return;
2580 pdst = new_LValue(func, FILE_PREDICATE);
2581
2582 // CAUTION: don't use pdst->getInsn, the definition might not be unique,
2583 // delay turning PSET(FSET(x,y),0) into PSET(x,y) to a later pass
2584
2585 bld.mkCmp(OP_SET, CC_NEU, insn->dType, pdst, insn->dType, bld.mkImm(0), pred);
2586
2587 insn->setPredicate(insn->cc, pdst);
2588 }
2589
2590 //
2591 // - add quadop dance for texturing
2592 // - put FP outputs in GPRs
2593 // - convert instruction sequences
2594 //
2595 bool
2596 NVC0LoweringPass::visit(Instruction *i)
2597 {
2598 bool ret = true;
2599 bld.setPosition(i, false);
2600
2601 if (i->cc != CC_ALWAYS)
2602 checkPredicate(i);
2603
2604 switch (i->op) {
2605 case OP_TEX:
2606 case OP_TXB:
2607 case OP_TXL:
2608 case OP_TXF:
2609 case OP_TXG:
2610 return handleTEX(i->asTex());
2611 case OP_TXD:
2612 return handleTXD(i->asTex());
2613 case OP_TXLQ:
2614 return handleTXLQ(i->asTex());
2615 case OP_TXQ:
2616 return handleTXQ(i->asTex());
2617 case OP_EX2:
2618 bld.mkOp1(OP_PREEX2, TYPE_F32, i->getDef(0), i->getSrc(0));
2619 i->setSrc(0, i->getDef(0));
2620 break;
2621 case OP_POW:
2622 return handlePOW(i);
2623 case OP_DIV:
2624 return handleDIV(i);
2625 case OP_MOD:
2626 return handleMOD(i);
2627 case OP_SQRT:
2628 return handleSQRT(i);
2629 case OP_EXPORT:
2630 ret = handleEXPORT(i);
2631 break;
2632 case OP_EMIT:
2633 case OP_RESTART:
2634 return handleOUT(i);
2635 case OP_RDSV:
2636 return handleRDSV(i);
2637 case OP_WRSV:
2638 return handleWRSV(i);
2639 case OP_STORE:
2640 case OP_LOAD:
2641 handleLDST(i);
2642 break;
2643 case OP_ATOM:
2644 {
2645 const bool cctl = i->src(0).getFile() == FILE_MEMORY_BUFFER;
2646 handleATOM(i);
2647 handleCasExch(i, cctl);
2648 }
2649 break;
2650 case OP_SULDB:
2651 case OP_SULDP:
2652 case OP_SUSTB:
2653 case OP_SUSTP:
2654 case OP_SUREDB:
2655 case OP_SUREDP:
2656 if (targ->getChipset() >= NVISA_GK104_CHIPSET)
2657 handleSurfaceOpNVE4(i->asTex());
2658 else
2659 handleSurfaceOpNVC0(i->asTex());
2660 break;
2661 case OP_SUQ:
2662 handleSUQ(i->asTex());
2663 break;
2664 case OP_BUFQ:
2665 handleBUFQ(i);
2666 break;
2667 default:
2668 break;
2669 }
2670
2671 /* Kepler+ has a special opcode to compute a new base address to be used
2672 * for indirect loads.
2673 */
2674 if (targ->getChipset() >= NVISA_GK104_CHIPSET && !i->perPatch &&
2675 (i->op == OP_VFETCH || i->op == OP_EXPORT) && i->src(0).isIndirect(0)) {
2676 Instruction *afetch = bld.mkOp1(OP_AFETCH, TYPE_U32, bld.getSSA(),
2677 cloneShallow(func, i->getSrc(0)));
2678 afetch->setIndirect(0, 0, i->getIndirect(0, 0));
2679 i->src(0).get()->reg.data.offset = 0;
2680 i->setIndirect(0, 0, afetch->getDef(0));
2681 }
2682
2683 return ret;
2684 }
2685
2686 bool
2687 TargetNVC0::runLegalizePass(Program *prog, CGStage stage) const
2688 {
2689 if (stage == CG_STAGE_PRE_SSA) {
2690 NVC0LoweringPass pass(prog);
2691 return pass.run(prog, false, true);
2692 } else
2693 if (stage == CG_STAGE_POST_RA) {
2694 NVC0LegalizePostRA pass(prog);
2695 return pass.run(prog, false, true);
2696 } else
2697 if (stage == CG_STAGE_SSA) {
2698 NVC0LegalizeSSA pass;
2699 return pass.run(prog, false, true);
2700 }
2701 return false;
2702 }
2703
2704 } // namespace nv50_ir