1use alloc::{
11 borrow::Cow,
12 format,
13 string::{String, ToString},
14 vec::Vec,
15};
16use core::fmt::{Error as FmtError, Write as _};
17
18use crate::{
19 arena::Handle,
20 valid::{FunctionInfo, ModuleInfo},
21};
22
23#[derive(Clone, Debug, Default)]
25pub struct Options {
26 pub cfg_only: bool,
28}
29
30type NodeId = usize;
32
33#[derive(Default, Clone, Copy)]
35struct Targets {
36 continue_target: Option<usize>,
38 break_target: Option<usize>,
40}
41
42#[derive(Default)]
44struct StatementGraph {
45 nodes: Vec<&'static str>,
47 flow: Vec<(NodeId, NodeId, &'static str)>,
50 jumps: Vec<(NodeId, NodeId, &'static str, usize)>,
54 dependencies: Vec<(NodeId, Handle<crate::Expression>, &'static str)>,
57 emits: Vec<(NodeId, Handle<crate::Expression>)>,
59 calls: Vec<(NodeId, Handle<crate::Function>)>,
61}
62
63impl StatementGraph {
64 fn add(&mut self, block: &[crate::Statement], targets: Targets) -> (NodeId, NodeId) {
66 use crate::Statement as S;
67
68 let root = self.nodes.len();
70 self.nodes.push(if root == 0 { "Root" } else { "Node" });
71 let mut last_node = root;
74 for statement in block {
75 let id = self.nodes.len();
78 self.flow.push((last_node, id, ""));
79 self.nodes.push(""); let mut merge_id = id;
86
87 self.nodes[id] = match *statement {
88 S::Emit(ref range) => {
89 for handle in range.clone() {
90 self.emits.push((id, handle));
91 }
92 "Emit"
93 }
94 S::Kill => "Kill", S::Break => {
96 if let Some(target) = targets.break_target {
99 self.jumps.push((id, target, "Break", 5))
100 } else {
101 self.jumps.push((id, root, "Broken", 7))
102 }
103 "Break"
104 }
105 S::Continue => {
106 if let Some(target) = targets.continue_target {
109 self.jumps.push((id, target, "Continue", 5))
110 } else {
111 self.jumps.push((id, root, "Broken", 7))
112 }
113 "Continue"
114 }
115 S::ControlBarrier(_flags) => "ControlBarrier",
116 S::MemoryBarrier(_flags) => "MemoryBarrier",
117 S::Block(ref b) => {
118 let (other, last) = self.add(b, targets);
119 self.flow.push((id, other, ""));
120 merge_id = last;
123 "Block"
124 }
125 S::If {
126 condition,
127 ref accept,
128 ref reject,
129 } => {
130 self.dependencies.push((id, condition, "condition"));
131 let (accept_id, accept_last) = self.add(accept, targets);
132 self.flow.push((id, accept_id, "accept"));
133 let (reject_id, reject_last) = self.add(reject, targets);
134 self.flow.push((id, reject_id, "reject"));
135
136 merge_id = self.nodes.len();
139 self.nodes.push("Merge");
140 self.flow.push((accept_last, merge_id, ""));
141 self.flow.push((reject_last, merge_id, ""));
142
143 "If"
144 }
145 S::Switch {
146 selector,
147 ref cases,
148 } => {
149 self.dependencies.push((id, selector, "selector"));
150
151 merge_id = self.nodes.len();
154 self.nodes.push("Merge");
155
156 let mut targets = targets;
159 targets.break_target = Some(merge_id);
160
161 for case in cases {
162 let (case_id, case_last) = self.add(&case.body, targets);
163 let label = match case.value {
164 crate::SwitchValue::Default => "default",
165 _ => "case",
166 };
167 self.flow.push((id, case_id, label));
168 self.flow.push((case_last, merge_id, ""));
170 }
171 "Switch"
172 }
173 S::Loop {
174 ref body,
175 ref continuing,
176 break_if,
177 } => {
178 let mut targets = targets;
182 targets.break_target = Some(id);
183
184 let (continuing_id, continuing_last) = self.add(continuing, targets);
185
186 targets.continue_target = Some(continuing_id);
189
190 let (body_id, body_last) = self.add(body, targets);
191
192 self.flow.push((id, body_id, "body"));
193
194 self.flow.push((body_last, continuing_id, "continuing"));
196 self.flow.push((continuing_last, body_id, "continuing"));
199
200 if let Some(expr) = break_if {
201 self.dependencies.push((continuing_id, expr, "break if"));
202 }
203
204 "Loop"
205 }
206 S::Return { value } => {
207 if let Some(expr) = value {
208 self.dependencies.push((id, expr, "value"));
209 }
210 "Return"
211 }
212 S::Store { pointer, value } => {
213 self.dependencies.push((id, value, "value"));
214 self.emits.push((id, pointer));
215 "Store"
216 }
217 S::ImageStore {
218 image,
219 coordinate,
220 array_index,
221 value,
222 } => {
223 self.dependencies.push((id, image, "image"));
224 self.dependencies.push((id, coordinate, "coordinate"));
225 if let Some(expr) = array_index {
226 self.dependencies.push((id, expr, "array_index"));
227 }
228 self.dependencies.push((id, value, "value"));
229 "ImageStore"
230 }
231 S::Call {
232 function,
233 ref arguments,
234 result,
235 } => {
236 for &arg in arguments {
237 self.dependencies.push((id, arg, "arg"));
238 }
239 if let Some(expr) = result {
240 self.emits.push((id, expr));
241 }
242 self.calls.push((id, function));
243 "Call"
244 }
245 S::Atomic {
246 pointer,
247 ref fun,
248 value,
249 result,
250 } => {
251 if let Some(result) = result {
252 self.emits.push((id, result));
253 }
254 self.dependencies.push((id, pointer, "pointer"));
255 self.dependencies.push((id, value, "value"));
256 if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun {
257 self.dependencies.push((id, cmp, "cmp"));
258 }
259 "Atomic"
260 }
261 S::ImageAtomic {
262 image,
263 coordinate,
264 array_index,
265 fun: _,
266 value,
267 } => {
268 self.dependencies.push((id, image, "image"));
269 self.dependencies.push((id, coordinate, "coordinate"));
270 if let Some(expr) = array_index {
271 self.dependencies.push((id, expr, "array_index"));
272 }
273 self.dependencies.push((id, value, "value"));
274 "ImageAtomic"
275 }
276 S::WorkGroupUniformLoad { pointer, result } => {
277 self.emits.push((id, result));
278 self.dependencies.push((id, pointer, "pointer"));
279 "WorkGroupUniformLoad"
280 }
281 S::RayQuery { query, ref fun } => {
282 self.dependencies.push((id, query, "query"));
283 match *fun {
284 crate::RayQueryFunction::Initialize {
285 acceleration_structure,
286 descriptor,
287 } => {
288 self.dependencies.push((
289 id,
290 acceleration_structure,
291 "acceleration_structure",
292 ));
293 self.dependencies.push((id, descriptor, "descriptor"));
294 "RayQueryInitialize"
295 }
296 crate::RayQueryFunction::Proceed { result } => {
297 self.emits.push((id, result));
298 "RayQueryProceed"
299 }
300 crate::RayQueryFunction::GenerateIntersection { hit_t } => {
301 self.dependencies.push((id, hit_t, "hit_t"));
302 "RayQueryGenerateIntersection"
303 }
304 crate::RayQueryFunction::ConfirmIntersection => {
305 "RayQueryConfirmIntersection"
306 }
307 crate::RayQueryFunction::Terminate => "RayQueryTerminate",
308 crate::RayQueryFunction::Begin => "RayQueryVariableUsageBegins",
309 }
310 }
311 S::SubgroupBallot { result, predicate } => {
312 if let Some(predicate) = predicate {
313 self.dependencies.push((id, predicate, "predicate"));
314 }
315 self.emits.push((id, result));
316 "SubgroupBallot"
317 }
318 S::SubgroupCollectiveOperation {
319 op,
320 collective_op,
321 argument,
322 result,
323 } => {
324 self.dependencies.push((id, argument, "arg"));
325 self.emits.push((id, result));
326 match (collective_op, op) {
327 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::All) => {
328 "SubgroupAll"
329 }
330 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Any) => {
331 "SubgroupAny"
332 }
333 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Add) => {
334 "SubgroupAdd"
335 }
336 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Mul) => {
337 "SubgroupMul"
338 }
339 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Max) => {
340 "SubgroupMax"
341 }
342 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Min) => {
343 "SubgroupMin"
344 }
345 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::And) => {
346 "SubgroupAnd"
347 }
348 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Or) => {
349 "SubgroupOr"
350 }
351 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Xor) => {
352 "SubgroupXor"
353 }
354 (
355 crate::CollectiveOperation::ExclusiveScan,
356 crate::SubgroupOperation::Add,
357 ) => "SubgroupExclusiveAdd",
358 (
359 crate::CollectiveOperation::ExclusiveScan,
360 crate::SubgroupOperation::Mul,
361 ) => "SubgroupExclusiveMul",
362 (
363 crate::CollectiveOperation::InclusiveScan,
364 crate::SubgroupOperation::Add,
365 ) => "SubgroupInclusiveAdd",
366 (
367 crate::CollectiveOperation::InclusiveScan,
368 crate::SubgroupOperation::Mul,
369 ) => "SubgroupInclusiveMul",
370 _ => unimplemented!(),
371 }
372 }
373 S::SubgroupGather {
374 mode,
375 argument,
376 result,
377 } => {
378 match mode {
379 crate::GatherMode::BroadcastFirst => {}
380 crate::GatherMode::Broadcast(index)
381 | crate::GatherMode::Shuffle(index)
382 | crate::GatherMode::ShuffleDown(index)
383 | crate::GatherMode::ShuffleUp(index)
384 | crate::GatherMode::ShuffleXor(index)
385 | crate::GatherMode::QuadBroadcast(index) => {
386 self.dependencies.push((id, index, "index"))
387 }
388 crate::GatherMode::QuadSwap(_) => {}
389 }
390 self.dependencies.push((id, argument, "arg"));
391 self.emits.push((id, result));
392 match mode {
393 crate::GatherMode::BroadcastFirst => "SubgroupBroadcastFirst",
394 crate::GatherMode::Broadcast(_) => "SubgroupBroadcast",
395 crate::GatherMode::Shuffle(_) => "SubgroupShuffle",
396 crate::GatherMode::ShuffleDown(_) => "SubgroupShuffleDown",
397 crate::GatherMode::ShuffleUp(_) => "SubgroupShuffleUp",
398 crate::GatherMode::ShuffleXor(_) => "SubgroupShuffleXor",
399 crate::GatherMode::QuadBroadcast(_) => "SubgroupQuadBroadcast",
400 crate::GatherMode::QuadSwap(direction) => match direction {
401 crate::Direction::X => "SubgroupQuadSwapX",
402 crate::Direction::Y => "SubgroupQuadSwapY",
403 crate::Direction::Diagonal => "SubgroupQuadSwapDiagonal",
404 },
405 }
406 }
407 S::SubgroupBallotFindBit {
408 order,
409 argument,
410 result,
411 } => {
412 self.dependencies.push((id, argument, "arg"));
413 self.emits.push((id, result));
414 match order {
415 crate::BallotFindBitOrder::Lsb => "SubgroupBallotFindLSB",
416 crate::BallotFindBitOrder::Msb => "SubgroupBallotFindMSB",
417 }
418 }
419 S::CooperativeStore { target, data } => {
420 self.dependencies.push((id, target, "target"));
421 self.dependencies.push((id, data.pointer, "pointer"));
422 self.dependencies.push((id, data.stride, "stride"));
423 if data.row_major {
424 "CoopStoreT"
425 } else {
426 "CoopStore"
427 }
428 }
429 S::RayPipelineFunction(func) => match func {
430 crate::RayPipelineFunction::TraceRay {
431 acceleration_structure,
432 descriptor,
433 payload,
434 } => {
435 self.dependencies.push((
436 id,
437 acceleration_structure,
438 "acceleration_structure",
439 ));
440 self.dependencies.push((id, descriptor, "descriptor"));
441 self.dependencies.push((id, payload, "payload"));
442 "TraceRay"
443 }
444 crate::RayPipelineFunction::ReorderThread { hint, bits } => {
445 self.dependencies.push((id, hint, "hint"));
446 self.dependencies.push((id, bits, "bits"));
447 "ReorderThread"
448 }
449 },
450 S::HitObject {
451 hit_object,
452 ref fun,
453 } => {
454 self.dependencies.push((id, hit_object, "hit_object"));
455 match *fun {
456 crate::HitObjectFunction::TraceRay {
457 acceleration_structure,
458 descriptor,
459 payload,
460 } => {
461 self.dependencies.push((
462 id,
463 acceleration_structure,
464 "acceleration_structure",
465 ));
466 self.dependencies.push((id, descriptor, "descriptor"));
467 self.dependencies.push((id, payload, "payload"));
468 "HitObjectTraceRay"
469 }
470 crate::HitObjectFunction::RecordMiss { descriptor } => {
471 self.dependencies.push((id, descriptor, "descriptor"));
472 "HitObjectRecordMiss"
473 }
474 crate::HitObjectFunction::RecordFromQuery { query } => {
475 self.dependencies.push((id, query, "query"));
476 "HitObjectRecordFromQuery"
477 }
478 crate::HitObjectFunction::RecordEmpty => "HitObjectRecordEmpty",
479 crate::HitObjectFunction::ExecuteShader { payload } => {
480 self.dependencies.push((id, payload, "payload"));
481 "HitObjectExecuteShader"
482 }
483 crate::HitObjectFunction::Reorder { hint } => {
484 if let Some(crate::ReorderHint { hint, bits }) = hint {
485 self.dependencies.push((id, hint, "hint"));
486 self.dependencies.push((id, bits, "bits"));
487 }
488 "ReorderThreadWithHitObject"
489 }
490 }
491 }
492 S::DebugPrintf {
493 format: _,
494 ref arguments,
495 } => {
496 for &expr in arguments {
497 self.dependencies.push((id, expr, "arg"));
498 }
499 "DebugPrintf"
500 }
501 };
502 last_node = merge_id;
504 }
505 (root, last_node)
506 }
507}
508
509fn name(option: &Option<String>) -> &str {
510 option.as_deref().unwrap_or_default()
511}
512
513const COLORS: &[&str] = &[
515 "white", "#8dd3c7", "#ffffb3", "#bebada", "#fb8072", "#80b1d3", "#fdb462", "#b3de69", "#fccde5",
517 "#d9d9d9",
518];
519
520struct Prefixed<T>(Handle<T>);
521
522impl core::fmt::Display for Prefixed<crate::Expression> {
523 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
524 self.0.write_prefixed(f, "e")
525 }
526}
527
528impl core::fmt::Display for Prefixed<crate::LocalVariable> {
529 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
530 self.0.write_prefixed(f, "l")
531 }
532}
533
534impl core::fmt::Display for Prefixed<crate::GlobalVariable> {
535 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
536 self.0.write_prefixed(f, "g")
537 }
538}
539
540impl core::fmt::Display for Prefixed<crate::Function> {
541 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
542 self.0.write_prefixed(f, "f")
543 }
544}
545
546fn write_fun(
547 output: &mut String,
548 prefix: String,
549 fun: &crate::Function,
550 info: Option<&FunctionInfo>,
551 options: &Options,
552) -> Result<(), FmtError> {
553 writeln!(output, "\t\tnode [ style=filled ]")?;
554
555 if !options.cfg_only {
556 for (handle, var) in fun.local_variables.iter() {
557 writeln!(
558 output,
559 "\t\t{}_{} [ shape=hexagon label=\"{:?} '{}'\" ]",
560 prefix,
561 Prefixed(handle),
562 handle,
563 name(&var.name),
564 )?;
565 }
566
567 write_function_expressions(output, &prefix, fun, info)?;
568 }
569
570 let mut sg = StatementGraph::default();
571 sg.add(&fun.body, Targets::default());
572 for (index, label) in sg.nodes.into_iter().enumerate() {
573 writeln!(
574 output,
575 "\t\t{prefix}_s{index} [ shape=square label=\"{label}\" ]",
576 )?;
577 }
578 for (from, to, label) in sg.flow {
579 writeln!(
580 output,
581 "\t\t{prefix}_s{from} -> {prefix}_s{to} [ arrowhead=tee label=\"{label}\" ]",
582 )?;
583 }
584 for (from, to, label, color_id) in sg.jumps {
585 writeln!(
586 output,
587 "\t\t{}_s{} -> {}_s{} [ arrowhead=tee style=dashed color=\"{}\" label=\"{}\" ]",
588 prefix, from, prefix, to, COLORS[color_id], label,
589 )?;
590 }
591
592 if !options.cfg_only {
593 for (to, expr, label) in sg.dependencies {
594 writeln!(
595 output,
596 "\t\t{}_{} -> {}_s{} [ label=\"{}\" ]",
597 prefix,
598 Prefixed(expr),
599 prefix,
600 to,
601 label,
602 )?;
603 }
604 for (from, to) in sg.emits {
605 writeln!(
606 output,
607 "\t\t{}_s{} -> {}_{} [ style=dotted ]",
608 prefix,
609 from,
610 prefix,
611 Prefixed(to),
612 )?;
613 }
614 }
615
616 assert!(sg.calls.is_empty());
617 for (from, function) in sg.calls {
618 writeln!(
619 output,
620 "\t\t{}_s{} -> {}_s0",
621 prefix,
622 from,
623 Prefixed(function),
624 )?;
625 }
626
627 Ok(())
628}
629
630fn write_function_expressions(
631 output: &mut String,
632 prefix: &str,
633 fun: &crate::Function,
634 info: Option<&FunctionInfo>,
635) -> Result<(), FmtError> {
636 enum Payload<'a> {
637 Arguments(&'a [Handle<crate::Expression>]),
638 Local(Handle<crate::LocalVariable>),
639 Global(Handle<crate::GlobalVariable>),
640 }
641
642 let mut edges = crate::FastHashMap::<&str, _>::default();
643 let mut payload = None;
644 for (handle, expression) in fun.expressions.iter() {
645 use crate::Expression as E;
646 let (label, color_id) = match *expression {
647 E::Literal(_) => ("Literal".into(), 2),
648 E::Constant(_) => ("Constant".into(), 2),
649 E::Override(_) => ("Override".into(), 2),
650 E::ZeroValue(_) => ("ZeroValue".into(), 2),
651 E::Compose { ref components, .. } => {
652 payload = Some(Payload::Arguments(components));
653 ("Compose".into(), 3)
654 }
655 E::Access { base, index } => {
656 edges.insert("base", base);
657 edges.insert("index", index);
658 ("Access".into(), 1)
659 }
660 E::AccessIndex { base, index } => {
661 edges.insert("base", base);
662 (format!("AccessIndex[{index}]").into(), 1)
663 }
664 E::Splat { size, value } => {
665 edges.insert("value", value);
666 (format!("Splat{size:?}").into(), 3)
667 }
668 E::Swizzle {
669 size,
670 vector,
671 pattern,
672 } => {
673 edges.insert("vector", vector);
674 (format!("Swizzle{:?}", &pattern[..size as usize]).into(), 3)
675 }
676 E::FunctionArgument(index) => (format!("Argument[{index}]").into(), 1),
677 E::GlobalVariable(h) => {
678 payload = Some(Payload::Global(h));
679 ("Global".into(), 2)
680 }
681 E::LocalVariable(h) => {
682 payload = Some(Payload::Local(h));
683 ("Local".into(), 1)
684 }
685 E::Load { pointer } => {
686 edges.insert("pointer", pointer);
687 ("Load".into(), 4)
688 }
689 E::ImageSample {
690 image,
691 sampler,
692 gather,
693 coordinate,
694 array_index,
695 offset: _,
696 level,
697 depth_ref,
698 clamp_to_edge: _,
699 } => {
700 edges.insert("image", image);
701 edges.insert("sampler", sampler);
702 edges.insert("coordinate", coordinate);
703 if let Some(expr) = array_index {
704 edges.insert("array_index", expr);
705 }
706 match level {
707 crate::SampleLevel::Auto => {}
708 crate::SampleLevel::Zero => {}
709 crate::SampleLevel::Exact(expr) => {
710 edges.insert("level", expr);
711 }
712 crate::SampleLevel::Bias(expr) => {
713 edges.insert("bias", expr);
714 }
715 crate::SampleLevel::Gradient { x, y } => {
716 edges.insert("grad_x", x);
717 edges.insert("grad_y", y);
718 }
719 }
720 if let Some(expr) = depth_ref {
721 edges.insert("depth_ref", expr);
722 }
723 let string = match gather {
724 Some(component) => Cow::Owned(format!("ImageGather{component:?}")),
725 _ => Cow::Borrowed("ImageSample"),
726 };
727 (string, 5)
728 }
729 E::ImageLoad {
730 image,
731 coordinate,
732 array_index,
733 sample,
734 level,
735 } => {
736 edges.insert("image", image);
737 edges.insert("coordinate", coordinate);
738 if let Some(expr) = array_index {
739 edges.insert("array_index", expr);
740 }
741 if let Some(sample) = sample {
742 edges.insert("sample", sample);
743 }
744 if let Some(level) = level {
745 edges.insert("level", level);
746 }
747 ("ImageLoad".into(), 5)
748 }
749 E::ImageQuery { image, query } => {
750 edges.insert("image", image);
751 let args = match query {
752 crate::ImageQuery::Size { level } => {
753 if let Some(expr) = level {
754 edges.insert("level", expr);
755 }
756 Cow::from("ImageSize")
757 }
758 _ => Cow::Owned(format!("{query:?}")),
759 };
760 (args, 7)
761 }
762 E::Unary { op, expr } => {
763 edges.insert("expr", expr);
764 (format!("{op:?}").into(), 6)
765 }
766 E::Binary { op, left, right } => {
767 edges.insert("left", left);
768 edges.insert("right", right);
769 (format!("{op:?}").into(), 6)
770 }
771 E::Select {
772 condition,
773 accept,
774 reject,
775 } => {
776 edges.insert("condition", condition);
777 edges.insert("accept", accept);
778 edges.insert("reject", reject);
779 ("Select".into(), 3)
780 }
781 E::Derivative { axis, ctrl, expr } => {
782 edges.insert("", expr);
783 (format!("d{axis:?}{ctrl:?}").into(), 8)
784 }
785 E::Relational { fun, argument } => {
786 edges.insert("arg", argument);
787 (format!("{fun:?}").into(), 6)
788 }
789 E::Math {
790 fun,
791 arg,
792 arg1,
793 arg2,
794 arg3,
795 } => {
796 edges.insert("arg", arg);
797 if let Some(expr) = arg1 {
798 edges.insert("arg1", expr);
799 }
800 if let Some(expr) = arg2 {
801 edges.insert("arg2", expr);
802 }
803 if let Some(expr) = arg3 {
804 edges.insert("arg3", expr);
805 }
806 (format!("{fun:?}").into(), 7)
807 }
808 E::As { expr, target } => {
809 edges.insert("", expr);
810 (
811 format!("Convert<{:?},{}>", target.kind, target.width).into(),
812 3,
813 )
814 }
815 E::Bitcast { expr, ty } => {
816 edges.insert("", expr);
817 (format!("Bitcast<{ty:?}>").into(), 3)
818 }
819 E::CallResult(_function) => ("CallResult".into(), 4),
820 E::AtomicResult { .. } => ("AtomicResult".into(), 4),
821 E::WorkGroupUniformLoadResult { .. } => ("WorkGroupUniformLoadResult".into(), 4),
822 E::ArrayLength(expr) => {
823 edges.insert("", expr);
824 ("ArrayLength".into(), 7)
825 }
826 E::RayQueryProceedResult => ("rayQueryProceedResult".into(), 4),
827 E::RayQueryGetIntersection { query, committed } => {
828 edges.insert("", query);
829 let ty = if committed { "Committed" } else { "Candidate" };
830 (format!("rayQueryGet{ty}Intersection").into(), 4)
831 }
832 E::SubgroupBallotResult => ("SubgroupBallotResult".into(), 4),
833 E::SubgroupOperationResult { .. } => ("SubgroupOperationResult".into(), 4),
834 E::RayQueryVertexPositions { query, committed } => {
835 edges.insert("", query);
836 let ty = if committed { "Committed" } else { "Candidate" };
837 (format!("get{ty}HitVertexPositions").into(), 4)
838 }
839 E::HitObjectQuery { hit_object, query } => {
840 edges.insert("", hit_object);
841 let name = match query {
842 crate::HitObjectQuery::IsEmpty => "hitObjectIsEmpty",
843 crate::HitObjectQuery::IsHit => "hitObjectIsHit",
844 crate::HitObjectQuery::IsMiss => "hitObjectIsMiss",
845 crate::HitObjectQuery::Intersection => "hitObjectGetIntersection",
846 };
847 (name.into(), 4)
848 }
849 E::CooperativeLoad { ref data, .. } => {
850 edges.insert("pointer", data.pointer);
851 edges.insert("stride", data.stride);
852 let suffix = if data.row_major { "T " } else { "" };
853 (format!("coopLoad{suffix}").into(), 4)
854 }
855 E::CooperativeMultiplyAdd { a, b, c } => {
856 edges.insert("a", a);
857 edges.insert("b", b);
858 edges.insert("c", c);
859 ("cooperativeMultiplyAdd".into(), 4)
860 }
861 };
862
863 let color_attr = match info {
865 Some(info) if info[handle].uniformity.non_uniform_result.is_none() => "fillcolor",
866 _ => "color",
867 };
868 writeln!(
869 output,
870 "\t\t{}_{} [ {}=\"{}\" label=\"{:?} {}\" ]",
871 prefix,
872 Prefixed(handle),
873 color_attr,
874 COLORS[color_id],
875 handle,
876 label,
877 )?;
878
879 for (key, edge) in edges.drain() {
880 writeln!(
881 output,
882 "\t\t{}_{} -> {}_{} [ label=\"{}\" ]",
883 prefix,
884 Prefixed(edge),
885 prefix,
886 Prefixed(handle),
887 key,
888 )?;
889 }
890 match payload.take() {
891 Some(Payload::Arguments(list)) => {
892 write!(output, "\t\t{{")?;
893 for &comp in list {
894 write!(output, " {}_{}", prefix, Prefixed(comp))?;
895 }
896 writeln!(output, " }} -> {}_{}", prefix, Prefixed(handle))?;
897 }
898 Some(Payload::Local(h)) => {
899 writeln!(
900 output,
901 "\t\t{}_{} -> {}_{}",
902 prefix,
903 Prefixed(h),
904 prefix,
905 Prefixed(handle),
906 )?;
907 }
908 Some(Payload::Global(h)) => {
909 writeln!(
910 output,
911 "\t\t{} -> {}_{} [fillcolor=gray]",
912 Prefixed(h),
913 prefix,
914 Prefixed(handle),
915 )?;
916 }
917 None => {}
918 }
919 }
920
921 Ok(())
922}
923
924pub fn write(
926 module: &crate::Module,
927 mod_info: Option<&ModuleInfo>,
928 options: Options,
929) -> Result<String, FmtError> {
930 use core::fmt::Write as _;
931
932 let mut output = String::new();
933 output += "digraph Module {\n";
934
935 if !options.cfg_only {
936 writeln!(output, "\tsubgraph cluster_globals {{")?;
937 writeln!(output, "\t\tlabel=\"Globals\"")?;
938 for (handle, var) in module.global_variables.iter() {
939 writeln!(
940 output,
941 "\t\t{} [ shape=hexagon label=\"{:?} {:?}/'{}'\" ]",
942 Prefixed(handle),
943 handle,
944 var.space,
945 name(&var.name),
946 )?;
947 }
948 writeln!(output, "\t}}")?;
949 }
950
951 for (handle, fun) in module.functions.iter() {
952 let prefix = Prefixed(handle).to_string();
953 writeln!(output, "\tsubgraph cluster_{prefix} {{")?;
954 writeln!(
955 output,
956 "\t\tlabel=\"Function{:?}/'{}'\"",
957 handle,
958 name(&fun.name)
959 )?;
960 let info = mod_info.map(|a| &a[handle]);
961 write_fun(&mut output, prefix, fun, info, &options)?;
962 writeln!(output, "\t}}")?;
963 }
964 for (ep_index, ep) in module.entry_points.iter().enumerate() {
965 let prefix = format!("ep{ep_index}");
966 writeln!(output, "\tsubgraph cluster_{prefix} {{")?;
967 writeln!(output, "\t\tlabel=\"{:?}/'{}'\"", ep.stage, ep.name)?;
968 let info = mod_info.map(|a| a.get_entry_point(ep_index));
969 write_fun(&mut output, prefix, &ep.function, info, &options)?;
970 writeln!(output, "\t}}")?;
971 }
972
973 output += "}\n";
974 Ok(output)
975}