Generate unique names for IR values. Give names such as 'r5' to temp values in IR which are useful when pretty-printing or generating C. Ensure generated names are unique.
(args: list[Register], blocks: list[BasicBlock])
| 474 | |
| 475 | |
| 476 | def generate_names_for_ir(args: list[Register], blocks: list[BasicBlock]) -> dict[Value, str]: |
| 477 | """Generate unique names for IR values. |
| 478 | |
| 479 | Give names such as 'r5' to temp values in IR which are useful when |
| 480 | pretty-printing or generating C. Ensure generated names are unique. |
| 481 | """ |
| 482 | names: dict[Value, str] = {} |
| 483 | used_names = set() |
| 484 | |
| 485 | temp_index = 0 |
| 486 | |
| 487 | for arg in args: |
| 488 | names[arg] = arg.name |
| 489 | used_names.add(arg.name) |
| 490 | |
| 491 | for block in blocks: |
| 492 | for op in block.ops: |
| 493 | values = [] |
| 494 | |
| 495 | for source in op.sources(): |
| 496 | if source not in names: |
| 497 | values.append(source) |
| 498 | |
| 499 | if isinstance(op, (Assign, AssignMulti)): |
| 500 | values.append(op.dest) |
| 501 | elif isinstance(op, ControlOp) or op.is_void: |
| 502 | continue |
| 503 | elif op not in names: |
| 504 | values.append(op) |
| 505 | |
| 506 | for value in values: |
| 507 | if value in names: |
| 508 | continue |
| 509 | if isinstance(value, Register) and value.name: |
| 510 | name = value.name |
| 511 | elif isinstance(value, (Integer, Float, Undef)): |
| 512 | continue |
| 513 | else: |
| 514 | name = "r%d" % temp_index |
| 515 | temp_index += 1 |
| 516 | |
| 517 | # Append _2, _3, ... if needed to make the name unique. |
| 518 | if name in used_names: |
| 519 | n = 2 |
| 520 | while True: |
| 521 | candidate = "%s_%d" % (name, n) |
| 522 | if candidate not in used_names: |
| 523 | name = candidate |
| 524 | break |
| 525 | n += 1 |
| 526 | |
| 527 | names[value] = name |
| 528 | used_names.add(name) |
| 529 | |
| 530 | return names |
searching dependent graphs…