nvc0/ir: add base tex offset for fermi indirect tex case
[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 // TODO
74 }
75
76 bool
77 NVC0LegalizeSSA::visit(Function *fn)
78 {
79 bld.setProgram(fn->getProgram());
80 return true;
81 }
82
83 bool
84 NVC0LegalizeSSA::visit(BasicBlock *bb)
85 {
86 Instruction *next;
87 for (Instruction *i = bb->getEntry(); i; i = next) {
88 next = i->next;
89 if (i->dType == TYPE_F32)
90 continue;
91 switch (i->op) {
92 case OP_DIV:
93 case OP_MOD:
94 handleDIV(i);
95 break;
96 case OP_RCP:
97 case OP_RSQ:
98 if (i->dType == TYPE_F64)
99 handleRCPRSQ(i);
100 break;
101 default:
102 break;
103 }
104 }
105 return true;
106 }
107
108 NVC0LegalizePostRA::NVC0LegalizePostRA(const Program *prog)
109 : rZero(NULL),
110 carry(NULL),
111 needTexBar(prog->getTarget()->getChipset() >= 0xe0)
112 {
113 }
114
115 bool
116 NVC0LegalizePostRA::insnDominatedBy(const Instruction *later,
117 const Instruction *early) const
118 {
119 if (early->bb == later->bb)
120 return early->serial < later->serial;
121 return later->bb->dominatedBy(early->bb);
122 }
123
124 void
125 NVC0LegalizePostRA::addTexUse(std::list<TexUse> &uses,
126 Instruction *usei, const Instruction *insn)
127 {
128 bool add = true;
129 for (std::list<TexUse>::iterator it = uses.begin();
130 it != uses.end();) {
131 if (insnDominatedBy(usei, it->insn)) {
132 add = false;
133 break;
134 }
135 if (insnDominatedBy(it->insn, usei))
136 it = uses.erase(it);
137 else
138 ++it;
139 }
140 if (add)
141 uses.push_back(TexUse(usei, insn));
142 }
143
144 void
145 NVC0LegalizePostRA::findOverwritingDefs(const Instruction *texi,
146 Instruction *insn,
147 const BasicBlock *term,
148 std::list<TexUse> &uses)
149 {
150 while (insn->op == OP_MOV && insn->getDef(0)->equals(insn->getSrc(0)))
151 insn = insn->getSrc(0)->getUniqueInsn();
152
153 if (!insn || !insn->bb->reachableBy(texi->bb, term))
154 return;
155
156 switch (insn->op) {
157 /* Values not connected to the tex's definition through any of these should
158 * not be conflicting.
159 */
160 case OP_SPLIT:
161 case OP_MERGE:
162 case OP_PHI:
163 case OP_UNION:
164 /* recurse again */
165 for (int s = 0; insn->srcExists(s); ++s)
166 findOverwritingDefs(texi, insn->getSrc(s)->getUniqueInsn(), term,
167 uses);
168 break;
169 default:
170 // if (!isTextureOp(insn->op)) // TODO: are TEXes always ordered ?
171 addTexUse(uses, insn, texi);
172 break;
173 }
174 }
175
176 void
177 NVC0LegalizePostRA::findFirstUses(const Instruction *texi,
178 const Instruction *insn,
179 std::list<TexUse> &uses)
180 {
181 for (int d = 0; insn->defExists(d); ++d) {
182 Value *v = insn->getDef(d);
183 for (Value::UseIterator u = v->uses.begin(); u != v->uses.end(); ++u) {
184 Instruction *usei = (*u)->getInsn();
185
186 if (usei->op == OP_PHI || usei->op == OP_UNION) {
187 // need a barrier before WAW cases
188 for (int s = 0; usei->srcExists(s); ++s) {
189 Instruction *defi = usei->getSrc(s)->getUniqueInsn();
190 if (defi && &usei->src(s) != *u)
191 findOverwritingDefs(texi, defi, usei->bb, uses);
192 }
193 }
194
195 if (usei->op == OP_SPLIT ||
196 usei->op == OP_MERGE ||
197 usei->op == OP_PHI ||
198 usei->op == OP_UNION) {
199 // these uses don't manifest in the machine code
200 findFirstUses(texi, usei, uses);
201 } else
202 if (usei->op == OP_MOV && usei->getDef(0)->equals(usei->getSrc(0)) &&
203 usei->subOp != NV50_IR_SUBOP_MOV_FINAL) {
204 findFirstUses(texi, usei, uses);
205 } else {
206 addTexUse(uses, usei, insn);
207 }
208 }
209 }
210 }
211
212 // Texture barriers:
213 // This pass is a bit long and ugly and can probably be optimized.
214 //
215 // 1. obtain a list of TEXes and their outputs' first use(s)
216 // 2. calculate the barrier level of each first use (minimal number of TEXes,
217 // over all paths, between the TEX and the use in question)
218 // 3. for each barrier, if all paths from the source TEX to that barrier
219 // contain a barrier of lesser level, it can be culled
220 bool
221 NVC0LegalizePostRA::insertTextureBarriers(Function *fn)
222 {
223 std::list<TexUse> *uses;
224 std::vector<Instruction *> texes;
225 std::vector<int> bbFirstTex;
226 std::vector<int> bbFirstUse;
227 std::vector<int> texCounts;
228 std::vector<TexUse> useVec;
229 ArrayList insns;
230
231 fn->orderInstructions(insns);
232
233 texCounts.resize(fn->allBBlocks.getSize(), 0);
234 bbFirstTex.resize(fn->allBBlocks.getSize(), insns.getSize());
235 bbFirstUse.resize(fn->allBBlocks.getSize(), insns.getSize());
236
237 // tag BB CFG nodes by their id for later
238 for (ArrayList::Iterator i = fn->allBBlocks.iterator(); !i.end(); i.next()) {
239 BasicBlock *bb = reinterpret_cast<BasicBlock *>(i.get());
240 if (bb)
241 bb->cfg.tag = bb->getId();
242 }
243
244 // gather the first uses for each TEX
245 for (int i = 0; i < insns.getSize(); ++i) {
246 Instruction *tex = reinterpret_cast<Instruction *>(insns.get(i));
247 if (isTextureOp(tex->op)) {
248 texes.push_back(tex);
249 if (!texCounts.at(tex->bb->getId()))
250 bbFirstTex[tex->bb->getId()] = texes.size() - 1;
251 texCounts[tex->bb->getId()]++;
252 }
253 }
254 insns.clear();
255 if (texes.empty())
256 return false;
257 uses = new std::list<TexUse>[texes.size()];
258 if (!uses)
259 return false;
260 for (size_t i = 0; i < texes.size(); ++i)
261 findFirstUses(texes[i], texes[i], uses[i]);
262
263 // determine the barrier level at each use
264 for (size_t i = 0; i < texes.size(); ++i) {
265 for (std::list<TexUse>::iterator u = uses[i].begin(); u != uses[i].end();
266 ++u) {
267 BasicBlock *tb = texes[i]->bb;
268 BasicBlock *ub = u->insn->bb;
269 if (tb == ub) {
270 u->level = 0;
271 for (size_t j = i + 1; j < texes.size() &&
272 texes[j]->bb == tb && texes[j]->serial < u->insn->serial;
273 ++j)
274 u->level++;
275 } else {
276 u->level = fn->cfg.findLightestPathWeight(&tb->cfg,
277 &ub->cfg, texCounts);
278 if (u->level < 0) {
279 WARN("Failed to find path TEX -> TEXBAR\n");
280 u->level = 0;
281 continue;
282 }
283 // this counted all TEXes in the origin block, correct that
284 u->level -= i - bbFirstTex.at(tb->getId()) + 1 /* this TEX */;
285 // and did not count the TEXes in the destination block, add those
286 for (size_t j = bbFirstTex.at(ub->getId()); j < texes.size() &&
287 texes[j]->bb == ub && texes[j]->serial < u->insn->serial;
288 ++j)
289 u->level++;
290 }
291 assert(u->level >= 0);
292 useVec.push_back(*u);
293 }
294 }
295 delete[] uses;
296 uses = NULL;
297
298 // insert the barriers
299 for (size_t i = 0; i < useVec.size(); ++i) {
300 Instruction *prev = useVec[i].insn->prev;
301 if (useVec[i].level < 0)
302 continue;
303 if (prev && prev->op == OP_TEXBAR) {
304 if (prev->subOp > useVec[i].level)
305 prev->subOp = useVec[i].level;
306 prev->setSrc(prev->srcCount(), useVec[i].tex->getDef(0));
307 } else {
308 Instruction *bar = new_Instruction(func, OP_TEXBAR, TYPE_NONE);
309 bar->fixed = 1;
310 bar->subOp = useVec[i].level;
311 // make use explicit to ease latency calculation
312 bar->setSrc(bar->srcCount(), useVec[i].tex->getDef(0));
313 useVec[i].insn->bb->insertBefore(useVec[i].insn, bar);
314 }
315 }
316
317 if (fn->getProgram()->optLevel < 3) {
318 if (uses)
319 delete[] uses;
320 return true;
321 }
322
323 std::vector<Limits> limitT, limitB, limitS; // entry, exit, single
324
325 limitT.resize(fn->allBBlocks.getSize(), Limits(0, 0));
326 limitB.resize(fn->allBBlocks.getSize(), Limits(0, 0));
327 limitS.resize(fn->allBBlocks.getSize());
328
329 // cull unneeded barriers (should do that earlier, but for simplicity)
330 IteratorRef bi = fn->cfg.iteratorCFG();
331 // first calculate min/max outstanding TEXes for each BB
332 for (bi->reset(); !bi->end(); bi->next()) {
333 Graph::Node *n = reinterpret_cast<Graph::Node *>(bi->get());
334 BasicBlock *bb = BasicBlock::get(n);
335 int min = 0;
336 int max = std::numeric_limits<int>::max();
337 for (Instruction *i = bb->getFirst(); i; i = i->next) {
338 if (isTextureOp(i->op)) {
339 min++;
340 if (max < std::numeric_limits<int>::max())
341 max++;
342 } else
343 if (i->op == OP_TEXBAR) {
344 min = MIN2(min, i->subOp);
345 max = MIN2(max, i->subOp);
346 }
347 }
348 // limits when looking at an isolated block
349 limitS[bb->getId()].min = min;
350 limitS[bb->getId()].max = max;
351 }
352 // propagate the min/max values
353 for (unsigned int l = 0; l <= fn->loopNestingBound; ++l) {
354 for (bi->reset(); !bi->end(); bi->next()) {
355 Graph::Node *n = reinterpret_cast<Graph::Node *>(bi->get());
356 BasicBlock *bb = BasicBlock::get(n);
357 const int bbId = bb->getId();
358 for (Graph::EdgeIterator ei = n->incident(); !ei.end(); ei.next()) {
359 BasicBlock *in = BasicBlock::get(ei.getNode());
360 const int inId = in->getId();
361 limitT[bbId].min = MAX2(limitT[bbId].min, limitB[inId].min);
362 limitT[bbId].max = MAX2(limitT[bbId].max, limitB[inId].max);
363 }
364 // I just hope this is correct ...
365 if (limitS[bbId].max == std::numeric_limits<int>::max()) {
366 // no barrier
367 limitB[bbId].min = limitT[bbId].min + limitS[bbId].min;
368 limitB[bbId].max = limitT[bbId].max + limitS[bbId].min;
369 } else {
370 // block contained a barrier
371 limitB[bbId].min = MIN2(limitS[bbId].max,
372 limitT[bbId].min + limitS[bbId].min);
373 limitB[bbId].max = MIN2(limitS[bbId].max,
374 limitT[bbId].max + limitS[bbId].min);
375 }
376 }
377 }
378 // finally delete unnecessary barriers
379 for (bi->reset(); !bi->end(); bi->next()) {
380 Graph::Node *n = reinterpret_cast<Graph::Node *>(bi->get());
381 BasicBlock *bb = BasicBlock::get(n);
382 Instruction *prev = NULL;
383 Instruction *next;
384 int max = limitT[bb->getId()].max;
385 for (Instruction *i = bb->getFirst(); i; i = next) {
386 next = i->next;
387 if (i->op == OP_TEXBAR) {
388 if (i->subOp >= max) {
389 delete_Instruction(prog, i);
390 i = NULL;
391 } else {
392 max = i->subOp;
393 if (prev && prev->op == OP_TEXBAR && prev->subOp >= max) {
394 delete_Instruction(prog, prev);
395 prev = NULL;
396 }
397 }
398 } else
399 if (isTextureOp(i->op)) {
400 max++;
401 }
402 if (i && !i->isNop())
403 prev = i;
404 }
405 }
406 if (uses)
407 delete[] uses;
408 return true;
409 }
410
411 bool
412 NVC0LegalizePostRA::visit(Function *fn)
413 {
414 if (needTexBar)
415 insertTextureBarriers(fn);
416
417 rZero = new_LValue(fn, FILE_GPR);
418 carry = new_LValue(fn, FILE_FLAGS);
419
420 rZero->reg.data.id = prog->getTarget()->getFileSize(FILE_GPR);
421 carry->reg.data.id = 0;
422
423 return true;
424 }
425
426 void
427 NVC0LegalizePostRA::replaceZero(Instruction *i)
428 {
429 for (int s = 0; i->srcExists(s); ++s) {
430 if (s == 2 && i->op == OP_SUCLAMP)
431 continue;
432 ImmediateValue *imm = i->getSrc(s)->asImm();
433 if (imm && imm->reg.data.u64 == 0)
434 i->setSrc(s, rZero);
435 }
436 }
437
438 // replace CONT with BRA for single unconditional continue
439 bool
440 NVC0LegalizePostRA::tryReplaceContWithBra(BasicBlock *bb)
441 {
442 if (bb->cfg.incidentCount() != 2 || bb->getEntry()->op != OP_PRECONT)
443 return false;
444 Graph::EdgeIterator ei = bb->cfg.incident();
445 if (ei.getType() != Graph::Edge::BACK)
446 ei.next();
447 if (ei.getType() != Graph::Edge::BACK)
448 return false;
449 BasicBlock *contBB = BasicBlock::get(ei.getNode());
450
451 if (!contBB->getExit() || contBB->getExit()->op != OP_CONT ||
452 contBB->getExit()->getPredicate())
453 return false;
454 contBB->getExit()->op = OP_BRA;
455 bb->remove(bb->getEntry()); // delete PRECONT
456
457 ei.next();
458 assert(ei.end() || ei.getType() != Graph::Edge::BACK);
459 return true;
460 }
461
462 // replace branches to join blocks with join ops
463 void
464 NVC0LegalizePostRA::propagateJoin(BasicBlock *bb)
465 {
466 if (bb->getEntry()->op != OP_JOIN || bb->getEntry()->asFlow()->limit)
467 return;
468 for (Graph::EdgeIterator ei = bb->cfg.incident(); !ei.end(); ei.next()) {
469 BasicBlock *in = BasicBlock::get(ei.getNode());
470 Instruction *exit = in->getExit();
471 if (!exit) {
472 in->insertTail(new FlowInstruction(func, OP_JOIN, bb));
473 // there should always be a terminator instruction
474 WARN("inserted missing terminator in BB:%i\n", in->getId());
475 } else
476 if (exit->op == OP_BRA) {
477 exit->op = OP_JOIN;
478 exit->asFlow()->limit = 1; // must-not-propagate marker
479 }
480 }
481 bb->remove(bb->getEntry());
482 }
483
484 bool
485 NVC0LegalizePostRA::visit(BasicBlock *bb)
486 {
487 Instruction *i, *next;
488
489 // remove pseudo operations and non-fixed no-ops, split 64 bit operations
490 for (i = bb->getFirst(); i; i = next) {
491 next = i->next;
492 if (i->op == OP_EMIT || i->op == OP_RESTART) {
493 if (!i->getDef(0)->refCount())
494 i->setDef(0, NULL);
495 if (i->src(0).getFile() == FILE_IMMEDIATE)
496 i->setSrc(0, rZero); // initial value must be 0
497 replaceZero(i);
498 } else
499 if (i->isNop()) {
500 bb->remove(i);
501 } else {
502 // TODO: Move this to before register allocation for operations that
503 // need the $c register !
504 if (typeSizeof(i->dType) == 8) {
505 Instruction *hi;
506 hi = BuildUtil::split64BitOpPostRA(func, i, rZero, carry);
507 if (hi)
508 next = hi;
509 }
510
511 if (i->op != OP_MOV && i->op != OP_PFETCH)
512 replaceZero(i);
513 }
514 }
515 if (!bb->getEntry())
516 return true;
517
518 if (!tryReplaceContWithBra(bb))
519 propagateJoin(bb);
520
521 return true;
522 }
523
524 NVC0LoweringPass::NVC0LoweringPass(Program *prog) : targ(prog->getTarget())
525 {
526 bld.setProgram(prog);
527 gMemBase = NULL;
528 }
529
530 bool
531 NVC0LoweringPass::visit(Function *fn)
532 {
533 if (prog->getType() == Program::TYPE_GEOMETRY) {
534 assert(!strncmp(fn->getName(), "MAIN", 4));
535 // TODO: when we generate actual functions pass this value along somehow
536 bld.setPosition(BasicBlock::get(fn->cfg.getRoot()), false);
537 gpEmitAddress = bld.loadImm(NULL, 0)->asLValue();
538 if (fn->cfgExit) {
539 bld.setPosition(BasicBlock::get(fn->cfgExit)->getExit(), false);
540 bld.mkMovToReg(0, gpEmitAddress);
541 }
542 }
543 return true;
544 }
545
546 bool
547 NVC0LoweringPass::visit(BasicBlock *bb)
548 {
549 return true;
550 }
551
552 inline Value *
553 NVC0LoweringPass::loadTexHandle(Value *ptr, unsigned int slot)
554 {
555 uint8_t b = prog->driver->io.resInfoCBSlot;
556 uint32_t off = prog->driver->io.texBindBase + slot * 4;
557 return bld.
558 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U32, off), ptr);
559 }
560
561 // move array source to first slot, convert to u16, add indirections
562 bool
563 NVC0LoweringPass::handleTEX(TexInstruction *i)
564 {
565 const int dim = i->tex.target.getDim() + i->tex.target.isCube();
566 const int arg = i->tex.target.getArgCount();
567 const int lyr = arg - (i->tex.target.isMS() ? 2 : 1);
568 const int chipset = prog->getTarget()->getChipset();
569
570 if (chipset >= NVISA_GK104_CHIPSET) {
571 if (i->tex.rIndirectSrc >= 0 || i->tex.sIndirectSrc >= 0) {
572 WARN("indirect TEX not implemented\n");
573 }
574 if (i->tex.r == i->tex.s) {
575 i->tex.r += prog->driver->io.texBindBase / 4;
576 i->tex.s = 0; // only a single cX[] value possible here
577 } else {
578 Value *hnd = bld.getScratch();
579 Value *rHnd = loadTexHandle(NULL, i->tex.r);
580 Value *sHnd = loadTexHandle(NULL, i->tex.s);
581
582 bld.mkOp3(OP_INSBF, TYPE_U32, hnd, rHnd, bld.mkImm(0x1400), sHnd);
583
584 i->tex.r = 0; // not used for indirect tex
585 i->tex.s = 0;
586 i->setIndirectR(hnd);
587 }
588 if (i->tex.target.isArray()) {
589 LValue *layer = new_LValue(func, FILE_GPR);
590 Value *src = i->getSrc(lyr);
591 const int sat = (i->op == OP_TXF) ? 1 : 0;
592 DataType sTy = (i->op == OP_TXF) ? TYPE_U32 : TYPE_F32;
593 bld.mkCvt(OP_CVT, TYPE_U16, layer, sTy, src)->saturate = sat;
594 for (int s = dim; s >= 1; --s)
595 i->setSrc(s, i->getSrc(s - 1));
596 i->setSrc(0, layer);
597 }
598 } else
599 // (nvc0) generate and move the tsc/tic/array source to the front
600 if (i->tex.target.isArray() || i->tex.rIndirectSrc >= 0 || i->tex.sIndirectSrc >= 0) {
601 LValue *src = new_LValue(func, FILE_GPR); // 0xttxsaaaa
602
603 Value *ticRel = i->getIndirectR();
604 Value *tscRel = i->getIndirectS();
605
606 if (ticRel) {
607 i->setSrc(i->tex.rIndirectSrc, NULL);
608 if (i->tex.r)
609 ticRel = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getScratch(),
610 ticRel, bld.mkImm(i->tex.r));
611 }
612 if (tscRel) {
613 i->setSrc(i->tex.sIndirectSrc, NULL);
614 if (i->tex.s)
615 tscRel = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getScratch(),
616 tscRel, bld.mkImm(i->tex.s));
617 }
618
619 Value *arrayIndex = i->tex.target.isArray() ? i->getSrc(lyr) : NULL;
620 for (int s = dim; s >= 1; --s)
621 i->setSrc(s, i->getSrc(s - 1));
622 i->setSrc(0, arrayIndex);
623
624 if (arrayIndex) {
625 int sat = (i->op == OP_TXF) ? 1 : 0;
626 DataType sTy = (i->op == OP_TXF) ? TYPE_U32 : TYPE_F32;
627 bld.mkCvt(OP_CVT, TYPE_U16, src, sTy, arrayIndex)->saturate = sat;
628 } else {
629 bld.loadImm(src, 0);
630 }
631
632 if (ticRel)
633 bld.mkOp3(OP_INSBF, TYPE_U32, src, ticRel, bld.mkImm(0x0917), src);
634 if (tscRel)
635 bld.mkOp3(OP_INSBF, TYPE_U32, src, tscRel, bld.mkImm(0x0710), src);
636
637 i->setSrc(0, src);
638 }
639
640 // For nvc0, the sample id has to be in the second operand, as the offset
641 // does. Right now we don't know how to pass both in, and this case can't
642 // happen with OpenGL. On nve0, the sample id is part of the texture
643 // coordinate argument.
644 assert(chipset >= NVISA_GK104_CHIPSET ||
645 !i->tex.useOffsets || !i->tex.target.isMS());
646
647 // offset is between lod and dc
648 if (i->tex.useOffsets) {
649 int n, c;
650 int s = i->srcCount(0xff, true);
651 if (i->op != OP_TXD || chipset < NVISA_GK104_CHIPSET) {
652 if (i->tex.target.isShadow())
653 s--;
654 if (i->srcExists(s)) // move potential predicate out of the way
655 i->moveSources(s, 1);
656 if (i->tex.useOffsets == 4 && i->srcExists(s + 1))
657 i->moveSources(s + 1, 1);
658 }
659 if (i->op == OP_TXG) {
660 // Either there is 1 offset, which goes into the 2 low bytes of the
661 // first source, or there are 4 offsets, which go into 2 sources (8
662 // values, 1 byte each).
663 Value *offs[2] = {NULL, NULL};
664 for (n = 0; n < i->tex.useOffsets; n++) {
665 for (c = 0; c < 2; ++c) {
666 if ((n % 2) == 0 && c == 0)
667 offs[n / 2] = i->offset[n][c].get();
668 else
669 bld.mkOp3(OP_INSBF, TYPE_U32,
670 offs[n / 2],
671 i->offset[n][c].get(),
672 bld.mkImm(0x800 | ((n * 16 + c * 8) % 32)),
673 offs[n / 2]);
674 }
675 }
676 i->setSrc(s, offs[0]);
677 if (offs[1])
678 i->setSrc(s + 1, offs[1]);
679 } else {
680 unsigned imm = 0;
681 assert(i->tex.useOffsets == 1);
682 for (c = 0; c < 3; ++c) {
683 ImmediateValue val;
684 assert(i->offset[0][c].getImmediate(val));
685 imm |= (val.reg.data.u32 & 0xf) << (c * 4);
686 }
687 if (i->op == OP_TXD && chipset >= NVISA_GK104_CHIPSET) {
688 // The offset goes into the upper 16 bits of the array index. So
689 // create it if it's not already there, and INSBF it if it already
690 // is.
691 if (i->tex.target.isArray()) {
692 bld.mkOp3(OP_INSBF, TYPE_U32, i->getSrc(0),
693 bld.loadImm(NULL, imm), bld.mkImm(0xc10),
694 i->getSrc(0));
695 } else {
696 for (int s = dim; s >= 1; --s)
697 i->setSrc(s, i->getSrc(s - 1));
698 i->setSrc(0, bld.loadImm(NULL, imm << 16));
699 }
700 } else {
701 i->setSrc(s, bld.loadImm(NULL, imm));
702 }
703 }
704 }
705
706 if (chipset >= NVISA_GK104_CHIPSET) {
707 //
708 // If TEX requires more than 4 sources, the 2nd register tuple must be
709 // aligned to 4, even if it consists of just a single 4-byte register.
710 //
711 // XXX HACK: We insert 0 sources to avoid the 5 or 6 regs case.
712 //
713 int s = i->srcCount(0xff, true);
714 if (s > 4 && s < 7) {
715 if (i->srcExists(s)) // move potential predicate out of the way
716 i->moveSources(s, 7 - s);
717 while (s < 7)
718 i->setSrc(s++, bld.loadImm(NULL, 0));
719 }
720 }
721
722 return true;
723 }
724
725 bool
726 NVC0LoweringPass::handleManualTXD(TexInstruction *i)
727 {
728 static const uint8_t qOps[4][2] =
729 {
730 { QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(MOV2, MOV2, ADD, ADD) }, // l0
731 { QUADOP(SUBR, MOV2, SUBR, MOV2), QUADOP(MOV2, MOV2, ADD, ADD) }, // l1
732 { QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(SUBR, SUBR, MOV2, MOV2) }, // l2
733 { QUADOP(SUBR, MOV2, SUBR, MOV2), QUADOP(SUBR, SUBR, MOV2, MOV2) }, // l3
734 };
735 Value *def[4][4];
736 Value *crd[3];
737 Instruction *tex;
738 Value *zero = bld.loadImm(bld.getSSA(), 0);
739 int l, c;
740 const int dim = i->tex.target.getDim();
741 const int array = i->tex.target.isArray();
742
743 i->op = OP_TEX; // no need to clone dPdx/dPdy later
744
745 for (c = 0; c < dim; ++c)
746 crd[c] = bld.getScratch();
747
748 bld.mkOp(OP_QUADON, TYPE_NONE, NULL);
749 for (l = 0; l < 4; ++l) {
750 // mov coordinates from lane l to all lanes
751 for (c = 0; c < dim; ++c)
752 bld.mkQuadop(0x00, crd[c], l, i->getSrc(c + array), zero);
753 // add dPdx from lane l to lanes dx
754 for (c = 0; c < dim; ++c)
755 bld.mkQuadop(qOps[l][0], crd[c], l, i->dPdx[c].get(), crd[c]);
756 // add dPdy from lane l to lanes dy
757 for (c = 0; c < dim; ++c)
758 bld.mkQuadop(qOps[l][1], crd[c], l, i->dPdy[c].get(), crd[c]);
759 // texture
760 bld.insert(tex = cloneForward(func, i));
761 for (c = 0; c < dim; ++c)
762 tex->setSrc(c + array, crd[c]);
763 // save results
764 for (c = 0; i->defExists(c); ++c) {
765 Instruction *mov;
766 def[c][l] = bld.getSSA();
767 mov = bld.mkMov(def[c][l], tex->getDef(c));
768 mov->fixed = 1;
769 mov->lanes = 1 << l;
770 }
771 }
772 bld.mkOp(OP_QUADPOP, TYPE_NONE, NULL);
773
774 for (c = 0; i->defExists(c); ++c) {
775 Instruction *u = bld.mkOp(OP_UNION, TYPE_U32, i->getDef(c));
776 for (l = 0; l < 4; ++l)
777 u->setSrc(l, def[c][l]);
778 }
779
780 i->bb->remove(i);
781 return true;
782 }
783
784 bool
785 NVC0LoweringPass::handleTXD(TexInstruction *txd)
786 {
787 int dim = txd->tex.target.getDim();
788 unsigned arg = txd->tex.target.getArgCount();
789 unsigned expected_args = arg;
790 const int chipset = prog->getTarget()->getChipset();
791
792 if (chipset >= NVISA_GK104_CHIPSET) {
793 if (!txd->tex.target.isArray() && txd->tex.useOffsets)
794 expected_args++;
795 } else {
796 if (txd->tex.useOffsets)
797 expected_args++;
798 if (!txd->tex.target.isArray() && (
799 txd->tex.rIndirectSrc >= 0 || txd->tex.sIndirectSrc >= 0))
800 expected_args++;
801 }
802
803 if (expected_args > 4 ||
804 dim > 2 ||
805 txd->tex.target.isShadow() ||
806 txd->tex.target.isCube())
807 txd->op = OP_TEX;
808
809 handleTEX(txd);
810 while (txd->srcExists(arg))
811 ++arg;
812
813 txd->tex.derivAll = true;
814 if (txd->op == OP_TEX)
815 return handleManualTXD(txd);
816
817 assert(arg == expected_args);
818 for (int c = 0; c < dim; ++c) {
819 txd->setSrc(arg + c * 2 + 0, txd->dPdx[c]);
820 txd->setSrc(arg + c * 2 + 1, txd->dPdy[c]);
821 txd->dPdx[c].set(NULL);
822 txd->dPdy[c].set(NULL);
823 }
824 return true;
825 }
826
827 bool
828 NVC0LoweringPass::handleTXQ(TexInstruction *txq)
829 {
830 // TODO: indirect resource/sampler index
831 return true;
832 }
833
834 bool
835 NVC0LoweringPass::handleTXLQ(TexInstruction *i)
836 {
837 /* The outputs are inverted compared to what the TGSI instruction
838 * expects. Take that into account in the mask.
839 */
840 assert((i->tex.mask & ~3) == 0);
841 if (i->tex.mask == 1)
842 i->tex.mask = 2;
843 else if (i->tex.mask == 2)
844 i->tex.mask = 1;
845 handleTEX(i);
846 bld.setPosition(i, true);
847
848 /* The returned values are not quite what we want:
849 * (a) convert from s16/u16 to f32
850 * (b) multiply by 1/256
851 */
852 for (int def = 0; def < 2; ++def) {
853 if (!i->defExists(def))
854 continue;
855 enum DataType type = TYPE_S16;
856 if (i->tex.mask == 2 || def > 0)
857 type = TYPE_U16;
858 bld.mkCvt(OP_CVT, TYPE_F32, i->getDef(def), type, i->getDef(def));
859 bld.mkOp2(OP_MUL, TYPE_F32, i->getDef(def),
860 i->getDef(def), bld.loadImm(NULL, 1.0f / 256));
861 }
862 if (i->tex.mask == 3) {
863 LValue *t = new_LValue(func, FILE_GPR);
864 bld.mkMov(t, i->getDef(0));
865 bld.mkMov(i->getDef(0), i->getDef(1));
866 bld.mkMov(i->getDef(1), t);
867 }
868 return true;
869 }
870
871
872 bool
873 NVC0LoweringPass::handleATOM(Instruction *atom)
874 {
875 SVSemantic sv;
876
877 switch (atom->src(0).getFile()) {
878 case FILE_MEMORY_LOCAL:
879 sv = SV_LBASE;
880 break;
881 case FILE_MEMORY_SHARED:
882 sv = SV_SBASE;
883 break;
884 default:
885 assert(atom->src(0).getFile() == FILE_MEMORY_GLOBAL);
886 return true;
887 }
888 Value *base =
889 bld.mkOp1v(OP_RDSV, TYPE_U32, bld.getScratch(), bld.mkSysVal(sv, 0));
890 Value *ptr = atom->getIndirect(0, 0);
891
892 atom->setSrc(0, cloneShallow(func, atom->getSrc(0)));
893 atom->getSrc(0)->reg.file = FILE_MEMORY_GLOBAL;
894 if (ptr)
895 base = bld.mkOp2v(OP_ADD, TYPE_U32, base, base, ptr);
896 atom->setIndirect(0, 0, base);
897
898 return true;
899 }
900
901 bool
902 NVC0LoweringPass::handleCasExch(Instruction *cas, bool needCctl)
903 {
904 if (cas->subOp != NV50_IR_SUBOP_ATOM_CAS &&
905 cas->subOp != NV50_IR_SUBOP_ATOM_EXCH)
906 return false;
907 bld.setPosition(cas, true);
908
909 if (needCctl) {
910 Instruction *cctl = bld.mkOp1(OP_CCTL, TYPE_NONE, NULL, cas->getSrc(0));
911 cctl->setIndirect(0, 0, cas->getIndirect(0, 0));
912 cctl->fixed = 1;
913 cctl->subOp = NV50_IR_SUBOP_CCTL_IV;
914 if (cas->isPredicated())
915 cctl->setPredicate(cas->cc, cas->getPredicate());
916 }
917
918 if (cas->defExists(0) && cas->subOp == NV50_IR_SUBOP_ATOM_CAS) {
919 // CAS is crazy. It's 2nd source is a double reg, and the 3rd source
920 // should be set to the high part of the double reg or bad things will
921 // happen elsewhere in the universe.
922 // Also, it sometimes returns the new value instead of the old one
923 // under mysterious circumstances.
924 Value *dreg = bld.getSSA(8);
925 bld.setPosition(cas, false);
926 bld.mkOp2(OP_MERGE, TYPE_U64, dreg, cas->getSrc(1), cas->getSrc(2));
927 cas->setSrc(1, dreg);
928 }
929
930 return true;
931 }
932
933 inline Value *
934 NVC0LoweringPass::loadResInfo32(Value *ptr, uint32_t off)
935 {
936 uint8_t b = prog->driver->io.resInfoCBSlot;
937 off += prog->driver->io.suInfoBase;
938 return bld.
939 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U32, off), ptr);
940 }
941
942 inline Value *
943 NVC0LoweringPass::loadMsInfo32(Value *ptr, uint32_t off)
944 {
945 uint8_t b = prog->driver->io.msInfoCBSlot;
946 off += prog->driver->io.msInfoBase;
947 return bld.
948 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U32, off), ptr);
949 }
950
951 /* On nvc0, surface info is obtained via the surface binding points passed
952 * to the SULD/SUST instructions.
953 * On nve4, surface info is stored in c[] and is used by various special
954 * instructions, e.g. for clamping coordiantes or generating an address.
955 * They couldn't just have added an equivalent to TIC now, couldn't they ?
956 */
957 #define NVE4_SU_INFO_ADDR 0x00
958 #define NVE4_SU_INFO_FMT 0x04
959 #define NVE4_SU_INFO_DIM_X 0x08
960 #define NVE4_SU_INFO_PITCH 0x0c
961 #define NVE4_SU_INFO_DIM_Y 0x10
962 #define NVE4_SU_INFO_ARRAY 0x14
963 #define NVE4_SU_INFO_DIM_Z 0x18
964 #define NVE4_SU_INFO_UNK1C 0x1c
965 #define NVE4_SU_INFO_WIDTH 0x20
966 #define NVE4_SU_INFO_HEIGHT 0x24
967 #define NVE4_SU_INFO_DEPTH 0x28
968 #define NVE4_SU_INFO_TARGET 0x2c
969 #define NVE4_SU_INFO_CALL 0x30
970 #define NVE4_SU_INFO_RAW_X 0x34
971 #define NVE4_SU_INFO_MS_X 0x38
972 #define NVE4_SU_INFO_MS_Y 0x3c
973
974 #define NVE4_SU_INFO__STRIDE 0x40
975
976 #define NVE4_SU_INFO_DIM(i) (0x08 + (i) * 8)
977 #define NVE4_SU_INFO_SIZE(i) (0x20 + (i) * 4)
978 #define NVE4_SU_INFO_MS(i) (0x38 + (i) * 4)
979
980 static inline uint16_t getSuClampSubOp(const TexInstruction *su, int c)
981 {
982 switch (su->tex.target.getEnum()) {
983 case TEX_TARGET_BUFFER: return NV50_IR_SUBOP_SUCLAMP_PL(0, 1);
984 case TEX_TARGET_RECT: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
985 case TEX_TARGET_1D: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
986 case TEX_TARGET_1D_ARRAY: return (c == 1) ?
987 NV50_IR_SUBOP_SUCLAMP_PL(0, 2) :
988 NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
989 case TEX_TARGET_2D: return NV50_IR_SUBOP_SUCLAMP_BL(0, 2);
990 case TEX_TARGET_2D_MS: return NV50_IR_SUBOP_SUCLAMP_BL(0, 2);
991 case TEX_TARGET_2D_ARRAY: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
992 case TEX_TARGET_2D_MS_ARRAY: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
993 case TEX_TARGET_3D: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
994 case TEX_TARGET_CUBE: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
995 case TEX_TARGET_CUBE_ARRAY: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
996 default:
997 assert(0);
998 return 0;
999 }
1000 }
1001
1002 void
1003 NVC0LoweringPass::adjustCoordinatesMS(TexInstruction *tex)
1004 {
1005 const uint16_t base = tex->tex.r * NVE4_SU_INFO__STRIDE;
1006 const int arg = tex->tex.target.getArgCount();
1007
1008 if (tex->tex.target == TEX_TARGET_2D_MS)
1009 tex->tex.target = TEX_TARGET_2D;
1010 else
1011 if (tex->tex.target == TEX_TARGET_2D_MS_ARRAY)
1012 tex->tex.target = TEX_TARGET_2D_ARRAY;
1013 else
1014 return;
1015
1016 Value *x = tex->getSrc(0);
1017 Value *y = tex->getSrc(1);
1018 Value *s = tex->getSrc(arg - 1);
1019
1020 Value *tx = bld.getSSA(), *ty = bld.getSSA(), *ts = bld.getSSA();
1021
1022 Value *ms_x = loadResInfo32(NULL, base + NVE4_SU_INFO_MS(0));
1023 Value *ms_y = loadResInfo32(NULL, base + NVE4_SU_INFO_MS(1));
1024
1025 bld.mkOp2(OP_SHL, TYPE_U32, tx, x, ms_x);
1026 bld.mkOp2(OP_SHL, TYPE_U32, ty, y, ms_y);
1027
1028 s = bld.mkOp2v(OP_AND, TYPE_U32, ts, s, bld.loadImm(NULL, 0x7));
1029 s = bld.mkOp2v(OP_SHL, TYPE_U32, ts, ts, bld.mkImm(3));
1030
1031 Value *dx = loadMsInfo32(ts, 0x0);
1032 Value *dy = loadMsInfo32(ts, 0x4);
1033
1034 bld.mkOp2(OP_ADD, TYPE_U32, tx, tx, dx);
1035 bld.mkOp2(OP_ADD, TYPE_U32, ty, ty, dy);
1036
1037 tex->setSrc(0, tx);
1038 tex->setSrc(1, ty);
1039 tex->moveSources(arg, -1);
1040 }
1041
1042 // Sets 64-bit "generic address", predicate and format sources for SULD/SUST.
1043 // They're computed from the coordinates using the surface info in c[] space.
1044 void
1045 NVC0LoweringPass::processSurfaceCoordsNVE4(TexInstruction *su)
1046 {
1047 Instruction *insn;
1048 const bool atom = su->op == OP_SUREDB || su->op == OP_SUREDP;
1049 const bool raw =
1050 su->op == OP_SULDB || su->op == OP_SUSTB || su->op == OP_SUREDB;
1051 const int idx = su->tex.r;
1052 const int dim = su->tex.target.getDim();
1053 const int arg = dim + (su->tex.target.isArray() ? 1 : 0);
1054 const uint16_t base = idx * NVE4_SU_INFO__STRIDE;
1055 int c;
1056 Value *zero = bld.mkImm(0);
1057 Value *p1 = NULL;
1058 Value *v;
1059 Value *src[3];
1060 Value *bf, *eau, *off;
1061 Value *addr, *pred;
1062
1063 off = bld.getScratch(4);
1064 bf = bld.getScratch(4);
1065 addr = bld.getSSA(8);
1066 pred = bld.getScratch(1, FILE_PREDICATE);
1067
1068 bld.setPosition(su, false);
1069
1070 adjustCoordinatesMS(su);
1071
1072 // calculate clamped coordinates
1073 for (c = 0; c < arg; ++c) {
1074 src[c] = bld.getScratch();
1075 if (c == 0 && raw)
1076 v = loadResInfo32(NULL, base + NVE4_SU_INFO_RAW_X);
1077 else
1078 v = loadResInfo32(NULL, base + NVE4_SU_INFO_DIM(c));
1079 bld.mkOp3(OP_SUCLAMP, TYPE_S32, src[c], su->getSrc(c), v, zero)
1080 ->subOp = getSuClampSubOp(su, c);
1081 }
1082 for (; c < 3; ++c)
1083 src[c] = zero;
1084
1085 // set predicate output
1086 if (su->tex.target == TEX_TARGET_BUFFER) {
1087 src[0]->getInsn()->setFlagsDef(1, pred);
1088 } else
1089 if (su->tex.target.isArray()) {
1090 p1 = bld.getSSA(1, FILE_PREDICATE);
1091 src[dim]->getInsn()->setFlagsDef(1, p1);
1092 }
1093
1094 // calculate pixel offset
1095 if (dim == 1) {
1096 if (su->tex.target != TEX_TARGET_BUFFER)
1097 bld.mkOp2(OP_AND, TYPE_U32, off, src[0], bld.loadImm(NULL, 0xffff));
1098 } else
1099 if (dim == 3) {
1100 v = loadResInfo32(NULL, base + NVE4_SU_INFO_UNK1C);
1101 bld.mkOp3(OP_MADSP, TYPE_U32, off, src[2], v, src[1])
1102 ->subOp = NV50_IR_SUBOP_MADSP(4,2,8); // u16l u16l u16l
1103
1104 v = loadResInfo32(NULL, base + NVE4_SU_INFO_PITCH);
1105 bld.mkOp3(OP_MADSP, TYPE_U32, off, off, v, src[0])
1106 ->subOp = NV50_IR_SUBOP_MADSP(0,2,8); // u32 u16l u16l
1107 } else {
1108 assert(dim == 2);
1109 v = loadResInfo32(NULL, base + NVE4_SU_INFO_PITCH);
1110 bld.mkOp3(OP_MADSP, TYPE_U32, off, src[1], v, src[0])
1111 ->subOp = su->tex.target.isArray() ?
1112 NV50_IR_SUBOP_MADSP_SD : NV50_IR_SUBOP_MADSP(4,2,8); // u16l u16l u16l
1113 }
1114
1115 // calculate effective address part 1
1116 if (su->tex.target == TEX_TARGET_BUFFER) {
1117 if (raw) {
1118 bf = src[0];
1119 } else {
1120 v = loadResInfo32(NULL, base + NVE4_SU_INFO_FMT);
1121 bld.mkOp3(OP_VSHL, TYPE_U32, bf, src[0], v, zero)
1122 ->subOp = NV50_IR_SUBOP_V1(7,6,8|2);
1123 }
1124 } else {
1125 Value *y = src[1];
1126 Value *z = src[2];
1127 uint16_t subOp = 0;
1128
1129 switch (dim) {
1130 case 1:
1131 y = zero;
1132 z = zero;
1133 break;
1134 case 2:
1135 z = off;
1136 if (!su->tex.target.isArray()) {
1137 z = loadResInfo32(NULL, base + NVE4_SU_INFO_UNK1C);
1138 subOp = NV50_IR_SUBOP_SUBFM_3D;
1139 }
1140 break;
1141 default:
1142 subOp = NV50_IR_SUBOP_SUBFM_3D;
1143 assert(dim == 3);
1144 break;
1145 }
1146 insn = bld.mkOp3(OP_SUBFM, TYPE_U32, bf, src[0], y, z);
1147 insn->subOp = subOp;
1148 insn->setFlagsDef(1, pred);
1149 }
1150
1151 // part 2
1152 v = loadResInfo32(NULL, base + NVE4_SU_INFO_ADDR);
1153
1154 if (su->tex.target == TEX_TARGET_BUFFER) {
1155 eau = v;
1156 } else {
1157 eau = bld.mkOp3v(OP_SUEAU, TYPE_U32, bld.getScratch(4), off, bf, v);
1158 }
1159 // add array layer offset
1160 if (su->tex.target.isArray()) {
1161 v = loadResInfo32(NULL, base + NVE4_SU_INFO_ARRAY);
1162 if (dim == 1)
1163 bld.mkOp3(OP_MADSP, TYPE_U32, eau, src[1], v, eau)
1164 ->subOp = NV50_IR_SUBOP_MADSP(4,0,0); // u16 u24 u32
1165 else
1166 bld.mkOp3(OP_MADSP, TYPE_U32, eau, v, src[2], eau)
1167 ->subOp = NV50_IR_SUBOP_MADSP(0,0,0); // u32 u24 u32
1168 // combine predicates
1169 assert(p1);
1170 bld.mkOp2(OP_OR, TYPE_U8, pred, pred, p1);
1171 }
1172
1173 if (atom) {
1174 Value *lo = bf;
1175 if (su->tex.target == TEX_TARGET_BUFFER) {
1176 lo = zero;
1177 bld.mkMov(off, bf);
1178 }
1179 // bf == g[] address & 0xff
1180 // eau == g[] address >> 8
1181 bld.mkOp3(OP_PERMT, TYPE_U32, bf, lo, bld.loadImm(NULL, 0x6540), eau);
1182 bld.mkOp3(OP_PERMT, TYPE_U32, eau, zero, bld.loadImm(NULL, 0x0007), eau);
1183 } else
1184 if (su->op == OP_SULDP && su->tex.target == TEX_TARGET_BUFFER) {
1185 // Convert from u32 to u8 address format, which is what the library code
1186 // doing SULDP currently uses.
1187 // XXX: can SUEAU do this ?
1188 // XXX: does it matter that we don't mask high bytes in bf ?
1189 // Grrr.
1190 bld.mkOp2(OP_SHR, TYPE_U32, off, bf, bld.mkImm(8));
1191 bld.mkOp2(OP_ADD, TYPE_U32, eau, eau, off);
1192 }
1193
1194 bld.mkOp2(OP_MERGE, TYPE_U64, addr, bf, eau);
1195
1196 if (atom && su->tex.target == TEX_TARGET_BUFFER)
1197 bld.mkOp2(OP_ADD, TYPE_U64, addr, addr, off);
1198
1199 // let's just set it 0 for raw access and hope it works
1200 v = raw ?
1201 bld.mkImm(0) : loadResInfo32(NULL, base + NVE4_SU_INFO_FMT);
1202
1203 // get rid of old coordinate sources, make space for fmt info and predicate
1204 su->moveSources(arg, 3 - arg);
1205 // set 64 bit address and 32-bit format sources
1206 su->setSrc(0, addr);
1207 su->setSrc(1, v);
1208 su->setSrc(2, pred);
1209 }
1210
1211 void
1212 NVC0LoweringPass::handleSurfaceOpNVE4(TexInstruction *su)
1213 {
1214 processSurfaceCoordsNVE4(su);
1215
1216 // Who do we hate more ? The person who decided that nvc0's SULD doesn't
1217 // have to support conversion or the person who decided that, in OpenCL,
1218 // you don't have to specify the format here like you do in OpenGL ?
1219
1220 if (su->op == OP_SULDP) {
1221 // We don't patch shaders. Ever.
1222 // You get an indirect call to our library blob here.
1223 // But at least it's uniform.
1224 FlowInstruction *call;
1225 LValue *p[3];
1226 LValue *r[5];
1227 uint16_t base = su->tex.r * NVE4_SU_INFO__STRIDE + NVE4_SU_INFO_CALL;
1228
1229 for (int i = 0; i < 4; ++i)
1230 (r[i] = bld.getScratch(4, FILE_GPR))->reg.data.id = i;
1231 for (int i = 0; i < 3; ++i)
1232 (p[i] = bld.getScratch(1, FILE_PREDICATE))->reg.data.id = i;
1233 (r[4] = bld.getScratch(8, FILE_GPR))->reg.data.id = 4;
1234
1235 bld.mkMov(p[1], bld.mkImm((su->cache == CACHE_CA) ? 1 : 0), TYPE_U8);
1236 bld.mkMov(p[2], bld.mkImm((su->cache == CACHE_CG) ? 1 : 0), TYPE_U8);
1237 bld.mkMov(p[0], su->getSrc(2), TYPE_U8);
1238 bld.mkMov(r[4], su->getSrc(0), TYPE_U64);
1239 bld.mkMov(r[2], su->getSrc(1), TYPE_U32);
1240
1241 call = bld.mkFlow(OP_CALL, NULL, su->cc, su->getPredicate());
1242
1243 call->indirect = 1;
1244 call->absolute = 1;
1245 call->setSrc(0, bld.mkSymbol(FILE_MEMORY_CONST,
1246 prog->driver->io.resInfoCBSlot, TYPE_U32,
1247 prog->driver->io.suInfoBase + base));
1248 call->setSrc(1, r[2]);
1249 call->setSrc(2, r[4]);
1250 for (int i = 0; i < 3; ++i)
1251 call->setSrc(3 + i, p[i]);
1252 for (int i = 0; i < 4; ++i) {
1253 call->setDef(i, r[i]);
1254 bld.mkMov(su->getDef(i), r[i]);
1255 }
1256 call->setDef(4, p[1]);
1257 delete_Instruction(bld.getProgram(), su);
1258 }
1259
1260 if (su->op == OP_SUREDB || su->op == OP_SUREDP) {
1261 // FIXME: for out of bounds access, destination value will be undefined !
1262 Value *pred = su->getSrc(2);
1263 CondCode cc = CC_NOT_P;
1264 if (su->getPredicate()) {
1265 pred = bld.getScratch(1, FILE_PREDICATE);
1266 cc = su->cc;
1267 if (cc == CC_NOT_P) {
1268 bld.mkOp2(OP_OR, TYPE_U8, pred, su->getPredicate(), su->getSrc(2));
1269 } else {
1270 bld.mkOp2(OP_AND, TYPE_U8, pred, su->getPredicate(), su->getSrc(2));
1271 pred->getInsn()->src(1).mod = Modifier(NV50_IR_MOD_NOT);
1272 }
1273 }
1274 Instruction *red = bld.mkOp(OP_ATOM, su->dType, su->getDef(0));
1275 red->subOp = su->subOp;
1276 if (!gMemBase)
1277 gMemBase = bld.mkSymbol(FILE_MEMORY_GLOBAL, 0, TYPE_U32, 0);
1278 red->setSrc(0, gMemBase);
1279 red->setSrc(1, su->getSrc(3));
1280 if (su->subOp == NV50_IR_SUBOP_ATOM_CAS)
1281 red->setSrc(2, su->getSrc(4));
1282 red->setIndirect(0, 0, su->getSrc(0));
1283 red->setPredicate(cc, pred);
1284 delete_Instruction(bld.getProgram(), su);
1285 handleCasExch(red, true);
1286 } else {
1287 su->sType = (su->tex.target == TEX_TARGET_BUFFER) ? TYPE_U32 : TYPE_U8;
1288 }
1289 }
1290
1291 bool
1292 NVC0LoweringPass::handleWRSV(Instruction *i)
1293 {
1294 Instruction *st;
1295 Symbol *sym;
1296 uint32_t addr;
1297
1298 // must replace, $sreg are not writeable
1299 addr = targ->getSVAddress(FILE_SHADER_OUTPUT, i->getSrc(0)->asSym());
1300 if (addr >= 0x400)
1301 return false;
1302 sym = bld.mkSymbol(FILE_SHADER_OUTPUT, 0, i->sType, addr);
1303
1304 st = bld.mkStore(OP_EXPORT, i->dType, sym, i->getIndirect(0, 0),
1305 i->getSrc(1));
1306 st->perPatch = i->perPatch;
1307
1308 bld.getBB()->remove(i);
1309 return true;
1310 }
1311
1312 void
1313 NVC0LoweringPass::readTessCoord(LValue *dst, int c)
1314 {
1315 Value *laneid = bld.getSSA();
1316 Value *x, *y;
1317
1318 bld.mkOp1(OP_RDSV, TYPE_U32, laneid, bld.mkSysVal(SV_LANEID, 0));
1319
1320 if (c == 0) {
1321 x = dst;
1322 y = NULL;
1323 } else
1324 if (c == 1) {
1325 x = NULL;
1326 y = dst;
1327 } else {
1328 assert(c == 2);
1329 x = bld.getSSA();
1330 y = bld.getSSA();
1331 }
1332 if (x)
1333 bld.mkFetch(x, TYPE_F32, FILE_SHADER_OUTPUT, 0x2f0, NULL, laneid);
1334 if (y)
1335 bld.mkFetch(y, TYPE_F32, FILE_SHADER_OUTPUT, 0x2f4, NULL, laneid);
1336
1337 if (c == 2) {
1338 bld.mkOp2(OP_ADD, TYPE_F32, dst, x, y);
1339 bld.mkOp2(OP_SUB, TYPE_F32, dst, bld.loadImm(NULL, 1.0f), dst);
1340 }
1341 }
1342
1343 bool
1344 NVC0LoweringPass::handleRDSV(Instruction *i)
1345 {
1346 Symbol *sym = i->getSrc(0)->asSym();
1347 const SVSemantic sv = sym->reg.data.sv.sv;
1348 Value *vtx = NULL;
1349 Instruction *ld;
1350 uint32_t addr = targ->getSVAddress(FILE_SHADER_INPUT, sym);
1351
1352 if (addr >= 0x400) {
1353 // mov $sreg
1354 if (sym->reg.data.sv.index == 3) {
1355 // TGSI backend may use 4th component of TID,NTID,CTAID,NCTAID
1356 i->op = OP_MOV;
1357 i->setSrc(0, bld.mkImm((sv == SV_NTID || sv == SV_NCTAID) ? 1 : 0));
1358 }
1359 return true;
1360 }
1361
1362 switch (sv) {
1363 case SV_POSITION:
1364 assert(prog->getType() == Program::TYPE_FRAGMENT);
1365 if (i->srcExists(1)) {
1366 // Pass offset through to the interpolation logic
1367 ld = bld.mkInterp(NV50_IR_INTERP_LINEAR | NV50_IR_INTERP_OFFSET,
1368 i->getDef(0), addr, NULL);
1369 ld->setSrc(1, i->getSrc(1));
1370 } else {
1371 bld.mkInterp(NV50_IR_INTERP_LINEAR, i->getDef(0), addr, NULL);
1372 }
1373 break;
1374 case SV_FACE:
1375 {
1376 Value *face = i->getDef(0);
1377 bld.mkInterp(NV50_IR_INTERP_FLAT, face, addr, NULL);
1378 if (i->dType == TYPE_F32) {
1379 bld.mkOp2(OP_AND, TYPE_U32, face, face, bld.mkImm(0x80000000));
1380 bld.mkOp2(OP_XOR, TYPE_U32, face, face, bld.mkImm(0xbf800000));
1381 }
1382 }
1383 break;
1384 case SV_TESS_COORD:
1385 assert(prog->getType() == Program::TYPE_TESSELLATION_EVAL);
1386 readTessCoord(i->getDef(0)->asLValue(), i->getSrc(0)->reg.data.sv.index);
1387 break;
1388 case SV_NTID:
1389 case SV_NCTAID:
1390 case SV_GRIDID:
1391 assert(targ->getChipset() >= NVISA_GK104_CHIPSET); // mov $sreg otherwise
1392 if (sym->reg.data.sv.index == 3) {
1393 i->op = OP_MOV;
1394 i->setSrc(0, bld.mkImm(sv == SV_GRIDID ? 0 : 1));
1395 return true;
1396 }
1397 addr += prog->driver->prop.cp.gridInfoBase;
1398 bld.mkLoad(TYPE_U32, i->getDef(0),
1399 bld.mkSymbol(FILE_MEMORY_CONST, 0, TYPE_U32, addr), NULL);
1400 break;
1401 case SV_SAMPLE_INDEX:
1402 // TODO: Properly pass source as an address in the PIX address space
1403 // (which can be of the form [r0+offset]). But this is currently
1404 // unnecessary.
1405 ld = bld.mkOp1(OP_PIXLD, TYPE_U32, i->getDef(0), bld.mkImm(0));
1406 ld->subOp = NV50_IR_SUBOP_PIXLD_SAMPLEID;
1407 break;
1408 case SV_SAMPLE_POS: {
1409 Value *off = new_LValue(func, FILE_GPR);
1410 ld = bld.mkOp1(OP_PIXLD, TYPE_U32, i->getDef(0), bld.mkImm(0));
1411 ld->subOp = NV50_IR_SUBOP_PIXLD_SAMPLEID;
1412 bld.mkOp2(OP_SHL, TYPE_U32, off, i->getDef(0), bld.mkImm(3));
1413 bld.mkLoad(TYPE_F32,
1414 i->getDef(0),
1415 bld.mkSymbol(
1416 FILE_MEMORY_CONST, prog->driver->io.resInfoCBSlot,
1417 TYPE_U32, prog->driver->io.sampleInfoBase +
1418 4 * sym->reg.data.sv.index),
1419 off);
1420 break;
1421 }
1422 case SV_SAMPLE_MASK:
1423 ld = bld.mkOp1(OP_PIXLD, TYPE_U32, i->getDef(0), bld.mkImm(0));
1424 ld->subOp = NV50_IR_SUBOP_PIXLD_COVMASK;
1425 break;
1426 default:
1427 if (prog->getType() == Program::TYPE_TESSELLATION_EVAL)
1428 vtx = bld.mkOp1v(OP_PFETCH, TYPE_U32, bld.getSSA(), bld.mkImm(0));
1429 ld = bld.mkFetch(i->getDef(0), i->dType,
1430 FILE_SHADER_INPUT, addr, i->getIndirect(0, 0), vtx);
1431 ld->perPatch = i->perPatch;
1432 break;
1433 }
1434 bld.getBB()->remove(i);
1435 return true;
1436 }
1437
1438 bool
1439 NVC0LoweringPass::handleDIV(Instruction *i)
1440 {
1441 if (!isFloatType(i->dType))
1442 return true;
1443 bld.setPosition(i, false);
1444 Instruction *rcp = bld.mkOp1(OP_RCP, i->dType, bld.getSSA(), i->getSrc(1));
1445 i->op = OP_MUL;
1446 i->setSrc(1, rcp->getDef(0));
1447 return true;
1448 }
1449
1450 bool
1451 NVC0LoweringPass::handleMOD(Instruction *i)
1452 {
1453 if (i->dType != TYPE_F32)
1454 return true;
1455 LValue *value = bld.getScratch();
1456 bld.mkOp1(OP_RCP, TYPE_F32, value, i->getSrc(1));
1457 bld.mkOp2(OP_MUL, TYPE_F32, value, i->getSrc(0), value);
1458 bld.mkOp1(OP_TRUNC, TYPE_F32, value, value);
1459 bld.mkOp2(OP_MUL, TYPE_F32, value, i->getSrc(1), value);
1460 i->op = OP_SUB;
1461 i->setSrc(1, value);
1462 return true;
1463 }
1464
1465 bool
1466 NVC0LoweringPass::handleSQRT(Instruction *i)
1467 {
1468 Instruction *rsq = bld.mkOp1(OP_RSQ, TYPE_F32,
1469 bld.getSSA(), i->getSrc(0));
1470 i->op = OP_MUL;
1471 i->setSrc(1, rsq->getDef(0));
1472
1473 return true;
1474 }
1475
1476 bool
1477 NVC0LoweringPass::handlePOW(Instruction *i)
1478 {
1479 LValue *val = bld.getScratch();
1480
1481 bld.mkOp1(OP_LG2, TYPE_F32, val, i->getSrc(0));
1482 bld.mkOp2(OP_MUL, TYPE_F32, val, i->getSrc(1), val)->dnz = 1;
1483 bld.mkOp1(OP_PREEX2, TYPE_F32, val, val);
1484
1485 i->op = OP_EX2;
1486 i->setSrc(0, val);
1487 i->setSrc(1, NULL);
1488
1489 return true;
1490 }
1491
1492 bool
1493 NVC0LoweringPass::handleEXPORT(Instruction *i)
1494 {
1495 if (prog->getType() == Program::TYPE_FRAGMENT) {
1496 int id = i->getSrc(0)->reg.data.offset / 4;
1497
1498 if (i->src(0).isIndirect(0)) // TODO, ugly
1499 return false;
1500 i->op = OP_MOV;
1501 i->subOp = NV50_IR_SUBOP_MOV_FINAL;
1502 i->src(0).set(i->src(1));
1503 i->setSrc(1, NULL);
1504 i->setDef(0, new_LValue(func, FILE_GPR));
1505 i->getDef(0)->reg.data.id = id;
1506
1507 prog->maxGPR = MAX2(prog->maxGPR, id);
1508 } else
1509 if (prog->getType() == Program::TYPE_GEOMETRY) {
1510 i->setIndirect(0, 1, gpEmitAddress);
1511 }
1512 return true;
1513 }
1514
1515 bool
1516 NVC0LoweringPass::handleOUT(Instruction *i)
1517 {
1518 Instruction *prev = i->prev;
1519 ImmediateValue stream, prevStream;
1520
1521 // Only merge if the stream ids match. Also, note that the previous
1522 // instruction would have already been lowered, so we take arg1 from it.
1523 if (i->op == OP_RESTART && prev && prev->op == OP_EMIT &&
1524 i->src(0).getImmediate(stream) &&
1525 prev->src(1).getImmediate(prevStream) &&
1526 stream.reg.data.u32 == prevStream.reg.data.u32) {
1527 i->prev->subOp = NV50_IR_SUBOP_EMIT_RESTART;
1528 delete_Instruction(prog, i);
1529 } else {
1530 assert(gpEmitAddress);
1531 i->setDef(0, gpEmitAddress);
1532 i->setSrc(1, i->getSrc(0));
1533 i->setSrc(0, gpEmitAddress);
1534 }
1535 return true;
1536 }
1537
1538 // Generate a binary predicate if an instruction is predicated by
1539 // e.g. an f32 value.
1540 void
1541 NVC0LoweringPass::checkPredicate(Instruction *insn)
1542 {
1543 Value *pred = insn->getPredicate();
1544 Value *pdst;
1545
1546 if (!pred || pred->reg.file == FILE_PREDICATE)
1547 return;
1548 pdst = new_LValue(func, FILE_PREDICATE);
1549
1550 // CAUTION: don't use pdst->getInsn, the definition might not be unique,
1551 // delay turning PSET(FSET(x,y),0) into PSET(x,y) to a later pass
1552
1553 bld.mkCmp(OP_SET, CC_NEU, insn->dType, pdst, insn->dType, bld.mkImm(0), pred);
1554
1555 insn->setPredicate(insn->cc, pdst);
1556 }
1557
1558 //
1559 // - add quadop dance for texturing
1560 // - put FP outputs in GPRs
1561 // - convert instruction sequences
1562 //
1563 bool
1564 NVC0LoweringPass::visit(Instruction *i)
1565 {
1566 bld.setPosition(i, false);
1567
1568 if (i->cc != CC_ALWAYS)
1569 checkPredicate(i);
1570
1571 switch (i->op) {
1572 case OP_TEX:
1573 case OP_TXB:
1574 case OP_TXL:
1575 case OP_TXF:
1576 case OP_TXG:
1577 return handleTEX(i->asTex());
1578 case OP_TXD:
1579 return handleTXD(i->asTex());
1580 case OP_TXLQ:
1581 return handleTXLQ(i->asTex());
1582 case OP_TXQ:
1583 return handleTXQ(i->asTex());
1584 case OP_EX2:
1585 bld.mkOp1(OP_PREEX2, TYPE_F32, i->getDef(0), i->getSrc(0));
1586 i->setSrc(0, i->getDef(0));
1587 break;
1588 case OP_POW:
1589 return handlePOW(i);
1590 case OP_DIV:
1591 return handleDIV(i);
1592 case OP_MOD:
1593 return handleMOD(i);
1594 case OP_SQRT:
1595 return handleSQRT(i);
1596 case OP_EXPORT:
1597 return handleEXPORT(i);
1598 case OP_EMIT:
1599 case OP_RESTART:
1600 return handleOUT(i);
1601 case OP_RDSV:
1602 return handleRDSV(i);
1603 case OP_WRSV:
1604 return handleWRSV(i);
1605 case OP_LOAD:
1606 if (i->src(0).getFile() == FILE_SHADER_INPUT) {
1607 if (prog->getType() == Program::TYPE_COMPUTE) {
1608 i->getSrc(0)->reg.file = FILE_MEMORY_CONST;
1609 i->getSrc(0)->reg.fileIndex = 0;
1610 } else
1611 if (prog->getType() == Program::TYPE_GEOMETRY &&
1612 i->src(0).isIndirect(0)) {
1613 // XXX: this assumes vec4 units
1614 Value *ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
1615 i->getIndirect(0, 0), bld.mkImm(4));
1616 i->setIndirect(0, 0, ptr);
1617 } else {
1618 i->op = OP_VFETCH;
1619 assert(prog->getType() != Program::TYPE_FRAGMENT); // INTERP
1620 }
1621 } else if (i->src(0).getFile() == FILE_MEMORY_CONST) {
1622 if (i->src(0).isIndirect(1)) {
1623 Value *ptr;
1624 if (i->src(0).isIndirect(0))
1625 ptr = bld.mkOp3v(OP_INSBF, TYPE_U32, bld.getSSA(),
1626 i->getIndirect(0, 1), bld.mkImm(0x1010),
1627 i->getIndirect(0, 0));
1628 else
1629 ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
1630 i->getIndirect(0, 1), bld.mkImm(16));
1631 i->setIndirect(0, 1, NULL);
1632 i->setIndirect(0, 0, ptr);
1633 i->subOp = NV50_IR_SUBOP_LDC_IS;
1634 }
1635 }
1636 break;
1637 case OP_ATOM:
1638 {
1639 const bool cctl = i->src(0).getFile() == FILE_MEMORY_GLOBAL;
1640 handleATOM(i);
1641 handleCasExch(i, cctl);
1642 }
1643 break;
1644 case OP_SULDB:
1645 case OP_SULDP:
1646 case OP_SUSTB:
1647 case OP_SUSTP:
1648 case OP_SUREDB:
1649 case OP_SUREDP:
1650 if (targ->getChipset() >= NVISA_GK104_CHIPSET)
1651 handleSurfaceOpNVE4(i->asTex());
1652 break;
1653 default:
1654 break;
1655 }
1656 return true;
1657 }
1658
1659 bool
1660 TargetNVC0::runLegalizePass(Program *prog, CGStage stage) const
1661 {
1662 if (stage == CG_STAGE_PRE_SSA) {
1663 NVC0LoweringPass pass(prog);
1664 return pass.run(prog, false, true);
1665 } else
1666 if (stage == CG_STAGE_POST_RA) {
1667 NVC0LegalizePostRA pass(prog);
1668 return pass.run(prog, false, true);
1669 } else
1670 if (stage == CG_STAGE_SSA) {
1671 NVC0LegalizeSSA pass;
1672 return pass.run(prog, false, true);
1673 }
1674 return false;
1675 }
1676
1677 } // namespace nv50_ir