MultiIssueQueue<OperationType extends Logic, OperandType extends Logic> constructor

MultiIssueQueue<OperationType extends Logic, OperandType extends Logic>({
  1. required Logic clk,
  2. required Logic reset,
  3. required Logic quiesce,
  4. required Logic dispatch,
  5. required CompactedLanes<ReservationStationEntry<OperationType, OperandType>> dispatchData,
  6. required List<Logic> wakeups,
  7. required List<WakeupEvent<OperandType>> wakeupData,
  8. required Logic invalidate,
  9. required Logic invalidationTag,
  10. required Logic cancel,
  11. required Logic cancelTag,
  12. required Logic cancelSlots,
  13. required Logic cancellationMask,
  14. required List<Logic> structuralReady,
  15. required List<Logic> issues,
  16. required int capacity,
  17. IssueAgeTrackingPolicy ageTrackingPolicy = IssueAgeTrackingPolicy.matrix,
  18. bool cancelSuppressesIssue = false,
  19. IssueSelectionGenerator? selectionGenerator,
  20. String? selectionName,
  21. RegisterFileFunctor? storageImplementation,
  22. String name = 'multi_issue_queue',
})

Creates an ordered multi-dispatch reservation station driven by actions.

wakeups and wakeupData hold one action and one payload per wakeup lane. issues and structuralReady hold one action and one per-slot readiness vector per issue lane. A custom selectionGenerator requires a distinct selectionName for the generated definition.

Implementation

MultiIssueQueue(
    {required Logic clk,
    required Logic reset,
    required Logic quiesce,
    required Logic dispatch,
    required CompactedLanes<
            ReservationStationEntry<OperationType, OperandType>>
        dispatchData,
    required List<Logic> wakeups,
    required List<WakeupEvent<OperandType>> wakeupData,
    required Logic invalidate,
    required Logic invalidationTag,
    required Logic cancel,
    required Logic cancelTag,
    required Logic cancelSlots,
    required Logic cancellationMask,
    required List<Logic> structuralReady,
    required List<Logic> issues,
    required this.capacity,
    this.ageTrackingPolicy = IssueAgeTrackingPolicy.matrix,
    this.cancelSuppressesIssue = false,
    IssueSelectionGenerator? selectionGenerator,
    String? selectionName,
    RegisterFileFunctor? storageImplementation,
    super.name = 'multi_issue_queue'})
    : dispatchLaneCount = dispatchData.laneCount,
      issueLaneCount = issues.length,
      operandCount = dispatchData.lanes.arrayElements.first.operandCount,
      wakeupLaneCount = wakeups.length,
      super(
          definitionName: _multiIssueQueueDefinitionName(
              capacity,
              dispatchData,
              issues.length,
              wakeups.length,
              resolveSelectionName(
                  ageTrackingPolicy, selectionGenerator, selectionName),
              ageTrackingPolicy,
              cancelSuppressesIssue,
              storageImplementation,
              wakeupData)) {
  final effectiveSelectionGenerator =
      selectionGenerator ?? _defaultSelection(ageTrackingPolicy);
  if (capacity < 1 || dispatchLaneCount < 1 || issueLaneCount < 1) {
    throw ArgumentError(
        'Capacity and dispatch and issue lane counts must be positive.');
  }
  if (wakeupLaneCount < 1) {
    throw ArgumentError.value(
        wakeups, 'wakeups', 'Must contain at least one wakeup lane.');
  }
  if (wakeupData.length != wakeupLaneCount) {
    throw ArgumentError.value(
        wakeupData, 'wakeupData', 'Must contain one payload per wakeup.');
  }
  if (structuralReady.length != issueLaneCount ||
      structuralReady.any((ready) => ready.width != capacity)) {
    throw ArgumentError(
        'Each issue lane needs one structural-ready bit per slot.');
  }
  if (cancellationMask.width != capacity) {
    throw ArgumentError(
        'The cancellation mask must contain one bit per slot.');
  }
  final dispatchEntry = dispatchData.lanes.arrayElements.first;
  final tagWidth = dispatchEntry.tagWidth;
  if (dispatchData.lanes.arrayElements.any((entry) =>
      entry.operandCount != operandCount ||
      entry.tagWidth != tagWidth ||
      entry.ageWidth != dispatchEntry.ageWidth ||
      entry.operation.width != dispatchEntry.operation.width ||
      entry.width != dispatchEntry.width)) {
    throw ArgumentError('Dispatch lane entry configurations must match.');
  }
  if (!rohdPayloadsCompatible(
      dispatchData.lanes.arrayElements.map((entry) => entry.operation),
      ignoreConstantNames: true)) {
    throw ArgumentError('Dispatch lane operations must be compatible.');
  }
  if (cancelTag.width != tagWidth || invalidationTag.width != tagWidth) {
    throw ArgumentError(
        'Cancellation, invalidation, and entry tag widths must match.');
  }
  if (wakeupData.any((event) => event.tagWidth != tagWidth)) {
    throw ArgumentError(
        'Wakeup tag and operand data widths must match each entry.');
  }
  for (var index = 0; index < operandCount; index++) {
    if (!rohdPayloadsCompatible([
      for (final entry in dispatchData.lanes.arrayElements)
        entry.operands[index].data,
      ...wakeupData.map((event) => event.data),
    ], ignoreConstantNames: true)) {
      throw ArgumentError('Operand and wakeup payloads must be compatible.');
    }
  }

  final localClk = addInput('clk', clk);
  final localReset = addInput('reset', reset);
  final localQuiesce = addInput('quiesce', quiesce);
  final localDispatch = addInput('dispatch', dispatch);
  final localDispatchData = addTypedInput('dispatchData', dispatchData);
  final localWakeups = [
    for (var lane = 0; lane < wakeupLaneCount; lane++)
      addInput('wakeup$lane', wakeups[lane])
  ];
  final localWakeupData = [
    for (var lane = 0; lane < wakeupLaneCount; lane++)
      addTypedInput('wakeupData$lane', wakeupData[lane])
  ];
  final localInvalidate = addInput('invalidate', invalidate);
  final localInvalidationTag =
      addInput('invalidationTag', invalidationTag, width: tagWidth);
  final localCancel = addInput('cancel', cancel);
  final localCancelTag = addInput('cancelTag', cancelTag, width: tagWidth);
  final localCancelSlots = addInput('cancelSlots', cancelSlots);
  final localCancellationMask =
      addInput('cancellationMask', cancellationMask, width: capacity);
  final localStructuralReady = [
    for (var lane = 0; lane < issueLaneCount; lane++)
      addInput('structuralReady$lane', structuralReady[lane], width: capacity)
  ];
  final localIssues = [
    for (var lane = 0; lane < issueLaneCount; lane++)
      addInput('issue$lane', issues[lane])
  ];

  addOutput('canDispatch');
  issueValid = [
    for (var lane = 0; lane < issueLaneCount; lane++)
      addOutput('issueValid$lane')
  ];
  issueEntries = [
    for (var lane = 0; lane < issueLaneCount; lane++)
      addTypedPayloadOutput(this, 'issueEntry$lane', dispatchEntry)
  ];
  entries = [
    for (var slot = 0; slot < capacity; slot++)
      addTypedPayloadOutput(this, 'entry$slot', dispatchEntry)
  ];
  addOutput('occupiedEntries', width: capacity);
  eligibleEntries = [
    for (var lane = 0; lane < issueLaneCount; lane++)
      addOutput('eligibleEntries$lane', width: capacity)
  ];
  issueSelections = [
    for (var lane = 0; lane < issueLaneCount; lane++)
      addOutput('issueSelection$lane', width: capacity)
  ];
  dispatchSelections = [
    for (var lane = 0; lane < dispatchLaneCount; lane++)
      addOutput('dispatchSelection$lane', width: capacity)
  ];
  final occupancyWidth = max(1, (capacity + 1).log2Ceil);
  addOutput('occupancy', width: occupancyWidth);
  addOutput('empty');
  addOutput('full');
  addOutput('duplicateDispatchTags', width: dispatchLaneCount);
  addOutput('cancelMiss');
  addOutput('multipleCancelMatches');
  addOutput('invalidCancellationMask', width: capacity);
  addOutput('multipleMatchingWakeups');
  addOutput('multipleIssueSelections', width: issueLaneCount);
  addOutput('invalidDispatchCount');

  // dependencyTransition observes its events as always-ready channels.
  final wakeupEvents = [
    for (var lane = 0; lane < wakeupLaneCount; lane++)
      ReadyAndValidInterface(
          localWakeupData[lane].cloneTyped(name: '${name}_wakeup_$lane'))
  ];
  for (var lane = 0; lane < wakeupLaneCount; lane++) {
    wakeupEvents[lane].valid <= localWakeups[lane];
    wakeupEvents[lane].ready <= Const(1);
    wakeupEvents[lane].data <= localWakeupData[lane];
  }
  final invalidationEvent = ReadyAndValidInterface(
      WakeupInvalidation(tagWidth: tagWidth, name: '${name}_invalidation'));
  invalidationEvent.valid <= localInvalidate;
  invalidationEvent.ready <= Const(1);
  invalidationEvent.data.tag <= localInvalidationTag;

  final occupied = [
    for (var slot = 0; slot < capacity; slot++)
      Logic(name: '${name}_occupied_$slot')
  ];
  final cancelMatches = [
    for (var slot = 0; slot < capacity; slot++)
      (occupied[slot] &
              entries[slot].destinationValid &
              entries[slot].destinationTag.eq(localCancelTag))
          .named('${name}_cancel_matches_$slot')
  ];
  final anyCancelMatch =
      cancelMatches.rconcat().or().named('${name}_any_cancel_match');
  Logic seenCancelMatch = Const(0);
  Logic multipleCancelMatch = Const(0);
  for (var slot = 0; slot < capacity; slot++) {
    multipleCancelMatch =
        (multipleCancelMatch | (seenCancelMatch & cancelMatches[slot]))
            .named('${name}_multiple_cancel_through_$slot');
    seenCancelMatch = (seenCancelMatch | cancelMatches[slot])
        .named('${name}_seen_cancel_through_$slot');
  }
  final canceledSlots = [
    for (var slot = 0; slot < capacity; slot++)
      ((localCancel & cancelMatches[slot]) |
              (localCancelSlots &
                  localCancellationMask[slot] &
                  occupied[slot]))
          .named('${name}_canceled_slot_$slot')
  ];

  List<ReadyAndValidInterface<Logic>>? ageAllocations;
  ReadyAndValidInterface<Logic>? ageReleaseMask;
  late final Logic olderThan;
  if (ageTrackingPolicy == IssueAgeTrackingPolicy.matrix) {
    ageAllocations = [
      for (var lane = 0; lane < dispatchLaneCount; lane++)
        ReadyAndValidInterface(Logic(
            name: '${name}_age_allocation_$lane',
            width: max(1, capacity.log2Ceil)))
    ];
    ageReleaseMask = ReadyAndValidInterface(
        Logic(name: '${name}_age_release_mask', width: capacity));
    final ageTracker = MultiAgeMatrixTracker(
        clk: localClk,
        reset: localReset,
        allocations: ageAllocations,
        releaseMask: ageReleaseMask,
        entryCount: capacity,
        storageImplementation: storageImplementation,
        name: '${name}_age');
    olderThan = ageTracker.olderThan;
  } else {
    if (dispatchEntry.ageWidth < 2 ||
        capacity >= (1 << (dispatchEntry.ageWidth - 1))) {
      throw ArgumentError(
          'Wrapping age width must place capacity in less than half the '
          'encoded age space.');
    }
    olderThan = Const(0, width: capacity * capacity);
  }

  final operandsReady = [
    for (var slot = 0; slot < capacity; slot++)
      (operandCount == 0
              ? Const(1)
              : entries[slot]
                  .operands
                  .map((operand) => operand.ready)
                  .reduce((left, right) => left & right))
          .named('${name}_operands_ready_$slot')
  ];
  var unavailableForIssue = cancelSuppressesIssue
      ? mux(localCancel, Const(-1, width: capacity), canceledSlots.rconcat())
      : canceledSlots.rconcat();
  final multipleSelections = <Logic>[];
  final issuedByLane = <List<Logic>>[];
  for (var lane = 0; lane < issueLaneCount; lane++) {
    final laneEligible = [
      for (var slot = 0; slot < capacity; slot++)
        (occupied[slot] &
                operandsReady[slot] &
                localStructuralReady[lane][slot] &
                ~localQuiesce &
                ~unavailableForIssue[slot])
            .named('${name}_issue_${lane}_eligible_$slot')
    ];
    final eligibleVector = laneEligible.rconcat();
    eligibleEntries[lane] <= eligibleVector;
    final generated = effectiveSelectionGenerator(
        eligible: eligibleVector,
        olderThan: olderThan,
        ages: entries.map((entry) => entry.age).toList(growable: false),
        name: '${name}_issue_$lane');
    if (generated.width != capacity) {
      throw ArgumentError.value(
          effectiveSelectionGenerator,
          'selectionGenerator',
          'Must return one selection bit per queue entry.');
    }
    Logic found = Const(0);
    Logic multiple = Const(0);
    final normalized = <Logic>[];
    for (var slot = 0; slot < capacity; slot++) {
      final selected = generated[slot] & ~found;
      normalized.add(selected);
      multiple = (multiple | (found & generated[slot]))
          .named('${name}_issue_${lane}_multiple_through_$slot');
      found = (found | generated[slot])
          .named('${name}_issue_${lane}_found_through_$slot');
    }
    final selection = normalized.rconcat();
    issueSelections[lane] <= selection;
    multipleSelections.add(multiple);
    unavailableForIssue = (unavailableForIssue | selection)
        .named('${name}_unavailable_after_issue_lane_$lane');

    Logic selectedEntry = entries.last;
    for (var slot = capacity - 2; slot >= 0; slot--) {
      selectedEntry = mux(selection[slot], entries[slot], selectedEntry)
          .named('${name}_issue_${lane}_selected_entry_$slot');
    }
    issueValid[lane] <= selection.or();
    issueEntries[lane] <= selectedEntry;
    final issueTaken = (localIssues[lane] & issueValid[lane])
        .named('${name}_issue_${lane}_taken');
    issuedByLane.add([
      for (var slot = 0; slot < capacity; slot++)
        (issueTaken & selection[slot])
            .named('${name}_issue_${lane}_accepted_slot_$slot')
    ]);
  }

  final issuedSlots = [
    for (var slot = 0; slot < capacity; slot++)
      issuedByLane
          .map((lane) => lane[slot])
          .fold<Logic>(Const(0), (issued, bit) => issued | bit)
          .named('${name}_issued_slot_$slot')
  ];
  final releasedSlots = [
    for (var slot = 0; slot < capacity; slot++)
      (issuedSlots[slot] | canceledSlots[slot])
          .named('${name}_released_slot_$slot')
  ];
  var availableForDispatch = [
    for (var slot = 0; slot < capacity; slot++)
      (~occupied[slot] | releasedSlots[slot])
          .named('${name}_available_slot_$slot')
  ];
  final offeredCount = localDispatchData.validCount;
  final dispatchLaneValid = [
    for (var lane = 0; lane < dispatchLaneCount; lane++)
      offeredCount.gt(Const(lane, width: offeredCount.width))
  ];
  final selectedDispatchSlots = <List<Logic>>[];
  final dispatchLaneHasSlot = <Logic>[];
  for (var lane = 0; lane < dispatchLaneCount; lane++) {
    Logic found = Const(0);
    final selections = <Logic>[];
    for (var slot = 0; slot < capacity; slot++) {
      final selected =
          dispatchLaneValid[lane] & availableForDispatch[slot] & ~found;
      selections.add(selected);
      found = (found | availableForDispatch[slot])
          .named('${name}_dispatch_${lane}_found_through_$slot');
    }
    selectedDispatchSlots.add(selections);
    final selection = selections.rconcat();
    dispatchSelections[lane] <= selection;
    dispatchLaneHasSlot.add(~dispatchLaneValid[lane] | selection.or());
    availableForDispatch = [
      for (var slot = 0; slot < capacity; slot++)
        (availableForDispatch[slot] & ~selections[slot])
            .named('${name}_available_${slot}_after_dispatch_$lane')
    ];
  }

  final dispatchEntries = localDispatchData.lanes.arrayElements;
  final duplicateDispatch = <Logic>[];
  for (var lane = 0; lane < dispatchLaneCount; lane++) {
    Logic duplicate = Const(0);
    for (var slot = 0; slot < capacity; slot++) {
      duplicate = duplicate |
          (dispatchEntries[lane].destinationValid &
              occupied[slot] &
              ~releasedSlots[slot] &
              entries[slot].destinationValid &
              entries[slot]
                  .destinationTag
                  .eq(dispatchEntries[lane].destinationTag));
    }
    for (var earlier = 0; earlier < lane; earlier++) {
      duplicate = duplicate |
          (dispatchLaneValid[earlier] &
              dispatchEntries[earlier].destinationValid &
              dispatchEntries[lane].destinationValid &
              dispatchEntries[earlier]
                  .destinationTag
                  .eq(dispatchEntries[lane].destinationTag));
    }
    duplicateDispatch.add((dispatchLaneValid[lane] & duplicate)
        .named('${name}_duplicate_dispatch_tag_$lane'));
  }
  final duplicateVector = duplicateDispatch.rconcat();
  final canceledIncoming = [
    for (var lane = 0; lane < dispatchLaneCount; lane++)
      dispatchLaneValid[lane] &
          dispatchEntries[lane].destinationValid &
          localCancel &
          dispatchEntries[lane].destinationTag.eq(localCancelTag)
  ].rconcat();
  final slotsAvailable =
      dispatchLaneHasSlot.reduce((left, right) => left & right);
  final dispatchCountValid =
      offeredCount.lte(Const(dispatchLaneCount, width: offeredCount.width));
  canDispatch <=
      slotsAvailable &
          ~duplicateVector.or() &
          ~canceledIncoming.or() &
          dispatchCountValid &
          ~localQuiesce;
  final dispatchTaken =
      (canDispatch & localDispatch).named('${name}_dispatch_taken');
  final dispatchedSlots = [
    for (var lane = 0; lane < dispatchLaneCount; lane++)
      [
        for (var slot = 0; slot < capacity; slot++)
          (dispatchTaken & selectedDispatchSlots[lane][slot])
              .named('${name}_dispatch_${lane}_accepted_slot_$slot')
      ]
  ];

  if (ageTrackingPolicy == IssueAgeTrackingPolicy.matrix) {
    for (var lane = 0; lane < dispatchLaneCount; lane++) {
      ageAllocations![lane].valid <= dispatchTaken & dispatchLaneValid[lane];
      Logic slotIndex = Const(0, width: ageAllocations[lane].data.width);
      for (var slot = capacity - 1; slot >= 0; slot--) {
        slotIndex = mux(selectedDispatchSlots[lane][slot],
            Const(slot, width: slotIndex.width), slotIndex);
      }
      ageAllocations[lane].data <= slotIndex;
    }
    ageReleaseMask!.valid <= releasedSlots.rconcat().or();
    ageReleaseMask.data <= releasedSlots.rconcat();
  }

  occupiedEntries <= occupied.rconcat();
  final occupiedSum = occupied
      .map((bit) => bit.zeroExtend(occupancyWidth))
      .reduce((left, right) => left + right)
      .named('${name}_occupancy_sum');
  occupancy <= occupiedSum;
  empty <= occupiedSum.eq(0);
  full <= occupied.rconcat().and() & ~releasedSlots.rconcat().or();
  duplicateDispatchTags <= duplicateVector;
  cancelMiss <= localCancel & ~anyCancelMatch;
  multipleCancelMatches <= localCancel & multipleCancelMatch;
  invalidCancellationMask <=
      mux(localCancelSlots, localCancellationMask & ~occupied.rconcat(),
          Const(0, width: capacity));
  multipleIssueSelections <= multipleSelections.rconcat();
  invalidDispatchCount <= localDispatch & ~dispatchCountValid;

  final wakeupCollisions = <Logic>[];
  final sequentialActions = <Conditional>[];
  final entryActions = <Conditional>[];
  final nextEntries = storageImplementation == null
      ? entries
      : [
          for (var slot = 0; slot < capacity; slot++)
            dispatchEntry.cloneTyped(name: '${name}_next_entry_$slot')
        ];
  for (var slot = 0; slot < capacity; slot++) {
    final slotDispatched = dispatchedSlots
        .map((lane) => lane[slot])
        .fold<Logic>(Const(0), (selected, bit) => selected | bit);
    final slotActions = <Iff>[];
    final entrySlotActions = <Iff>[];
    for (var lane = 0; lane < dispatchLaneCount; lane++) {
      slotActions.add(Iff(dispatchedSlots[lane][slot], [
        occupied[slot] < 1,
        if (storageImplementation == null) ...[
          entries[slot].operation < dispatchEntries[lane].operation,
          entries[slot].destinationTag < dispatchEntries[lane].destinationTag,
          entries[slot].destinationValid <
              dispatchEntries[lane].destinationValid,
          entries[slot].age < dispatchEntries[lane].age,
        ],
      ]));
      if (storageImplementation != null) {
        entrySlotActions.add(Iff(dispatchedSlots[lane][slot], [
          nextEntries[slot].operation < dispatchEntries[lane].operation,
          nextEntries[slot].destinationTag <
              dispatchEntries[lane].destinationTag,
          nextEntries[slot].destinationValid <
              dispatchEntries[lane].destinationValid,
          nextEntries[slot].age < dispatchEntries[lane].age
        ]));
      }
    }
    slotActions
      ..add(ElseIf(releasedSlots[slot], [occupied[slot] < 0]))
      ..add(Else([]));
    sequentialActions.add(If.block(slotActions));
    if (storageImplementation != null) {
      entrySlotActions
        ..add(ElseIf(releasedSlots[slot], []))
        ..add(Else([]));
      entryActions.add(If.block(entrySlotActions));
    }

    for (var operandIndex = 0; operandIndex < operandCount; operandIndex++) {
      final storedOperand = entries[slot].operands[operandIndex];
      Logic incomingBits = dispatchEntries.last.operands[operandIndex];
      for (var lane = dispatchLaneCount - 1; lane >= 0; lane--) {
        incomingBits = mux(dispatchedSlots[lane][slot],
            dispatchEntries[lane].operands[operandIndex], incomingBits);
      }
      final incomingName = '${name}_${slot}_${operandIndex}_incoming';
      final incoming = storedOperand.cloneTyped(name: incomingName)
        ..gets(incomingBits);
      final transition = dependencyTransition(
          stored: storedOperand,
          incoming: incoming,
          loadAccepted: slotDispatched,
          updateEnabled: (occupied[slot] | slotDispatched) &
              (~releasedSlots[slot] | slotDispatched),
          wakeups: wakeupEvents,
          invalidation: invalidationEvent,
          name: '${name}_${slot}_$operandIndex');
      wakeupCollisions.add(transition.multipleMatchingWakeups);
      final action =
          nextEntries[slot].operands[operandIndex] < transition.next;
      if (storageImplementation == null) {
        sequentialActions.add(action);
      } else {
        entryActions.add(action);
      }
    }
  }
  multipleMatchingWakeups <=
      (wakeupCollisions.isEmpty ? Const(0) : wakeupCollisions.rconcat().or());

  Sequential(localClk, reset: localReset, resetValues: {
    for (final bit in occupied) bit: 0,
    if (storageImplementation == null)
      for (final entry in entries)
        for (final element in entry.elements) element: 0
  }, [
    ...sequentialActions,
    if (storageImplementation == null) ...entryActions,
  ]);
  if (storageImplementation != null) {
    Combinational([
      for (var slot = 0; slot < capacity; slot++)
        nextEntries[slot] < entries[slot],
      ...entryActions,
    ]);
    connectRegisterFileBank(
      clk: localClk,
      reset: localReset,
      current: entries,
      next: nextEntries,
      resetValues: List.filled(
          capacity, LogicValue.filled(dispatchEntry.width, LogicValue.zero)),
      implementation: storageImplementation,
      name: '${name}_storage',
    );
  }
}