1 package net.mograsim.logic.core.wires;
3 import static net.mograsim.logic.core.types.Bit.U;
4 import static net.mograsim.logic.core.types.Bit.Z;
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.HashSet;
12 import net.mograsim.logic.core.LogicObservable;
13 import net.mograsim.logic.core.LogicObserver;
14 import net.mograsim.logic.core.timeline.Timeline;
15 import net.mograsim.logic.core.types.Bit;
16 import net.mograsim.logic.core.types.BitVector;
17 import net.mograsim.logic.core.types.BitVector.BitVectorMutator;
20 * Represents an array of wires that can store n bits of information.
22 * @author Fabian Stemmler
27 public final String name;
28 private BitVector cachedValues;
29 public final int travelTime;
30 private List<ReadEnd> attached = new ArrayList<>();
31 public final int width;
32 List<ReadWriteEnd> inputs = new ArrayList<>();
34 private Bit[] bitsWithoutFusions;
37 public CoreWire(Timeline timeline, int width, int travelTime)
39 this(timeline, width, travelTime, null);
42 public CoreWire(Timeline timeline, int width, int travelTime, String name)
45 throw new IllegalArgumentException(
46 String.format("Tried to create an array of wires with width %d, but a width of less than 1 makes no sense.", width));
48 this.timeline = timeline;
50 this.travelTime = travelTime;
54 private void initValues()
56 cachedValues = U.toVector(width);
57 bitsWithoutFusions = cachedValues.getBits();
60 private void setNewValues(BitVector newValues)
62 cachedValues = newValues;
66 private void invalidateCachedValuesForAllFusedWires()
68 invalidateCachedValues();
69 if (fusedBits != null)
70 for (FusedBit fusion : fusedBits)
72 fusion.invalidateCachedValuesForAllParticipatingWires();
75 private void invalidateCachedValues()
81 void recalculateValuesWithoutFusions()
83 Bit[] bits = new Bit[width];
88 System.arraycopy(inputs.get(0).getInputValues().getBits(), 0, bits, 0, width);
89 for (int i = 1; i < inputs.size(); i++)
90 Bit.join(bits, inputs.get(i).getInputValues().getBits());
92 bitsWithoutFusions = bits;
93 if (fusedBits == null)
94 setNewValues(BitVector.of(bits));
96 invalidateCachedValuesForAllFusedWires();
99 private void recalculatedCachedValues()
102 if (fusedBits == null)
103 bits = bitsWithoutFusions;
106 bits = new Bit[width];
107 for (int i = 0; i < width; i++)
109 FusedBit fusion = fusedBits[i];
111 bits[i] = bitsWithoutFusions[i];
113 bits[i] = fusion.getValue();
116 cachedValues = BitVector.of(bits);
120 * Forces a Wire to take on specific values. If the new values differ from the old ones, the observers of the Wire will be notified.
121 * WARNING! Use this with care! The preferred way of writing the values is ReadWriteEnd.feedSignals(BitVector)
123 * @param values The values the <code>Wire</code> will have immediately after this method is called
125 public void forceValues(BitVector values)
127 setNewValues(values);
131 * The {@link CoreWire} is interpreted as an unsigned integer with n bits.
133 * @return <code>true</code> if all bits are either <code>Bit.ONE</code> or <code>Bit.ZERO</code> (they do not all have to have the same
134 * value), not <code>Bit.U</code>, <code>Bit.X</code> or <code>Bit.Z</code>. <code>false</code> is returned otherwise.
136 * @author Fabian Stemmler
138 public boolean hasNumericValue()
140 return getValues().isBinary();
144 * The {@link CoreWire} is interpreted as an unsigned integer with n bits.
146 * @return The unsigned value of the {@link CoreWire}'s bits, where value 0 corresponds with 2^0, value 1 is 2^1 and so on.
148 * @author Fabian Stemmler
150 public long getUnsignedValue()
154 for (Bit bit : getValues())
161 return 0; // TODO: Proper handling for getUnsignedValue(), if not all bits are 1 or 0;
173 * The {@link CoreWire} is interpreted as a signed integer with n bits.
175 * @return The signed value of the {@link CoreWire}'s bits, where value 0 corresponds with 2^0, value 1 is 2^1 and so on.
177 * @author Fabian Stemmler
179 public long getSignedValue()
181 long val = getUnsignedValue();
182 long mask = 1 << (width - 1);
183 if ((mask & val) != 0)
185 int shifts = 64 - width;
186 return (val << shifts) >> shifts;
192 * Returns the least significant bit (LSB)
194 public Bit getValue()
200 * Returns the least significant bit (LSB) of the given index
202 public Bit getValue(int index)
204 return getValues().getLSBit(index);
207 public BitVector getValues(int start, int end)
209 return getValues().subVector(start, end);
212 public BitVector getValues()
214 if (cachedValues == null)
215 recalculatedCachedValues();
220 * Adds an {@link LogicObserver}, who will be notified when the value of the {@link CoreWire} is updated.
222 * @param ob The {@link LogicObserver} to be notified of changes.
223 * @return true if the given {@link LogicObserver} was not already registered, false otherwise
225 * @author Fabian Stemmler
227 boolean attachEnd(ReadEnd end)
229 return attached.add(end);
232 void detachEnd(ReadEnd end)
234 attached.remove(end);
237 private void notifyObservers()
239 attached.forEach(ReadEnd::update);
243 * Create and register a {@link ReadWriteEnd} object, which is tied to this {@link CoreWire}. This {@link ReadWriteEnd} can be written
246 public ReadWriteEnd createReadWriteEnd()
248 return new ReadWriteEnd();
252 * Create a {@link ReadEnd} object, which is tied to this {@link CoreWire}. This {@link ReadEnd} cannot be written to.
254 public ReadEnd createReadOnlyEnd()
256 return new ReadEnd();
259 void registerInput(ReadWriteEnd toRegister)
261 inputs.add(toRegister);
262 recalculateValuesWithoutFusions();
266 * A {@link ReadEnd} feeds a constant signal into the {@link CoreWire} it is tied to. The combination of all inputs determines the
267 * {@link CoreWire}s final value. X dominates all other inputs Z does not affect the final value, unless there are no other inputs than
268 * Z 0 and 1 turn into X when they are mixed
270 * @author Fabian Stemmler
272 public class ReadEnd implements LogicObservable
274 private List<LogicObserver> observers = new ArrayList<>();
279 CoreWire.this.attachEnd(this);
288 * Included for convenient use on {@link CoreWire}s of width 1.
290 * @return The value of bit 0.
292 * @author Fabian Stemmler
294 public Bit getValue()
296 return CoreWire.this.getValue();
300 * @param index Index of the requested bit.
301 * @return The value of the indexed bit.
303 * @author Fabian Stemmler
305 public Bit getValue(int index)
307 return CoreWire.this.getValue(index);
310 public BitVector getValues()
312 return CoreWire.this.getValues();
316 * @param start Start of the wanted segment. (inclusive)
317 * @param end End of the wanted segment. (exclusive)
318 * @return The values of the segment of {@link Bit}s indexed.
320 * @author Fabian Stemmler
322 public BitVector getValues(int start, int end)
324 return CoreWire.this.getValues(start, end);
328 * The {@link CoreWire} is interpreted as an unsigned integer with n bits.
330 * @return <code>true</code> if all bits are either <code>Bit.ONE</code> or <code>Bit.ZERO</code> (they do not all have to have the
331 * same value), not <code>Bit.X</code> or <code>Bit.Z</code>. <code>false</code> is returned otherwise.
333 * @author Fabian Stemmler
335 public boolean hasNumericValue()
337 return CoreWire.this.hasNumericValue();
341 * The {@link CoreWire} is interpreted as an unsigned integer with n bits.
343 * @return The unsigned value of the {@link CoreWire}'s bits, where value 0 corresponds with 2^0, value 1 is 2^1 and so on.
345 * @author Fabian Stemmler
347 public long getUnsignedValue()
349 return CoreWire.this.getUnsignedValue();
353 * The {@link CoreWire} is interpreted as a signed integer with n bits.
355 * @return The signed value of the {@link CoreWire}'s bits, where value 0 corresponds with 2^0, value 1 is 2^1 and so on.
357 * @author Fabian Stemmler
359 public long getSignedValue()
361 return CoreWire.this.getSignedValue();
365 public String toString()
367 return CoreWire.this.toString();
374 recalculateValuesWithoutFusions();
382 public CoreWire getWire()
384 return CoreWire.this;
388 public void registerObserver(LogicObserver ob)
394 public void deregisterObserver(LogicObserver ob)
396 observers.remove(ob);
399 // void registerCloseObserver(LogicObserver ob)
401 // closeObserver.add(ob);
404 // void deregisterCloseObserver(LogicObserver ob)
406 // closeObserver.remove(ob);
410 public void notifyObservers()
412 observers.forEach(ob -> ob.update(this));
416 public class ReadWriteEnd extends ReadEnd
418 private boolean open;
419 private boolean isWriting;
420 private BitVector inputValues;
431 private void initValues()
433 inputValues = U.toVector(width);
437 * Sets the wires values. This takes up time, as specified by the {@link CoreWire}s travel time.
439 * @param newValues The new values the wires should take on.
441 * @author Fabian Stemmler
443 public void feedSignals(Bit... newValues)
445 feedSignals(BitVector.of(newValues));
448 // TODO what if this is called multiple times at the same simulation time? (happens in component unit tests)
449 public void feedSignals(BitVector newValues)
451 if (newValues.length() != width)
452 throw new IllegalArgumentException(
453 String.format("Attempted to input %d bits instead of %d bits.", newValues.length(), width));
455 throw new IllegalStateException("Attempted to write to closed WireArrayEnd.");
456 timeline.addEvent(e -> setValues(newValues), travelTime);
460 * Sets values of a subarray of wires. This takes up time, as specified by the {@link CoreWire}s travel time.
462 * @param bitVector The new values the wires should take on.
463 * @param startingBit The first index of the subarray of wires.
465 * @author Fabian Stemmler
467 public void feedSignals(int startingBit, BitVector bitVector)
470 throw new IllegalStateException("Attempted to write to closed WireArrayEnd.");
471 timeline.addEvent(e -> setValues(startingBit, bitVector), travelTime);
475 * Sets the values that are being fed into the {@link CoreWire}. The preferred way of setting {@link ReadWriteEnd} values is via
476 * feedValues(...) with a delay.
478 void setValues(int startingBit, BitVector newValues)
480 // index check covered in equals
481 if (!inputValues.equalsWithOffset(newValues, startingBit))
483 Bit[] vals = inputValues.getBits();
484 System.arraycopy(newValues.getBits(), 0, vals, startingBit, newValues.length());
485 inputValues = BitVector.of(vals);
486 CoreWire.this.recalculateValuesWithoutFusions();
491 * Sets the values that are being fed into the {@link CoreWire}. The preferred way of setting {@link ReadWriteEnd} values is via
492 * feedValues(...) with a delay.
494 void setValues(BitVector newValues)
496 if (inputValues.equals(newValues))
498 inputValues = newValues;
499 CoreWire.this.recalculateValuesWithoutFusions();
503 * @return The value (of bit 0) the {@link ReadEnd} is currently feeding into the associated {@link CoreWire}.Returns the least
504 * significant bit (LSB)
506 public Bit getInputValue()
508 return getInputValue(0);
512 * @return The value which the {@link ReadEnd} is currently feeding into the associated {@link CoreWire} at the indexed {@link Bit}.
513 * Returns the least significant bit (LSB)
516 public Bit getInputValue(int index)
518 return inputValues.getLSBit(index);
522 * @return A copy (safe to modify) of the values the {@link ReadEnd} is currently feeding into the associated {@link CoreWire}.
524 public BitVector getInputValues()
529 public BitVector getInputValues(int start, int end)
531 return inputValues.subVector(start, end);
535 * {@link ReadEnd} now feeds Z into the associated {@link CoreWire}.
537 public void clearSignals()
539 feedSignals(Z.toVector(width));
542 public BitVector wireValuesExcludingMe()
544 BitVectorMutator mutator = BitVectorMutator.empty();
545 boolean modified = false;
546 for (ReadWriteEnd wireEnd : inputs)
551 mutator.join(wireEnd.inputValues);
554 mutator.join(BitVector.of(Bit.Z, width));
555 return mutator.toBitVector();
559 public String toString()
561 return inputValues.toString();
571 void setWriting(boolean isWriting)
573 if (this.isWriting != isWriting)
575 this.isWriting = isWriting;
580 CoreWire.this.recalculateValuesWithoutFusions();
591 public String toString()
593 String name = this.name == null ? String.format("0x%08x", hashCode()) : this.name;
594 return String.format("wire %s value: %s inputs: %s", name, getValues(), inputs);
597 public static ReadEnd[] extractEnds(CoreWire[] w)
599 ReadEnd[] inputs = new ReadEnd[w.length];
600 for (int i = 0; i < w.length; i++)
601 inputs[i] = w[i].createReadWriteEnd();
607 * Fuses two wires together. If the bits change in one Wire, the other is changed accordingly immediately. Warning: The bits are
608 * permanently fused together.
610 * @param a The {@link CoreWire} to be fused with b
611 * @param b The {@link CoreWire} to be fused with a
613 public static void fuse(CoreWire a, CoreWire b)
615 fuse(a, b, 0, 0, a.width);
619 * Fuses the selected bits of two wires together. If the bits change in one Wire, the other is changed accordingly immediately. Warning:
620 * The bits are permanently fused together.
622 * @param a The {@link CoreWire} to be (partially) fused with b
623 * @param b The {@link CoreWire} to be (partially) fused with a
624 * @param fromA The first bit of {@link CoreWire} a to be fused
625 * @param fromB The first bit of {@link CoreWire} b to be fused
626 * @param width The amount of bits to fuse
628 public static void fuse(CoreWire a, CoreWire b, int fromA, int fromB, int width)
630 // iterate in this direction to be fail-fast (rely on the checks in fuse(Wire, Wire, int, int)
631 for (int i = width - 1; i >= 0; i--)
632 fuse(a, b, fromA + i, fromB + i);
636 * Fuses one bit of two wires together. If this bit changes in one Wire, the other is changed accordingly immediately. Warning: The bits
637 * are permanently fused together.
639 * @param a The {@link CoreWire} to be (partially) fused with b
640 * @param b The {@link CoreWire} to be (partially) fused with a
641 * @param bitA The bit of {@link CoreWire} a to be fused
642 * @param bitB The bit of {@link CoreWire} b to be fused
644 public static void fuse(CoreWire a, CoreWire b, int bitA, int bitB)
647 throw new IllegalArgumentException("No bit " + bitA + " in " + a + " (width " + a.width + ")");
649 throw new IllegalArgumentException("No bit " + bitB + " in " + b + " (width " + b.width + ")");
650 if (a.fusedBits == null)
651 a.fusedBits = new FusedBit[a.width];
652 if (b.fusedBits == null)
653 b.fusedBits = new FusedBit[b.width];
654 FusedBit oldFusionA = a.fusedBits[bitA];
655 FusedBit oldFusionB = b.fusedBits[bitB];
656 if (oldFusionA == null)
657 if (oldFusionB == null)
659 FusedBit fusion = new FusedBit();
660 fusion.addParticipatingWireBit(a, bitA);
661 fusion.addParticipatingWireBit(b, bitB);
663 oldFusionB.addParticipatingWireBit(a, bitA);
664 else if (oldFusionB == null)
665 oldFusionA.addParticipatingWireBit(b, bitB);
667 oldFusionA.mergeOtherIntoThis(oldFusionB);
670 private static class FusedBit
672 private final Set<WireBit> participatingWireBits;
676 this.participatingWireBits = new HashSet<>();
679 public void addParticipatingWireBit(CoreWire w, int bit)
681 addParticipatingWireBit(new WireBit(w, bit));
684 private void addParticipatingWireBit(WireBit wb)
686 wb.wire.fusedBits[wb.bit] = this;
687 participatingWireBits.add(wb);
688 wb.wire.invalidateCachedValuesForAllFusedWires();
691 public void mergeOtherIntoThis(FusedBit other)
693 for (WireBit wb : other.participatingWireBits)
694 addParticipatingWireBit(wb);
697 public void invalidateCachedValuesForAllParticipatingWires()
699 for (WireBit wb : participatingWireBits)
700 wb.wire.invalidateCachedValues();
703 public Bit getValue()
706 for (WireBit wb : participatingWireBits)
707 if (!wb.wire.inputs.isEmpty())
709 Bit bit = wb.wire.bitsWithoutFusions[wb.bit];
710 result = result == null ? bit : result.join(bit);
712 return result == null ? U : result;
716 private static class WireBit
718 public final CoreWire wire;
719 public final int bit;
721 public WireBit(CoreWire wire, int bit)
728 public int hashCode()
730 final int prime = 31;
732 result = prime * result + bit;
733 result = prime * result + ((wire == null) ? 0 : wire.hashCode());
738 public boolean equals(Object obj)
744 if (getClass() != obj.getClass())
746 WireBit other = (WireBit) obj;
747 if (bit != other.bit)
751 if (other.wire != null)
753 } else if (!wire.equals(other.wire))