CountedQueue<LogicType extends Logic> constructor

CountedQueue<LogicType extends Logic>({
  1. required Logic clk,
  2. required Logic reset,
  3. required Logic enqueue,
  4. required CompactedLanes<LogicType> enqueueData,
  5. required Logic dequeue,
  6. required Logic dequeueCount,
  7. required int capacity,
  8. int? almostFullThreshold,
  9. int? almostEmptyThreshold,
  10. CountedQueueBankingTopology? bankingTopology,
  11. Logic? flush,
  12. String name = 'counted_queue',
})

Creates a counted queue driven by enqueue and dequeue actions.

Implementation

CountedQueue({
  required Logic clk,
  required Logic reset,
  required Logic enqueue,
  required CompactedLanes<LogicType> enqueueData,
  required Logic dequeue,
  required Logic dequeueCount,
  required this.capacity,
  int? almostFullThreshold,
  int? almostEmptyThreshold,
  this.bankingTopology,
  Logic? flush,
  super.name = 'counted_queue',
})  : laneCount = enqueueData.laneCount,
      almostFullThreshold = almostFullThreshold ?? capacity,
      almostEmptyThreshold = almostEmptyThreshold ?? 0,
      super(
        definitionName: 'CountedQueue_'
            'L${enqueueData.laneCount}_C${capacity}_'
            'AF${almostFullThreshold ?? capacity}_'
            'AE${almostEmptyThreshold ?? 0}_'
            '${bankingTopology?.identity ?? 'flat'}_'
            'W${enqueueData.lanes.elementWidth}_'
            'D${dequeueCount.width}_${flush == null ? 'NoFlush' : 'Flush'}_'
            '${payloadShapesIdentity([enqueueData])}',
      ) {
  if (capacity < 1) {
    throw ArgumentError.value(capacity, 'capacity', 'Must be positive.');
  }
  if (!rohdPayloadsCompatible(enqueueData.lanes.arrayElements,
      ignoreConstantNames: true)) {
    throw ArgumentError('Routed lane payloads must be compatible.');
  }
  if (dequeueCount.width < enqueueData.countWidth) {
    throw ArgumentError(
        'dequeueCount must represent every offered lane count.');
  }
  if (this.almostFullThreshold < 0 ||
      this.almostFullThreshold > capacity ||
      this.almostEmptyThreshold < 0 ||
      this.almostEmptyThreshold > capacity) {
    throw ArgumentError(
        'Queue thresholds must be between zero and capacity inclusive.');
  }
  if (bankingTopology != null) {
    if (bankingTopology!.capacity != capacity ||
        bankingTopology!.laneCount != laneCount) {
      throw ArgumentError(
          'Banking topology capacity and lane count must match the queue.');
    }
    bankingTopology!.requireCompatible();
  }

  final localClk = addInput('clk', clk);
  final localReset = addInput('reset', reset);
  final localFlush = flush == null ? Const(0) : addInput('flush', flush);
  final localEnqueue = addInput('enqueue', enqueue);
  final localData = addTypedInput('enqueueData', enqueueData);
  final localDequeue = addInput('dequeue', dequeue);
  final localDequeueCount =
      addInput('dequeueCount', dequeueCount, width: dequeueCount.width);
  addOutput('canEnqueue');
  addOutput('headValid');
  head = addTypedPayloadOutput(this, 'head', localData);

  final occupancyWidth = max(1, (capacity + 1).log2Ceil);
  final pointerWidth = max(1, capacity.log2Ceil);
  final arithmeticWidth = [
        occupancyWidth,
        pointerWidth,
        localData.validCount.width,
        localDequeueCount.width,
      ].reduce(max) +
      1;
  addOutput('occupancy', width: occupancyWidth);
  addOutput('availableCount', width: occupancyWidth);
  addOutput('empty');
  addOutput('full');
  addOutput('almostFull');
  addOutput('almostEmpty');
  addOutput('acceptedEnqueueCount', width: localData.validCount.width);
  addOutput('acceptedDequeueCount', width: head.validCount.width);
  addOutput('invalidEnqueueCount');
  addOutput('invalidDequeueCount');

  final readPointer =
      Logic(name: '${name}_read_pointer', width: pointerWidth);
  final writePointer =
      Logic(name: '${name}_write_pointer', width: pointerWidth);
  final offerLocked = Logic(name: '${name}_offer_locked');
  final lockedOfferCount = Logic(
    name: '${name}_locked_offer_count',
    width: head.validCount.width,
  );
  final slots = [
    for (var slot = 0; slot < capacity; slot++)
      localData.lanes.arrayElements.first
          .cloneTyped(name: _slotName(name, slot, bankingTopology)),
  ];
  final current = occupancy.zeroExtend(arithmeticWidth);
  final inputCount = localData.validCount.zeroExtend(arithmeticWidth);
  final requestedDequeue = localDequeueCount.zeroExtend(arithmeticWidth);
  final maximumBundle = min(laneCount, capacity);
  final inputCountValid = inputCount.neq(0) &
      inputCount.lte(Const(maximumBundle, width: arithmeticWidth));
  final offeredWide = mux(
    current.lte(Const(laneCount, width: arithmeticWidth)),
    current,
    Const(laneCount, width: arithmeticWidth),
  );
  final currentOutputCount = offeredWide.getRange(
    0,
    head.validCount.width,
  );
  final outputCount = mux(offerLocked, lockedOfferCount, currentOutputCount);
  final outputCountWide = outputCount.zeroExtend(arithmeticWidth);

  headValid <= occupancy.neq(0) & ~localFlush & ~localReset;
  head.validCount <= outputCount;
  head.consumedMask <=
      [
        for (var lane = 0; lane < laneCount; lane++)
          Const(lane, width: arithmeticWidth).lt(outputCountWide),
      ].reversed.toList(growable: false).concat();
  final visibleLaneData = bankingTopology == null
      ? [
          for (var lane = 0; lane < laneCount; lane++)
            _flatReadLane(
              slots: slots,
              readPointer: readPointer,
              lane: lane,
              capacity: capacity,
            ),
        ]
      : _bankedReadLanes(
          slots: slots,
          readPointer: readPointer,
          laneCount: laneCount,
          topology: bankingTopology!,
        );
  for (var lane = 0; lane < laneCount; lane++) {
    head.lanes.arrayElements[lane] <=
        mux(
          Const(lane, width: arithmeticWidth).lt(outputCountWide),
          visibleLaneData[lane],
          Const(0, width: visibleLaneData[lane].width),
        );
  }

  final outputAccepted =
      (localDequeue & headValid).named('${name}_dequeue_taken');
  final dequeueCountValid =
      requestedDequeue.neq(0) & requestedDequeue.lte(outputCountWide);
  final clampedDequeue = mux(
    requestedDequeue.eq(0),
    Const(1, width: arithmeticWidth),
    mux(
      requestedDequeue.lte(outputCountWide),
      requestedDequeue,
      outputCountWide,
    ),
  );
  final consumedCount = mux(
    outputAccepted,
    clampedDequeue,
    Const(0, width: arithmeticWidth),
  );
  final availableAfterDequeue =
      Const(capacity, width: arithmeticWidth) - current + consumedCount;
  canEnqueue <=
      ~localFlush &
          ~localReset &
          mux(
            inputCountValid,
            inputCount.lte(availableAfterDequeue),
            Const(1),
          );
  final inputAccepted =
      (localEnqueue & canEnqueue).named('${name}_enqueue_taken');
  final enqueuedCount = mux(
    inputAccepted & inputCountValid,
    inputCount,
    Const(0, width: arithmeticWidth),
  );
  final nextOccupancy = current - consumedCount + enqueuedCount;

  acceptedEnqueueCount <=
      enqueuedCount.getRange(
        0,
        acceptedEnqueueCount.width,
      );
  acceptedDequeueCount <=
      consumedCount.getRange(
        0,
        acceptedDequeueCount.width,
      );
  invalidEnqueueCount <= inputAccepted & ~inputCountValid;
  invalidDequeueCount <= outputAccepted & ~dequeueCountValid;
  availableCount <= Const(capacity, width: occupancyWidth) - occupancy;
  empty <= occupancy.eq(0);
  full <= occupancy.eq(capacity);
  almostFull <=
      ~occupancy.lt(Const(this.almostFullThreshold, width: occupancyWidth));
  almostEmpty <=
      occupancy.lte(Const(this.almostEmptyThreshold, width: occupancyWidth));

  final storageReset =
      (localReset | localFlush).named('${name}_storage_reset');
  final bankWriteEnables = <Logic>[];
  final bankWriteRows = <Logic>[];
  final bankWriteData = <Logic>[];
  if (bankingTopology != null) {
    final topology = bankingTopology!;
    final rowWidth = max(
      1,
      [
        for (var bank = 0; bank < topology.bankCount; bank++)
          topology.layout.bankEntryCount(bank),
      ].reduce(max).log2Ceil,
    );
    for (var bank = 0; bank < topology.bankCount; bank++) {
      Logic enable = Const(0);
      Logic row = Const(0, width: rowWidth);
      Logic data = localData.lanes.arrayElements.first;
      for (var base = 0; base < capacity; base++) {
        for (var lane = 0; lane < topology.maximumTransferCount; lane++) {
          final slot = (base + lane) % capacity;
          final coordinate = topology.layout.coordinateOf(slot);
          if (coordinate.bank != bank) {
            continue;
          }
          final selected = inputAccepted &
              inputCountValid &
              Const(lane, width: arithmeticWidth).lt(inputCount) &
              writePointer.eq(base);
          enable = enable | selected;
          row = mux(
            selected,
            Const(coordinate.row, width: rowWidth),
            row,
          );
          data = mux(
            selected,
            localData.lanes.arrayElements[lane],
            data,
          );
        }
      }
      bankWriteEnables.add(enable);
      bankWriteRows.add(row);
      bankWriteData.add(data);
    }
  }
  Sequential(localClk, reset: storageReset, resetValues: {
    occupancy: 0,
    readPointer: 0,
    writePointer: 0,
    offerLocked: 0,
    lockedOfferCount: 0,
    for (final slot in slots) slot: 0,
  }, [
    occupancy < nextOccupancy.getRange(0, occupancyWidth),
    If(~offerLocked & headValid & ~outputAccepted, then: [
      offerLocked < 1,
      lockedOfferCount < currentOutputCount,
    ]),
    If(outputAccepted, then: [
      offerLocked < 0,
    ]),
    readPointer <
        _advancePointer(
          readPointer,
          consumedCount,
          capacity,
          pointerWidth,
        ),
    writePointer <
        _advancePointer(
          writePointer,
          enqueuedCount,
          capacity,
          pointerWidth,
        ),
    if (bankingTopology == null)
      for (var lane = 0; lane < laneCount; lane++)
        for (var slot = 0; slot < capacity; slot++)
          If(
            inputAccepted &
                inputCountValid &
                Const(lane, width: arithmeticWidth).lt(inputCount) &
                _laneTargetsSlot(
                  pointer: writePointer,
                  lane: lane,
                  slot: slot,
                  capacity: capacity,
                ),
            then: [
              slots[slot] < localData.lanes.arrayElements[lane],
            ],
          )
    else
      for (var bank = 0; bank < bankingTopology!.bankCount; bank++)
        for (final slot in bankingTopology!.layout.indicesInBank(bank))
          If(
            bankWriteEnables[bank] &
                bankWriteRows[bank]
                    .eq(bankingTopology!.layout.coordinateOf(slot).row),
            then: [
              slots[slot] < bankWriteData[bank],
            ],
          ),
  ]);
}