Debian Codegraph @

visa/iga/IGALibrary/Frontend/FormatterJSON2.cpp

raw
1 /*========================== begin_copyright_notice ============================
2
3 Copyright (C) 2021 Intel Corporation
4
5 SPDX-License-Identifier: MIT
6
7 ============================= end_copyright_notice ===========================*/
8
9 #include "FormatterJSON.hpp"
10 #include "../IR/Messages.hpp"
11 #include "IRToString.hpp"
12
13 #include <unordered_map>
14 #include <set>
15
16 using namespace iga;
17
18 class JSONFormatterV2 : public BasicFormatter {
19 protected:
20 const Model &model;
21 const FormatOpts &opts;
22 const uint8_t *bits;
23 int currIndent = 2;
24
25 // map instruction ID to all def/use pairs
26 using DUMap = std::unordered_map<int, std::vector<const Dep *>>;
27 DUMap depDefs, depUses;
28
29 const RegSet EMPTY_SET;
30
31 public:
32 JSONFormatterV2(std::ostream &o, const FormatOpts &os, const void *bs)
33 : BasicFormatter(false, o), model(os.model), opts(os),
34 bits((const uint8_t *)bs), EMPTY_SET(os.model) {
35 o << std::boolalpha;
36 if (opts.liveAnalysis) {
37 for (const Dep &d : opts.liveAnalysis->deps) {
38 if (d.def != nullptr) {
39 depDefs[d.def->getID()].emplace_back(&d);
40 }
41 if (d.use != nullptr) {
42 depUses[d.use->getID()].emplace_back(&d);
43 }
44 }
45 }
46 }
47 Platform platform() const { return model.platform; }
48
49 // emits an error value that'll blow up on JSON load
50 void emitIrError(const char *what) { emit("IR.Error(\"", what, "\")"); }
51
52 void emitEscaped(const std::string &s) {
53 for (size_t i = 0; i < s.size(); i++) {
54 switch (s[i]) {
55 case '\n':
56 emit("\\n");
57 break;
58 case '\t':
59 emit("\\t");
60 break;
61 case '\v':
62 emit("\\v");
63 break;
64 case '\f':
65 emit("\\f");
66 break;
67 case '\a':
68 emit("\\a");
69 break;
70 case '\"':
71 emit("\\\"");
72 break;
73 case '\\':
74 emit("\\\\");
75 break;
76 default:
77 emit(s[i]);
78 break;
79 }
80 }
81 }
82
83 void emitIndent() {
84 for (int i = 0; i < currIndent; i++)
85 emit(' ');
86 }
87 void withIndent(const std::function<void()> &f) {
88 currIndent += 2;
89 f();
90 currIndent -= 2;
91 }
92
93 void emitLabel(int32_t pc) {
94 bool printed = false;
95 if (opts.labeler) {
96 const char *usrL = opts.labeler(pc, opts.labelerContext);
97 if (usrL) {
98 printed = true;
99 emit(usrL);
100 }
101 }
102 if (!printed) {
103 std::stringstream ss;
104 ss << std::setw(4) << std::dec << std::setfill('0') << pc;
105 emit("L", ss.str());
106 }
107 }
108
109 void emitKernel(const Kernel &k) {
110 precomputeBlockGraph(k);
111
112 emit("{\n");
113 emit(" \"version\":\"2.0\",\n");
114 emit(" \"platform\":\"", model.names[0].str(), "\",\n");
115 emit(" \"elems\":[\n");
116 currIndent += 2;
117
118 for (const Block *b : k.getBlockList()) {
119 emitIndent();
120 emit("{\"kind\":\"L\"");
121 emit(", \"id\":", b->getID());
122 if (opts.printInstPc) {
123 emit(", \"pc\":", b->getPC());
124 }
125 emit(", \"symbol\":\"");
126 emitLabel(b->getPC());
127 emit("\"");
128
129 auto emitSet = [&](const char *which, const std::set<int> &ids) {
130 if (ids.empty()) {
131 return;
132 }
133 emit(", ", which, ":[");
134 bool first = true;
135 for (int id : ids) {
136 if (first)
137 first = false;
138 else
139 emit(",");
140 emit(id);
141 }
142 emit("]");
143 }; // emitSet
144 emitSet("\"preds\"", preds[b]);
145 emitSet("\"succs\"", succs[b]);
146
147 emit("}");
148 if (b != k.getBlockList().back() || !b->getInstList().empty())
149 emit(",");
150 emit("\n");
151
152 for (const Instruction *iP : b->getInstList()) {
153 emitInst(*iP);
154 if (iP != b->getInstList().back() || b != k.getBlockList().back())
155 emit(",");
156 emit("\n");
157 }
158 }
159
160 emit(" ]\n");
161 currIndent -= 2;
162 emit("}\n");
163 emit("\n");
164 }
165
166 std::unordered_map<const Block *,std::set<int>> preds, succs;
167
168 void precomputeBlockGraph(const Kernel &k) {
169 succs.clear();
170 preds.clear();
171
172 const auto &bl = k.getBlockList();
173 auto itr = bl.begin();
174
175 auto addEdge =
176 [&](const Block *p, const Block *s) {
177 preds[s].insert(p->getID());
178 succs[p].insert(s->getID());
179 }; // addEdge
180
181 while (itr != bl.end()) {
182 const Block *b = *itr++;
183 auto addBranchTarget =
184 [&](const Operand &op) {
185 if (op.getKind() != Operand::Kind::LABEL) {
186 return;
187 }
188 const Block *bt = op.getTargetBlock();
189 if (bt) {
190 addEdge(b, bt);
191 }
192 }; // addBranchTarget
193
194 const auto &bInsts = b->getInstList();
195 if (bInsts.empty()) {
196 // empty block: fallthrough
197 if (itr != bl.end()) {
198 addEdge(b, *itr);
199 }
200 } else {
201 // non-empty block: look at last instruction
202 const Instruction &li = *bInsts.back();
203 if (!li.isBranching()) {
204 // non-branching: fallthrough (unless EOT which kills program)
205 bool unpredicatedEot =
206 !li.hasInstOpt(InstOpt::EOT) && !li.hasPredication();
207 if (itr != bl.end() && !unpredicatedEot) {
208 addEdge(b, *itr);
209 }
210 } else {
211 // edges to all operands
212 for (unsigned i = 0; i < li.getSourceCount(); i++) {
213 addBranchTarget(li.getSource(i));
214 }
215 // fallthrough only if not unpredicated jmpi
216 if (!li.is(Op::JMPI) || li.hasPredication()) {
217 if (itr != bl.end())
218 addEdge(b, *itr);
219 }
220 }
221 }
222 } // while
223 }
224
225 std::vector<std::string> comments;
226
227 void emitInst(const Instruction &i) {
228 comments.clear();
229
230 // const bool isSend = i.getOpSpec().isAnySendFormat();
231 emitIndent();
232 emit("{");
233 emit("\"kind\":\"I\"");
234 emit(", \"id\":", i.getID());
235 if (opts.printInstPc) {
236 emit(", \"pc\":", i.getPC());
237 }
238
239 if (opts.printLdSt) {
240 if (!emitLdStInst(i)) {
241 emitNormalInst(i);
242 }
243 } else {
244 emitNormalInst(i);
245 }
246
247 if (platform() >= Platform::XE) {
248 emitRegDist(i.getSWSB());
249 emitSbid(i.getSWSB());
250 }
251 emitInstOpts(i);
252
253 bool printBits = opts.printInstBits && bits != nullptr;
254 if (printBits) {
255 emit(", \"encoding\":");
256 const uint32_t *instBits = (const uint32_t *)(bits + i.getPC());
257 emit('\"');
258 if (!i.hasInstOpt(InstOpt::COMPACTED)) {
259 emitHex(instBits[3], 8);
260 emit('`');
261 emitHex(instBits[2], 8);
262 emit('`');
263 }
264 emitHex(instBits[1], 8);
265 emit('`');
266 emitHex(instBits[0], 8);
267 emit('\"');
268 }
269
270 if (opts.printInstDefs && opts.liveAnalysis &&
271 !opts.liveAnalysis->sums.empty()) {
272 emit(", \"liveTotals\":{");
273 const auto &totals = opts.liveAnalysis->sums[i.getID()];
274 emit("\"r\":", totals.grfBytes, ",");
275 emit("\"acc\":", totals.accBytes, ",");
276 emit("\"s\":", totals.scalarBytes, ",");
277 emit("\"f\":", totals.flagBytes, ",");
278 emit("\"a\":", totals.indexBytes);
279 emit("}");
280 }
281
282 if (!comments.empty()) {
283 emit(", \"comment\":\"");
284 for (size_t i = 0; i < comments.size(); i++) {
285 if (i > 0)
286 emit("; ");
287 emitEscaped(comments[i]);
288 }
289 emit("\"");
290 }
291 emit("}");
292 }
293
294 void emitNormalInst(const Instruction &i) {
295 std::string subfunc;
296 switch (i.getOpSpec().op) {
297 case Op::MATH:
298 subfunc = ToSyntax(i.getSubfunction().math);
299 break;
300 case Op::SEND:
301 case Op::SENDC:
302 subfunc = ToSyntax(i.getSubfunction().send);
303 break;
304 case Op::SENDG:
305 case Op::SENDGC:
306 case Op::SENDGX:
307 case Op::SENDGXC:
308 subfunc = ToSyntax(i.getSubfunction().send);
309 break;
310 case Op::SYNC:
311 subfunc = ToSyntax(i.getSubfunction().sync);
312 break;
313 case Op::BFN:
314 if (opts.syntaxBfnSymbolicFunctions) {
315 // decode binary function names to symbolic
316 // bfn.(s0&s1|~s2)
317 subfunc += format("(", i.getBfnFc().c_str(), ")");
318 } else {
319 // use a raw value
320 // emit<uint32_t>(i.getBfnFc().value);
321 subfunc = fmtHex((int)i.getBfnFc().value, 2);
322 }
323 break;
324 case Op::DPASW:
325 case Op::DPAS:
326 subfunc = ToSyntax(i.getDpasFc());
327 break;
328 default:
329 break;
330 }
331
332 emitPredOpSubfuncExecInfoFlagReg(i, i.getOpSpec().mnemonic.str(), subfunc);
333 // implicit accumulator def/uses
334 if (opts.liveAnalysis) {
335 RegSet accIn {model};
336 accIn.addSourceImplicit(i);
337 RegSet accOu {model};
338 accOu.addDestinationImplicit(i);
339 if (!accIn.empty() || !accOu.empty()) {
340 emit(", \"implicit\":{");
341 bool emittedInputs = emitDepInputs(i, accIn, false);
342 emitDepOutputs(i, accOu, emittedInputs);
343 emit("}");
344 }
345 }
346
347 withIndent([&] {
348 emit(",\n");
349 emitDstCommaNewline(i);
350 emitIndent();
351 if (i.getSourceCount() > 0) {
352 emit("\"srcs\":[\n");
353 withIndent([&] {
354 for (unsigned srcIx = 0; srcIx < i.getSourceCount(); srcIx++) {
355 emitIndent();
356 emitSrc(i, srcIx);
357 if (srcIx != i.getSourceCount() - 1)
358 emit(",\n");
359 }
360 // if it's a send, create fake extra send parameters
361 bool hasSendDescs = i.getOpSpec().isAnySendFormat();
362 hasSendDescs &= !i.getOpSpec().isSendgFormat();
363 if (hasSendDescs) {
364 auto emitDesc = [&](SendDesc sd) {
365 emit(",\n");
366 emitIndent();
367 emit("{");
368 if (sd.type == SendDesc::Kind::REG32A) {
369 RegSet rs {model};
370 emitKindField(Operand::Kind::DIRECT);
371 emit(", \"reg\":"); emitRegValue(RegName::ARF_A, sd.reg);
372 rs.setSrcRegion(RegName::ARF_A, sd.reg, Region::SRC110, 2, 16);
373 emitDepInputs(i, rs);
374 } else {
375 emitKindField(Operand::Kind::IMMEDIATE);
376 emit(", \"value\":\"0x", hex(sd.imm), "\"");
377 }
378 emit("}");
379 };
380 emitDesc(i.getExtMsgDescriptor());
381 emitDesc(i.getMsgDescriptor());
382 }
383 });
384 if (i.getOpSpec().isSendgFormat()) {
385 auto emitSendgIdReg = [&](const RegRef &rr) {
386 if (rr == REGREF_INVALID)
387 return;
388 RegSet rs {model};
389 emit(",\n");
390 emitIndent();
391 emit("{");
392 emitKindField(Operand::Kind::DIRECT);
393 emit(", \"reg\":");
394 emitRegValue(RegName::ARF_S, rr);
395 rs.setSrcRegion(RegName::ARF_S, rr, Region::SRC010, 1, 64);
396 emitDepInputs(i, rs);
397 emit("}");
398 };
399 emitSendgIdReg(i.getSendgIndDesc0Reg());
400 emitSendgIdReg(i.getSendgIndDesc0Reg());
401 emit(",\n");
402 emitIndent();
403 emitKindField(Operand::Kind::IMMEDIATE);
404 emit(", \"value\":\"0x", hex(i.getSendgDesc()), "\"");
405 }
406 emit("\n");
407 emitIndent();
408 emit("]");
409 } else {
410 emit("\"srcs\":[]"); // so we print *something* (for next comma)
411 }
412 });
413 } // emitNormalInst
414
415 /////////////////////////////////////////////////////////////////////////
416 bool emitLdStInst(const Instruction &i) {
417 const auto desc = i.getMsgDescriptor();
418 if (desc.isReg()) {
419 // given a register descriptor, we've no hope of decoding the op
420 // fallback to the regular canonical send path
421 return false;
422 }
423 const auto exDesc = i.getExtMsgDescriptor();
424 const auto sfid = i.getSendFc();
425 DecodeResult di;
426 bool defaultDecode = i.getOpSpec().isAnySendFormat();
427 defaultDecode &= !i.getOpSpec().isSendgFormat();
428 if (defaultDecode) {
429 di = tryDecode(platform(), sfid, i.getExecSize(),
430 i.getExtImmOffDescriptor(),
431 exDesc, desc, nullptr);
432 } else if (i.getOpSpec().isSendgFormat()) {
433 di = tryDecode(platform(), sfid, i.getExecSize(),
434 i.getSrc0Length(), i.getSrc1Length(),
435 i.getSendgIndDesc0Reg(), i.getSendgIndDesc1Reg(),
436 i.getSendgDesc(), nullptr);
437 }
438 if (!di) {
439 // if message decode failed fallback to the canonical send syntax
440 return false;
441 } else if (!sendOpSupportsSyntax(platform(), di.info.op, sfid)) {
442 // if decode succeeded but the syntax isn't supported, then bail
443 return false;
444 }
445
446 emitPredOpSubfuncExecInfoFlagReg(i, di.syntax.mnemonic, di.syntax.controls);
447
448 emit(",\n");
449 withIndent([&] {
450 emitIndent();
451 if (!di.syntax.isStore()) {
452 // there is an explicit destination
453 const Operand &dst = i.getDestination();
454 emit("\"dst\":{");
455 emitSendDataRegDst(i, dst.getDirRegName(), dst.getDirRegRef().regNum,
456 i.getDstLength());
457 emit("},\n");
458 }
459
460 /////////////////////////////////////////////
461 // sources
462 emitIndent();
463 emit("\"srcs\":[\n");
464 withIndent([&] {
465 // everyone has src0 as an address
466 emitIndent();
467 emit("{\"kind\":\"AD\", ");
468 emitSendSrc0AddressFields(i);
469 emitSendSrc0AddrSurfFields(i, di.info);
470 emit("},\n");
471
472 //////////////////////////////////////
473 // src1 (if not the old unary send)
474 if (i.getSourceCount() > 1) {
475 emitIndent();
476 emitSendPayloadSrc(i, 1, "DA");
477 emit("\n");
478 }
479 });
480
481 emitIndent();
482 emit("]"); // end of srcs:[..]
483 });
484
485 return true;
486 }
487
488 /////////////////////////////////////////////////////////////////////////
489 // op+subfunc+exec size and exec offset
490 void emitPredOpSubfuncExecInfoFlagReg(const Instruction &i,
491 const std::string& mnemonic,
492 const std::string& subop) {
493 emitPred(i);
494
495 emit(", \"op\":\"", mnemonic, "\"");
496 if (!subop.empty()) {
497 const auto& sf = subop[0] == '.' ? subop.substr(1) : subop;
498 emit(", \"subop\":\"", sf, "\"");
499 }
500
501 emit(", \"es\":", ToSyntax(i.getExecSize()));
502 if (i.getChannelOffset() != ChannelOffset::M0)
503 emit(", \"eo\":", 4 * (int)(i.getChannelOffset()));
504
505 if (i.hasFlagModifier()) {
506 emit(", \"fm\":{\"cond\":\"", ToSyntax(i.getFlagModifier()), "\"");
507 RegSet rs {model};
508 rs.addFlagModifierOutputs(i);
509 emitDepOutputs(i, rs);
510 emit("}");
511 }
512
513 emitFlagReg(i);
514 }
515
516
517 // pred:{func:[null|""|".any"|".all"|...],inv:[true|false]"",wren:[true|false]}
518 void emitPred(const Instruction &i) {
519 Predication p = i.getPredication();
520 if (i.hasPredication()) {
521 emit(", \"pred\":");
522 emit("{");
523 if (p.inverse) {
524 emit("\"inv\":true, ");
525 }
526 emit("\"func\":\"", ToSyntax(p.function), "\"");
527 RegSet rs {model};
528 rs.addPredicationInputs(i);
529 emitDepInputs(i, rs);
530 emit("}");
531 }
532 //
533 if (i.getMaskCtrl() == MaskCtrl::NOMASK) {
534 emit(", \"wren\":true");
535 }
536 }
537
538 // {flag:{reg:...}}
539 void emitFlagReg(const Instruction &i) {
540 if (i.hasPredication() || (i.hasFlagModifier() && !i.is(Op::SEL))) {
541 emit(", \"freg\":");
542 emitRegValue(RegName::ARF_F, i.getFlagReg());
543 }
544 }
545
546 // dst:{kind=..., REST, sat:T|F, uses:...}
547 void emitDstCommaNewline(const Instruction &i) {
548 const OpSpec &os = i.getOpSpec();
549 if (os.isAnySendFormat()) {
550 emitIndent();
551 emit("\"dst\":");
552 emitSendDstValue(i);
553 emit(",\n");
554 return;
555 }
556 const Operand &dst = i.getDestination();
557 if (!i.getOpSpec().supportsDestination()) {
558 return;
559 }
560 emitIndent();
561 emit("\"dst\":");
562 emit("{");
563 emitKindField(dst.getKind());
564 switch (dst.getKind()) {
565 case Operand::Kind::DIRECT:
566 emit(", \"reg\":");
567 emitRegValue(dst.getDirRegName(), dst.getDirRegRef());
568 break;
569 case Operand::Kind::MACRO:
570 emit(", \"reg\":");
571 emitRegValue(dst.getDirRegName(), dst.getDirRegRef());
572 emit(", ");
573 emitMathMacroExtField(dst.getMathMacroExt());
574 break;
575 case Operand::Kind::INDIRECT:
576 emit(", \"areg\":");
577 emitRegValue(RegName::ARF_A, dst.getIndAddrReg());
578 emit(", \"aoff\":", dst.getIndImmAddr());
579 break;
580 default:
581 break;
582 }
583 if (dst.getDstModifier() == DstModifier::SAT) {
584 emit(", \"sat\":true");
585 }
586 if (!os.hasImplicitDstRegion(i.isMacro())) {
587 emitRgnField(i, dst.getRegion(), true);
588 }
589 emitTypeField(dst.getType());
590
591 // uses
592 RegSet rs {model};
593 rs.addDestinationOutputs(i);
594 emitDepOutputs(i, rs);
595 emit("},\n");
596 }
597
598 void emitMathMacroExtField(MathMacroExt mme) {
599 emit("\"mme\":\"", ToSyntax(mme).substr(1), "\"");
600 }
601
602 void emitSrc(const Instruction &i, int srcIx) {
603 const OpSpec &os = i.getOpSpec();
604 if (os.isAnySendFormat()) {
605 emitSendSrc(i, srcIx);
606 return;
607 }
608 const Operand &src = i.getSource(srcIx);
609 emit("{");
610 emitKindField(src.getKind());
611 bool immOrLbl = false;
612 switch (src.getKind()) {
613 case Operand::Kind::DIRECT:
614 emitSrcModifierField(src.getSrcModifier());
615 emit(", \"reg\":");
616 emitRegValue(src.getDirRegName(), src.getDirRegRef());
617 emitSrcRgn(i, srcIx);
618 break;
619 case Operand::Kind::MACRO:
620 emitSrcModifierField(src.getSrcModifier());
621 emit(", \"reg\":");
622 emitRegValue(src.getDirRegName(), src.getDirRegRef());
623 emit(", ");
624 emitMathMacroExtField(src.getMathMacroExt());
625 emitSrcRgn(i, srcIx);
626 break;
627 case Operand::Kind::INDIRECT:
628 emitSrcModifierField(src.getSrcModifier());
629 emit(", \"areg\":");
630 emitRegValue(RegName::ARF_A, src.getIndAddrReg());
631 emit(", \"aoff\":", src.getIndImmAddr());
632 emitSrcRgn(i, srcIx);
633 break;
634 case Operand::Kind::IMMEDIATE: {
635 emit(", \"value\":\"");
636 auto imm = src.getImmediateValue();
637 switch (src.getType()) {
638 case Type::UB:
639 emitHex(imm.u8);
640 break;
641 case Type::UW:
642 emitHex(imm.u16);
643 break;
644 case Type::UD:
645 emitHex(imm.u32);
646 break;
647 case Type::UQ:
648 emitHex(imm.u64);
649 break;
650 case Type::B:
651 emitDecimal(imm.s8);
652 break;
653 case Type::W:
654 emitDecimal(imm.s16);
655 break;
656 case Type::D:
657 emitDecimal(imm.s32);
658 break;
659 case Type::Q:
660 emitDecimal(imm.s64);
661 break;
662 case Type::BF:
663 emitHex(imm.u16);
664 break;
665 case Type::HF:
666 if (opts.hexFloats) {
667 emitHex(imm.u16);
668 } else {
669 FormatFloat(o, imm.u16);
670 }
671 break;
672 case Type::F:
673 case Type::TF32:
674 if (opts.hexFloats) {
675 emitHex(imm.u32);
676 } else {
677 emitFloat(imm.f32);
678 }
679 break;
680 case Type::DF:
681 if (opts.hexFloats) {
682 emitHex(imm.u64);
683 } else {
684 emitFloat(imm.f64);
685 }
686 break;
687 case Type::BF8:
688 case Type::HF8:
689 emitHex(imm.u8);
690 break;
691 case Type::V:
692 emitHex(imm.u32);
693 break;
694 case Type::UV:
695 emitHex(imm.u32);
696 break;
697 case Type::VF:
698 emitHex(imm.u32);
699 break;
700 default:
701 emitIrError("invalid type for imm");
702 }
703 emit("\"");
704 immOrLbl = true;
705 break;
706 }
707 case Operand::Kind::LABEL: {
708 const Block *b = src.getTargetBlock();
709 emit(", \"target\":\"");
710 emitLabel(b ? b->getPC() : src.getImmediateValue().s32);
711 emit("\"");
712 immOrLbl = true;
713 break;
714 }
715 default:
716 break;
717 }
718
719 if (!os.hasImplicitSrcType(srcIx, immOrLbl)) {
720 emitTypeField(src.getType());
721 }
722
723 // even immediate fields will have this; it'll just be empty
724 RegSet rs {model};
725 rs.addSourceOperandInput(i, srcIx);
726 if (!rs.empty())
727 emitDepInputs(i, rs);
728
729 emit("}");
730 }
731
732 void emitSendDstValue(const Instruction &i) {
733 const Operand &dst = i.getDestination();
734 emit("{");
735 if (i.getDstLength() >= 0) {
736 // new style send (r13:4) (take bits from desc)
737 emitSendDataRegDst(i, dst.getDirRegName(), dst.getDirRegRef().regNum,
738 i.getDstLength());
739 } else {
740 emit("\"kind\":\"RD\"");
741 emit(", \"reg\":");
742 emitRegValue(dst.getDirRegName(), dst.getDirRegRef());
743 }
744 emit("}");
745 }
746
747 void emitSrcModifierField(SrcModifier sm) {
748 if (sm == SrcModifier::NONE)
749 return;
750 emit(", \"mods\":", sm == SrcModifier::NEG ? "\"n\""
751 : sm == SrcModifier::ABS ? "\"a\""
752 : sm == SrcModifier::NEG_ABS ? "\"na\""
753 : "\"\"");
754 }
755
756 void emitKindField(Operand::Kind k) {
757 emit("\"kind\":");
758 switch (k) {
759 case Operand::Kind::DIRECT:
760 emit("\"RD\"");
761 break;
762 case Operand::Kind::MACRO:
763 emit("\"RM\"");
764 break;
765 case Operand::Kind::INDIRECT:
766 emit("\"RI\"");
767 break;
768 case Operand::Kind::LABEL:
769 emit("\"LB\"");
770 break;
771 case Operand::Kind::IMMEDIATE:
772 emit("\"IM\"");
773 break;
774 default:
775 emitIrError("bad operand kind");
776 }
777 }
778
779 void emitSrcRgn(const Instruction &i, int srcIx) {
780 const Operand &src = i.getSource(srcIx);
781 if (!i.getOpSpec().hasImplicitSrcRegion(srcIx, i.getExecSize(),
782 i.isMacro())) {
783 emitRgnField(i, src.getRegion(), false);
784 }
785 }
786
787 void emitSendSrc(const Instruction &i, int srcIx) {
788 const Operand &src = i.getSource(srcIx);
789 if (srcIx == 0 && i.getSrc0Length() >= 0) {
790 emit("{");
791 emit("\"kind\":\"AD\", ");
792 emitSendSrc0AddressFields(i);
793 const auto di = tryDecode(i, nullptr);
794 if (di) {
795 comments.push_back(di.info.description);
796 emitSendSrc0AddrSurfFields(i, di.info);
797 }
798 emit("}");
799 } else if (srcIx == 1 && i.getSrc1Length() >= 0) {
800 emitSendPayloadSrc(i, 1, "DA");
801 } else {
802 // old send operand (treat as raw direct register access)
803 // this is because we lack a known payload length
804 // so the user is on their own
805 emit("{");
806 emit("\"kind\":\"RD\"");
807 emit(", \"reg\":");
808 emitRegValue(src.getDirRegName(), src.getDirRegRef());
809 // the best we can do is guess it's 1 without decoding the message
810 RegSet rs {model};
811 rs.addSourceOperandInput(i, srcIx);
812 emitSendPayloadDeps(i, rs, src.getDirRegName(), src.getDirRegRef().regNum,
813 1, true);
814 emit("}");
815 }
816 }
817
818 void emitSendSrc0AddressFields(const Instruction &i) {
819 emit("\"areg\":");
820 const auto &src0 = i.getSource(0);
821 if (src0.getKind() == Operand::Kind::DIRECT) {
822 emitRegValue(src0.getDirRegName(), src0.getDirRegRef().regNum);
823 } else if (src0.getKind() == Operand::Kind::INDIRECT) { // indirect send
824 emitRegValue(RegName::ARF_S, src0.getIndAddrReg());
825 } else {
826 emit("\"???\"");
827 }
828 emit(", \"alen\":", i.getSrc0Length());
829 // payload dependencies
830 RegSet rs {model};
831 rs.addSourceOperandInput(i, 0);
832 emitDepInputs("adefs", i, rs);
833 }
834
835 void emitSendSrc0AddrSurfFields(const Instruction &i, const MessageInfo &mi) {
836 if (mi.immediateOffsetBlock2dX || mi.immediateOffsetBlock2dY) {
837 emit(", \"aoff\":[",
838 mi.immediateOffsetBlock2dX, ",", mi.immediateOffsetBlock2dY, "]");
839 } else if (mi.immediateOffset) {
840 emit(", \"aoff\":", mi.immediateOffset);
841 }
842 if (mi.addrScaling != 0 && mi.addrScaling != 1) {
843 emit(", \"ascale\":", mi.addrScaling);
844 }
845
846 emit(", \"stype\":");
847
848 auto emitStateful = [&] (const char *addrType) {
849 emit(addrType);
850 if (mi.surfaceId.isReg()) {
851 emit(", \"soff\":");
852 RegSet surfOffDeps {model};
853 surfOffDeps.setSrcRegion(RegName::ARF_A, mi.surfaceId.reg,
854 Region::SRC110, 2, 16);
855 emitRegValue(RegName::ARF_A, mi.surfaceId.reg);
856 emitDepInputs("sdefs", i, surfOffDeps);
857 } else {
858 emit(", \"soff\":");
859 emitDecimal(mi.surfaceId.imm);
860 }
861 };
862
863 auto emitInd = [&](int which) {
864 if (!i.getOpSpec().isSendgFormat()) {
865 return;
866 }
867 const auto &id =
868 which == 0 ? i.getSendgIndDesc0Reg() : i.getSendgIndDesc1Reg();
869 if (id != REGREF_INVALID) {
870 RegSet surfOffDeps {model};
871 emit(", ", which == 0 ? "\"sbase\"" : "\"sbase2\"",":");
872 emitRegValue(RegName::ARF_S, id);
873 surfOffDeps.setSrcRegion(RegName::ARF_S, id, Region::SRC010, 1, 64);
874 emitDepInputs(which == 0 ? "sdefs" : "sdefs2", i, surfOffDeps);
875 }
876 };
877
878 switch (mi.addrType) {
879 case AddrType::INVALID:
880 emit("\"invalid\"");
881 break;
882 case AddrType::BTI:
883 emitStateful("\"bti\"");
884 break;
885 case AddrType::BSS:
886 emitStateful("\"bss\"");
887 break;
888 case AddrType::SS:
889 emitStateful("\"ss\"");
890 break;
891 case AddrType::FLAT: {
892 emit("\"flat\"");
893 emitInd(0);
894 emitInd(1);
895 break;
896 }
897 case AddrType::SURF: {
898 emit("\"surf\"");
899 emitInd(0);
900 emitInd(1);
901 if (mi.uvrImmediateOffsets[0] ||
902 mi.uvrImmediateOffsets[1] || mi.uvrImmediateOffsets[2])
903 {
904 emit(", \"uvroffs\":[",
905 mi.uvrImmediateOffsets[0], ",",
906 mi.uvrImmediateOffsets[1], ",",
907 mi.uvrImmediateOffsets[2], "]");
908 }
909 break;
910 }
911 default:
912 emitIrError("invalid surface type");
913 }
914 }
915
916 void emitSendPayloadSrc(const Instruction &i, int srcIx,
917 const char *kind = nullptr) {
918 const Operand &src = i.getSource(srcIx);
919 RegName regName = src.getDirRegName();
920 int regCount = srcIx == 0 ? i.getSrc0Length() : i.getSrc1Length();
921 emit("{");
922 if (kind) {
923 emit("\"kind\":\"", kind, "\", ");
924 }
925 emit("\"reg\":");
926 emitRegValue(regName, src.getDirRegRef().regNum);
927 emit(", \"len\":", regCount);
928 RegSet rs {model};
929 rs.addSourceOperandInput(i, srcIx);
930 emitSendPayloadDeps(i, rs, regName, regCount, regCount, true);
931 emit("}");
932 }
933
934 void emitSendDataRegDst(const Instruction &i, RegName dataReg, int regNum,
935 int regLen) {
936 emit("\"kind\":\"DA\"");
937 emitSendPayloadFields(dataReg, regNum, regLen);
938 emitSendPayloadDeps(i, EMPTY_SET, dataReg, regNum, regLen, false);
939 }
940
941 void emitSendPayloadFields(RegName reg, int regNum, int numRegs) {
942 emit(", \"reg\":");
943 emitRegValue(reg, regNum);
944 emit(", \"len\":", numRegs);
945 }
946 void emitSendPayloadDeps(const Instruction &i, const RegSet &regStats,
947 RegName reg, int regNum, int numRegs, bool isRead) {
948 if (isRead) {
949 emitDepInputs(i, regStats);
950 }
951 }
952
953 void emitRgnField(const Instruction &i, Region r, bool dst = false) {
954 if (!dst) {
955 // fix ternary regions
956 if (r.getVt() == Region::Vert::VT_INVALID &&
957 r.getWi() == Region::Width::WI_INVALID) {
958 // ternary src2
959 // officially it was: w = 0 if h is 0 or E; v = w * h
960 // use normalized regions here to simplify
961 // <0> ==> <0;1,0>
962 // <K> ==> <K;1,0>
963 auto hz = r.getHz();
964 // auto es = i.getExecSize();
965 if (hz == Region::Horz::HZ_0) {
966 r = Region::SRC010;
967 } else {
968 r = Region::SRC110;
969 r.set(Region::Vert(hz));
970 }
971 } else if (r.getWi() == Region::Width::WI_INVALID) {
972 // ternary src0/src1
973 // w = 1 when v & h are 0
974 // = v when h = 0
975 // = v/h otherwise
976 auto vt = r.getVt();
977 auto hz = r.getHz();
978 if (vt == Region::Vert::VT_0 && hz == Region::Horz::HZ_0) {
979 r.set(Region::Width::WI_1);
980 } else if (hz == Region::Horz::HZ_0) {
981 r.set(Region::Width(int(vt)));
982 } else {
983 r.set(Region::Width(int(vt) / int(hz)));
984 }
985 }
986 }
987 emitRgnField(r, dst);
988 } // emitRgnField(Instruction)
989
990 void emitRgnField(Region r, bool dst = false) {
991 if (r == Region::INVALID)
992 return;
993 emit(", \"rgn\":");
994 if (dst) {
995 emit("{\"h\":", int(r.getHz()), "}");
996 } else {
997 emit("{");
998 if (r.getVt() != Region::Vert::VT_VxH) {
999 emit("\"v\":", int(r.getVt()),",");
1000 }
1001 emit("\"w\":", int(r.getWi()), ",\"h\":", int(r.getHz()));
1002 emit("}");
1003 }
1004 } // emitRgnField(Region)
1005
1006 void emitTypeField(Type t) {
1007 if (t == Type::INVALID) {
1008 return;
1009 }
1010 emit(", \"type\":\"", ToSyntax(t).substr(1), "\""); // Type::UQ => "uq"
1011 }
1012
1013 void emitRegDist(const SWSB &di) {
1014 if (di.distType == SWSB::DistType::NO_DIST)
1015 return;
1016 emit(", \"regDist\":");
1017 auto emitPipeDist = [&](const char *pfx) {
1018 emit("\"", pfx, "@", (int)di.minDist, "\"");
1019 };
1020 switch (di.distType) {
1021 case SWSB::DistType::REG_DIST:
1022 emitPipeDist("");
1023 break;
1024 case SWSB::DistType::REG_DIST_ALL:
1025 emitPipeDist("A");
1026 break;
1027 case SWSB::DistType::REG_DIST_FLOAT:
1028 emitPipeDist("F");
1029 break;
1030 case SWSB::DistType::REG_DIST_INT:
1031 emitPipeDist("I");
1032 break;
1033 case SWSB::DistType::REG_DIST_LONG:
1034 emitPipeDist("L");
1035 break;
1036 case SWSB::DistType::REG_DIST_MATH:
1037 emitPipeDist("M");
1038 break;
1039 case SWSB::DistType::REG_DIST_SCALAR:
1040 emitPipeDist("S");
1041 break;
1042 default:
1043 emit("\"?\"");
1044 break;
1045 }
1046 }
1047
1048 void emitSbid(const SWSB &di) {
1049 if (di.tokenType == SWSB::TokenType::NOTOKEN)
1050 return;
1051
1052 emit(", \"sbid\":{");
1053 auto emitSwsbEvent = [&](const char *function) {
1054 emit("\"id\":", (int)di.sbid);
1055 emit(", \"func\":\"", function, "\"");
1056 };
1057 switch (di.tokenType) {
1058 case SWSB::TokenType::DST:
1059 emitSwsbEvent(".dst");
1060 break;
1061 case SWSB::TokenType::SRC:
1062 emitSwsbEvent(".src");
1063 break;
1064 case SWSB::TokenType::SET:
1065 emitSwsbEvent("");
1066 break;
1067 default:
1068 emit("\"?\"");
1069 break;
1070 }
1071 emit("}");
1072 }
1073
1074 void emitInstOpts(const Instruction &i) {
1075 static const InstOpt ALL_INST_OPTS[]{
1076 InstOpt::ACCWREN, InstOpt::ATOMIC, InstOpt::BREAKPOINT,
1077 InstOpt::COMPACTED, InstOpt::EOT, InstOpt::NOCOMPACT,
1078 InstOpt::NODDCHK, InstOpt::NODDCLR, InstOpt::NOPREEMPT,
1079 InstOpt::NOSRCDEPSET, InstOpt::SWITCH, InstOpt::SERIALIZE,
1080 InstOpt::EXBSO, InstOpt::CPS,
1081 InstOpt::FWD, // FwdCtrl for dpas
1082 };
1083
1084 InstOptSet ios = i.getInstOpts();
1085 bool first = true;
1086 std::stringstream ss;
1087 auto emitSeparator = [&]() {
1088 if (first)
1089 first = false;
1090 else
1091 ss << ",";
1092 };
1093 for (size_t i = 0;
1094 i < sizeof(ALL_INST_OPTS) / sizeof(ALL_INST_OPTS[0]) && !ios.empty();
1095 i++) {
1096 if (ios.contains(ALL_INST_OPTS[i])) {
1097 emitSeparator();
1098 ios.remove(ALL_INST_OPTS[i]);
1099 ss << "\"" << ToSyntax(ALL_INST_OPTS[i]) << "\"";
1100 }
1101 }
1102
1103 const auto &di = i.getSWSB();
1104 // special token and dist/token won't co-exist in the same swsb
1105 // no need to insert "," after this since there must not be
1106 // dist/token swsb
1107 if (di.hasSpecialToken()) {
1108 IGA_ASSERT(!di.hasDist() && !di.hasToken(), "malformed SWSB IR");
1109 if (di.spToken == SWSB::SpecialToken::NOACCSBSET) {
1110 emitSeparator();
1111 ss << "NoAccSBSet";
1112 }
1113 }
1114 auto s = ss.str();
1115 if (!s.empty())
1116 emit(", \"opts\":[", s ,"]");
1117 }
1118
1119 void emitRegValue(RegName rn, RegRef rr) {
1120 emit("{""\"rn\":\"", ToSyntax(rn), "\"");
1121 if (rr.regNum) {
1122 emit(",\"r\":", rr.regNum);
1123 }
1124 if (rr.subRegNum) {
1125 emit(",\"sr\":", rr.subRegNum);
1126 }
1127 emit("}");
1128 }
1129 void emitRegValue(RegName rn, int regNum, int sr = 0) {
1130 emitRegValue(rn, RegRef((int16_t)regNum, (int16_t)sr));
1131 }
1132
1133 /////////////////////////////////////////////////////////////////////////
1134 // call this for operands that are instruction outputs
1135 bool emitDepOutputs(
1136 const Instruction &i, const RegSet &rs, bool preComm = true)
1137 {
1138 // 'i' is writing 'rs' emit all pairs where this is the
1139 // def and report them as uess
1140 if (opts.liveAnalysis == nullptr) {
1141 return false;
1142 }
1143 const auto &ds = depDefs[i.getID()];
1144 if (ds.empty())
1145 return false;
1146
1147 std::set<int> ids; // make unique and in ascending order
1148 for (const Dep *d : ds) {
1149 if (d->use != nullptr && rs.intersects(d->values)) {
1150 ids.insert(d->use->getID());
1151 }
1152 }
1153
1154 return emitSetIfNonEmpty("uses", ids, preComm);
1155 }
1156
1157 // call this for operands that are instruction inputs
1158 bool emitDepInputs(
1159 const Instruction &i, const RegSet &rs, bool preComm = true)
1160 {
1161 return emitDepInputs("defs", i, rs, preComm);
1162 }
1163 bool emitDepInputs(const char *which,
1164 const Instruction &i, const RegSet &rs, bool preComm = true)
1165 {
1166 // 'i' is writing 'rs' emit all pairs where this is the
1167 // def and report them as uess
1168 if (opts.liveAnalysis == nullptr) {
1169 return false;
1170 }
1171 // the users of 'rs' are all those that use this set
1172 if (rs.empty())
1173 return false;
1174 const auto &c = depUses[i.getID()];
1175 if (c.empty())
1176 return false;
1177
1178 std::set<int> ids; // make unique and in ascending order
1179 for (const Dep *d : c) {
1180 if (d->def != nullptr && rs.intersects(d->values)) {
1181 ids.insert(d->def->getID());
1182 }
1183 }
1184
1185 return emitSetIfNonEmpty(which, ids, preComm);
1186 }
1187
1188 bool emitSetIfNonEmpty(
1189 const char *which, const std::set<int> &ids, bool preComm)
1190 {
1191 if (ids.empty()) // no intersection with this set
1192 return false;
1193 if (preComm)
1194 emit(", ");
1195 emit("\"", which, "\":[");
1196 bool first = true;
1197 for (auto id : ids) {
1198 if (first)
1199 first = false;
1200 else
1201 emit(",");
1202 emit(id);
1203 }
1204 emit("]");
1205 return true;
1206 }
1207 }; // JSONFormatterV2
1208
1209 namespace iga {
1210 void FormatJSON2(std::ostream &o, const FormatOpts &opts, const Kernel &k,
1211 const void *bits);
1212 } // iga::
1213
1214 void iga::FormatJSON2(std::ostream &o, const FormatOpts &opts, const Kernel &k,
1215 const void *bits) {
1216 JSONFormatterV2(o, opts, bits).emitKernel(k);
1217 }
1218
1219 void iga::FormatInstructionJSON2(std::ostream &o, const FormatOpts &opts,
1220 const Instruction &i, const void *bits) {
1221 JSONFormatterV2(o, opts, bits).emitInst(i);
1222 }