-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathRWRoute.java
More file actions
2493 lines (2232 loc) · 112 KB
/
RWRoute.java
File metadata and controls
2493 lines (2232 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* Copyright (c) 2021 Ghent University.
* Copyright (c) 2022-2025, Advanced Micro Devices, Inc.
* All rights reserved.
*
* Author: Yun Zhou, Ghent University.
*
* This file is part of RapidWright.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.xilinx.rapidwright.rwroute;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import com.xilinx.rapidwright.design.Cell;
import com.xilinx.rapidwright.design.Design;
import com.xilinx.rapidwright.design.DesignTools;
import com.xilinx.rapidwright.design.Net;
import com.xilinx.rapidwright.design.NetTools;
import com.xilinx.rapidwright.design.NetType;
import com.xilinx.rapidwright.design.SiteInst;
import com.xilinx.rapidwright.design.SitePinInst;
import com.xilinx.rapidwright.design.tools.LUTTools;
import com.xilinx.rapidwright.device.BEL;
import com.xilinx.rapidwright.device.ClockRegion;
import com.xilinx.rapidwright.device.IntentCode;
import com.xilinx.rapidwright.device.Node;
import com.xilinx.rapidwright.device.PIP;
import com.xilinx.rapidwright.device.Part;
import com.xilinx.rapidwright.device.Series;
import com.xilinx.rapidwright.device.Site;
import com.xilinx.rapidwright.device.SitePin;
import com.xilinx.rapidwright.device.Tile;
import com.xilinx.rapidwright.device.TileTypeEnum;
import com.xilinx.rapidwright.edif.EDIFHierNet;
import com.xilinx.rapidwright.interchange.Interchange;
import com.xilinx.rapidwright.router.RouteThruHelper;
import com.xilinx.rapidwright.tests.CodePerfTracker;
import com.xilinx.rapidwright.timing.ClkRouteTiming;
import com.xilinx.rapidwright.timing.TimingManager;
import com.xilinx.rapidwright.timing.TimingVertex;
import com.xilinx.rapidwright.timing.delayestimator.DelayEstimatorBase;
import com.xilinx.rapidwright.timing.delayestimator.InterconnectInfo;
import com.xilinx.rapidwright.util.MessageGenerator;
import com.xilinx.rapidwright.util.Pair;
import com.xilinx.rapidwright.util.RuntimeTracker;
import com.xilinx.rapidwright.util.RuntimeTrackerTree;
import com.xilinx.rapidwright.util.Utils;
/**
* RWRoute class provides the main methods for routing a design.
* Creating a RWRoute Object needs a {@link Design} Object and a {@link RWRouteConfig} Object.
*/
public class RWRoute {
/** The design to route */
protected Design design;
/** Created NetWrappers */
protected Map<Net,NetWrapper> nets;
/** A list of indirect connections that will go through iterative routing */
protected List<Connection> indirectConnections;
/** A list of direct connections that are easily routed through dedicated resources */
private List<Connection> directConnections;
/** Sorted indirect connections */
protected List<Connection> sortedIndirectConnections;
/** A list of global clock nets */
protected List<Net> clkNets;
/** Static nets */
protected Map<Net, List<SitePinInst>> staticNetAndRoutingTargets;
/** Several integers to indicate the netlist info */
protected int numPreservedRoutableNets;
protected int numPreservedClks;
protected int numPreservedStaticNets;
protected int numPreservedWire;
private int numWireNetsToRoute;
private int numConnectionsToRoute;
protected int numNotNeedingRoutingNets;
private int numUnrecognizedNets;
/** A {@link RWRouteConfig} instance consisting of a list of routing parameters */
protected RWRouteConfig config;
/** The present congestion cost factor */
protected float presentCongestionFactor;
/** The historical congestion cost factor */
private float historicalCongestionFactor;
/** Wirelength-driven weighting factor */
private float wlWeight;
/** 1 - wlWeight */
private float oneMinusWlWeight;
/** Timing-driven weighting factor */
private float timingWeight;
/** 1 - timingWeight */
private float oneMinusTimingWeight;
/** Flag for whether LUT pin swaps are to be considered */
private boolean lutPinSwapping;
/** Flag for use of Hybrid Updating Strategy (HUS) */
private boolean hus;
/** Flag (computed at end of iteration 1) to indicate design is congested enough to consider HUS */
private boolean husInitialCongested;
/** The current routing iteration */
protected int routeIteration;
/** Timers to store runtime of different phases */
protected RuntimeTrackerTree routerTimer;
protected RuntimeTracker rnodesTimer;
private RuntimeTracker updateTimingTimer;
private RuntimeTracker updateCongestionCosts;
/** An instantiation of RouteThruHelper to avoid route-thrus in the routing resource graph */
protected RouteThruHelper routethruHelper;
/** A set of indices of overused rondes */
private Set<RouteNode> overUsedRnodes;
/** Class encapsulating the routing resource graph */
protected RouteNodeGraph routingGraph;
/** Count of rnodes created in the current routing iteration */
protected long rnodesCreatedThisIteration;
/** State necessary to route the included connection */
private ConnectionState connectionState;
/** Total wirelength of the routed design */
private int totalWL;
/** Total used INT tile nodes */
private long totalINTNodes;
/** A map from node types to the node usage of the types */
private Map<IntentCode, Long> nodeTypeUsage;
/** A map from node types to the total wirelength of used nodes of the types */
private Map<IntentCode, Long> nodeTypeLength;
/** The total number of connections that are routed */
private final AtomicInteger connectionsRouted;
/** The total number of connections routed in an iteration */
private final AtomicInteger connectionsRoutedThisIteration;
/** Total number of nodes pushed/popped from the queue */
private final AtomicLong nodesPushed;
private final AtomicLong nodesPopped;
/** The maximum criticality constraint of connection */
private static final float MAX_CRITICALITY = 0.99f;
/** The minimum criticality of connections that should be re-routed, updated after each iteration */
protected float minRerouteCriticality;
/** The list of critical connections */
private List<Connection> criticalConnections;
/** A {@link TimingManager} instance to use that handles timing related tasks */
protected TimingManager timingManager;
/** A map from nodes to delay values, used for timing update after fixing routes */
private Map<Node, Float> nodesDelays;
/** The maximum delay and associated timing vertex */
private Pair<Float, TimingVertex> maxDelayAndTimingVertex;
/** A map storing routes from CLK_OUT to different INT tiles that connect to sink pins of a global clock net */
protected Map<String, List<String>> routesToSinkINTTiles;
public static final EnumSet<Series> SUPPORTED_SERIES = EnumSet.of(
Series.UltraScale,
Series.UltraScalePlus,
Series.Versal);
/** For connections that require SLR crossing(s), snap back to the previous Laguna column if the (horizontal) detour
* is no more than this number of tiles */
protected int maxDetourToSnapBackToPrevLagunaColumn = 4;
public RWRoute(Design design, RWRouteConfig config) {
this.design = design;
this.config = config;
connectionsRouted = new AtomicInteger();
connectionsRoutedThisIteration = new AtomicInteger();
nodesPushed = new AtomicLong();
nodesPopped = new AtomicLong();
if (design.getSeries() == Series.Versal) {
if (config.isLutPinSwapping()) {
throw new RuntimeException("ERROR: '--lutPinSwapping' not yet supported on Versal.");
}
if (config.isLutRoutethru()) {
throw new RuntimeException("ERROR: '--lutRoutethru' not yet supported on Versal.");
}
}
}
protected static String getUnsupportedSeriesMessage(Part part) {
return "ERROR: RWRoute does not support routing the " + part.getName() + " from the "
+ part.getSeries() + " series. Please re-target the design to a part from a "
+ "supported series: " + SUPPORTED_SERIES;
}
/**
* Pre-process the design to ensure that only the physical {@link Net}-s corresponding to
* the parent logical {@link EDIFHierNet} exists, and that such {@link Net}-s contain
* all necessary {@link SitePinInst} objects.
* @param design Design to preprocess
*/
public static void preprocess(Design design) {
Series series = design.getPart().getSeries();
if (!SUPPORTED_SERIES.contains(series)) {
throw new RuntimeException(getUnsupportedSeriesMessage(design.getPart()));
}
// Pre-processing of the design regarding physical net names pins
DesignTools.makePhysNetNamesConsistent(design);
DesignTools.createPossiblePinsToStaticNets(design);
DesignTools.createMissingSitePinInsts(design);
if (series == Series.Versal) {
DesignTools.updateVersalXPHYPinsForDMC(design);
}
}
protected void preprocess() {
preprocess(design);
}
protected void initialize() {
routerTimer = new RuntimeTrackerTree("Route design", config.isVerbose());
rnodesTimer = routerTimer.createStandAloneRuntimeTracker("rnodes creation");
updateTimingTimer = routerTimer.createStandAloneRuntimeTracker("update timing");
updateCongestionCosts = routerTimer.createStandAloneRuntimeTracker("update congestion costs");
routerTimer.createRuntimeTracker("Initialization", routerTimer.getRootRuntimeTracker()).start();
minRerouteCriticality = config.getMinRerouteCriticality();
criticalConnections = new ArrayList<>();
connectionState = new ConnectionState();
routingGraph = createRouteNodeGraph();
if (config.isTimingDriven()) {
nodesDelays = new HashMap<>();
}
routethruHelper = new RouteThruHelper(design.getDevice());
presentCongestionFactor = config.getInitialPresentCongestionFactor();
lutPinSwapping = config.isLutPinSwapping();
routerTimer.createRuntimeTracker("determine route targets", "Initialization").start();
determineRoutingTargets();
ensureSinkRoutability();
routerTimer.getRuntimeTracker("determine route targets").stop();
if (config.isTimingDriven()) {
ClkRouteTiming clkTiming = createClkTimingData(config);
routesToSinkINTTiles = clkTiming == null? null : clkTiming.getRoutesToSinkINTTiles();
Collection<Net> timingNets = getTimingNets();
timingManager = createTimingManager(clkTiming, timingNets);
timingManager.setTimingEdgesOfConnections(indirectConnections);
}
sortedIndirectConnections = new ArrayList<>(indirectConnections.size());
connectionsRouted.set(0);
connectionsRoutedThisIteration.set(0);
nodesPushed.set(0);
nodesPopped.set(0);
overUsedRnodes = new HashSet<>();
hus = config.isHus();
husInitialCongested = false;
routerTimer.getRuntimeTracker("Initialization").stop();
}
/**
* Creates clock routing related inputs based on the {@link RWRouteConfig} instance.
* @param config The {@link RWRouteConfig} instance to use.
*/
public static ClkRouteTiming createClkTimingData(RWRouteConfig config) {
String clkRouteTimingFile = config.getClkRouteTiming();
if (clkRouteTimingFile != null) {
return new ClkRouteTiming(clkRouteTimingFile);
}
return null;
}
protected RouteNodeGraph createRouteNodeGraph() {
if (config.isTimingDriven()) {
/* An instantiated delay estimator that is used to calculate delay of routing resources */
DelayEstimatorBase<InterconnectInfo> estimator = new DelayEstimatorBase<InterconnectInfo>(
design.getDevice(), new InterconnectInfo(), config.isUseUTurnNodes(), 0);
return new RouteNodeGraphTimingDriven(design, config, estimator);
} else {
return new RouteNodeGraph(design, config);
}
}
protected Collection<Net> getTimingNets() {
return design.getNets();
}
protected TimingManager createTimingManager(ClkRouteTiming clkTiming, Collection<Net> timingNets) {
final boolean isPartialRouting = false;
return new TimingManager(design, routerTimer, config, clkTiming, timingNets, isPartialRouting);
}
/**
* Classifies {@link Net} Objects into different categories: clocks, static nets,
* and regular signal nets (i.e. {@link NetType}.WIRE) and determines routing targets.
*/
protected void determineRoutingTargets() {
categorizeNets();
// Since createNetWrapperAndConnections() both creates the primary sink node and
// computes alternate sinks (e.g. for LUT pin swaps), it is possible that
// an alternate sink for one net later becomes an exclusive sink for another net.
// Examine for all connections for this case and remove such alternate sinks.
for (Connection connection : indirectConnections) {
connection.getAltSinkRnodes().removeIf(RouteNode::isUsed);
}
// Wait for all outstanding RouteNodeGraph.preserveAsync() calls to complete
routingGraph.awaitPreserve();
}
protected Set<Net> ensureSinkRoutability() {
// RWRoute routes designs from scratch -- all sinks must be reachable
return Collections.emptySet();
}
private void categorizeNets() {
numWireNetsToRoute = 0;
numConnectionsToRoute = 0;
numPreservedRoutableNets = 0;
numNotNeedingRoutingNets = 0;
numUnrecognizedNets = 0;
nets = new IdentityHashMap<>();
indirectConnections = new ArrayList<>();
directConnections = new ArrayList<>();
clkNets = new ArrayList<>();
staticNetAndRoutingTargets = new HashMap<>();
for (Net net : design.getNets()) {
if (NetTools.isGlobalClock(net)) {
addGlobalClkRoutingTargets(net);
} else if (net.isStaticNet()) {
addStaticNetRoutingTargets(net);
} else if (net.getType().equals(NetType.WIRE)) {
if (RouterHelper.isDriverLessOrLoadLessNet(net) ||
RouterHelper.isInternallyRoutedNet(net) ||
net.getName().equals(Net.Z_NET)) {
preserveNet(net, true);
numNotNeedingRoutingNets++;
} else if (RouterHelper.isRoutableNetWithSourceSinks(net)) {
addNetConnectionToRoutingTargets(net);
} else {
numNotNeedingRoutingNets++;
}
} else {
numUnrecognizedNets++;
System.err.println("ERROR: Unknown net " + net);
}
}
}
/**
* A helper method for profiling the routing runtime v.s. average span of connections.
*/
protected void printConnectionSpanStatistics() {
System.out.println("Connection Span Info:");
if (config.isPrintConnectionSpan()) System.out.println(" Span" + "\t" + "# Connections" + "\t" + "Percent");
long sumSpan = 0;
short max = 0;
for (Entry<Short, Integer> spanCount : connectionSpan.entrySet()) {
Short span = spanCount.getKey();
Integer count = spanCount.getValue();
if (config.isPrintConnectionSpan()) {
System.out.printf("%5d \t%12d \t%7.2f\n", span, count, (float)count / indirectConnections.size() * 100);
}
sumSpan += span * count;
if (span > max) max = span;
}
if (config.isPrintConnectionSpan()) System.out.println();
long avg = (long) (sumSpan / ((float) indirectConnections.size()));
System.out.println("INFO: Max span of connections: " + max);
System.out.println("INFO: Avg span of connections: " + avg);
int numConnectionsLongerThanAvg = 0;
for (Entry<Short, Integer> spanCount : connectionSpan.entrySet()) {
if (spanCount.getKey() >= avg) numConnectionsLongerThanAvg += spanCount.getValue();
}
System.out.printf("INFO: # connections longer than avg span: %d\n", numConnectionsLongerThanAvg);
System.out.printf("(%5.2f%%)\n", (float)numConnectionsLongerThanAvg / indirectConnections.size() * 100);
System.out.println("------------------------------------------------------------------------------");
}
/**
* Adds the clock net to the list of clock routing targets, if the clock has source and sink {@link SitePinInst} instances.
* Any existing routing on such nets will be unrouted.
* @param clk The clock net in question.
*/
protected void addGlobalClkRoutingTargets(Net clk) {
if (RouterHelper.isRoutableNetWithSourceSinks(clk)) {
clk.unroute();
// Preserve all pins (e.g. in case of BOUNCE nodes that may serve as a site pin)
preserveNet(clk, true);
clkNets.add(clk);
} else {
numNotNeedingRoutingNets++;
System.err.println("ERROR: Incomplete clock net " + clk);
}
}
/**
* Returns whether a node is (a) available for use,
* (b) already in used by this net, (c) unavailable
* @return NodeStatus result.
*/
protected NodeStatus getGlobalRoutingNodeStatus(Net net, Node node) {
if (!routingGraph.isAllowedTile(node)) {
// Outside of PBlock
return NodeStatus.UNAVAILABLE;
}
Net preservedNet = routingGraph.getPreservedNet(node);
if (preservedNet == net) {
return NodeStatus.INUSE;
}
if (preservedNet != null) {
return NodeStatus.UNAVAILABLE;
}
RouteNode rnode = routingGraph.getNode(node);
if (rnode != null) {
// A RouteNode will only be created if the net is necessary for
// a to-be-routed connection
return NodeStatus.UNAVAILABLE;
}
return NodeStatus.AVAILABLE;
}
/**
* Routes clock nets by default or in a different way when corresponding timing info supplied.
* NOTE: For an unrouted design, its clock nets must not contain any PIPs or nodes, i.e, completely unrouted.
* Otherwise, there could be a critical warning of clock routing results, when loading the routed design into Vivado.
* Vivado will unroute the global clock nets immediately when there is such warning.
* TODO: fix the potential issue.
*/
protected void routeGlobalClkNets() {
Map<Integer, Set<ClockRegion>> usedRoutingTracks = new HashMap<>();
for (Net clk : clkNets) {
routeGlobalClkNet(clk, usedRoutingTracks);
}
}
protected void routeGlobalClkNet(Net clk, Map<Integer, Set<ClockRegion>> usedRoutingTracks) {
// Since we preserved all pins in addGlobalClkRoutingTargets(), unpreserve them here
for (SitePinInst spi : clk.getPins()) {
routingGraph.unpreserve(spi.getConnectedNode());
}
Function<Node, NodeStatus> gns = (node) -> getGlobalRoutingNodeStatus(clk, node);
if (routesToSinkINTTiles != null) {
// routes clock nets with references of partial routes
System.out.println("INFO: Routing " + clk.getPins().size() + " pins of clock " + clk + " (timing-driven)");
GlobalSignalRouting.routeClkWithPartialRoutes(clk, routesToSinkINTTiles, design.getDevice(), gns);
} else {
// routes clock nets from scratch
System.out.println("INFO: Routing " + clk.getPins().size() + " pins of clock " + clk + " (non timing-driven)");
GlobalSignalRouting.symmetricClkRouting(clk, design.getDevice(), gns, usedRoutingTracks);
}
preserveNet(clk, false);
if (clk.hasPIPs()) {
clk.getSource().setRouted(true);
assert(clk.getAlternateSource() == null);
}
}
/**
* Adds and initialize a regular signal net to the list of routing targets.
* @param net The net to be added for routing.
*/
protected void addNetConnectionToRoutingTargets(Net net) {
net.unroute();
createNetWrapperAndConnections(net);
}
/**
* Adds a static net to the static net routing target list, unrouting it
* if any routing exists.
* @param staticNet The static net in question, i.e. VCC or GND.
*/
protected void addStaticNetRoutingTargets(Net staticNet) {
List<SitePinInst> sinks = staticNet.getSinkPins();
if (!sinks.isEmpty()) {
staticNet.unroute();
// Remove all output pins from unrouted net as those used will be repopulated
staticNet.setPins(sinks);
staticNetAndRoutingTargets.put(staticNet, new ArrayList<>(sinks));
} else {
numNotNeedingRoutingNets++;
}
}
/**
* Routes static nets.
*/
protected void routeStaticNets() {
Net vccNet = design.getVccNet();
Net gndNet = design.getGndNet();
boolean noStaticRouting = staticNetAndRoutingTargets.isEmpty();
if (!noStaticRouting) {
List<SitePinInst> gndPins = staticNetAndRoutingTargets.get(gndNet);
if (gndPins != null) {
boolean invertGndToVccForLutInputs = config.isInvertGndToVccForLutInputs();
Set<SitePinInst> newVccPins = RouterHelper.invertPossibleGndPinsToVccPins(design, gndPins, invertGndToVccForLutInputs);
if (!newVccPins.isEmpty()) {
gndPins.removeAll(newVccPins);
staticNetAndRoutingTargets.computeIfAbsent(vccNet, (net) -> new ArrayList<>())
.addAll(newVccPins);
}
}
Iterator<Map.Entry<Net,List<SitePinInst>>> it = staticNetAndRoutingTargets.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Net,List<SitePinInst>> e = it.next();
Net staticNet = e.getKey();
List<SitePinInst> pins = e.getValue();
// For some encrypted designs, it's possible that RapidWright cannot infer all SitePinInst-s leading to
// some site pins (e.g. CKEN) defaulting those to static nets. Detect such cases -- when signal nets are
// already routed to and preserved at those uninferrable SitePinInst-s -- and remove them from being a
// static net sink
pins.removeIf(spi -> {
Node node = spi.getConnectedNode();
if (!routingGraph.isAllowedTile(node)) {
// If sink is not in an allowed tile (e.g. outside routing PBlock) drop it silently
return true;
}
Net preservedNet = routingGraph.getPreservedNet(node);
if (preservedNet == null) {
// This sink is not preserved by any net, allow
return false;
}
// Sink preserved by another net, abandon; check that it cannot have been preserved by this static net
assert(preservedNet != staticNet);
return true;
});
// Remove from map if empty
if (pins.isEmpty()) {
it.remove();
}
}
}
// Preserve all static nets' sink pins regardless of whether any routing is necessary
for (Net staticNet : Arrays.asList(vccNet, gndNet)) {
for (SitePinInst spi : staticNet.getPins()) {
if (spi.isOutPin()) {
continue;
}
routingGraph.preserve(spi.getConnectedNode(), staticNet);
}
}
if (noStaticRouting) {
// Now that all static nets have been fully preserved, return if no work to be done
return;
}
for (Map.Entry<Net,List<SitePinInst>> e : staticNetAndRoutingTargets.entrySet()) {
Net staticNet = e.getKey();
List<SitePinInst> pins = e.getValue();
System.out.println("INFO: Routing " + pins.size() + " pins of " + staticNet);
Function<Node, NodeStatus> gns = (node) -> getGlobalRoutingNodeStatus(staticNet, node);
GlobalSignalRouting.routeStaticNet(pins, gns, design, routethruHelper);
preserveNet(staticNet, false);
}
}
/**
* Preserves a net by preserving all nodes use by the net.
* @param net The net to be preserved.
*/
protected void preserveNet(Net net, boolean async) {
if (async) {
routingGraph.preserveAsync(net);
} else {
routingGraph.preserve(net);
}
}
private final Map<Short, Integer> connectionSpan = new HashMap<>();
/**
* Creates a unique {@link NetWrapper} instance and {@link Connection} instances based on a {@link Net} instance.
* @param net The net to be initialized.
* @return A {@link NetWrapper} instance.
*/
protected NetWrapper createNetWrapperAndConnections(Net net) {
List<SitePinInst> sinkPins = net.getSinkPins();
assert(!sinkPins.isEmpty());
NetWrapper netWrapper = new NetWrapper(numWireNetsToRoute++, net);
NetWrapper existingNetWrapper = nets.put(net, netWrapper);
assert(existingNetWrapper == null);
SitePinInst source = net.getSource();
Node sourceINTNode = RouterHelper.projectOutputPinToINTNode(source);
RouteNode sourceINTRnode = null;
int indirect = 0;
for (SitePinInst sink : sinkPins) {
Connection connection = new Connection(numConnectionsToRoute++, source, sink, netWrapper);
Node sinkINTNode = RouterHelper.projectInputPinToINTNode(sink);
if (sourceINTNode == null && sinkINTNode != null) {
// Sink can be projected to an INT tile, but primary source (e.g. COUT)
// cannot be; try alternate source
Pair<SitePinInst,RouteNode> altSourceAndRnode = connection.getOrCreateAlternateSource(routingGraph);
if (altSourceAndRnode != null) {
SitePinInst altSource = altSourceAndRnode.getFirst();
RouteNode altSourceINTRnode = altSourceAndRnode.getSecond();
connection.setSource(altSource);
connection.setSourceRnode(altSourceINTRnode);
}
}
if ((sourceINTNode == null && connection.getSourceRnode() == null) || sinkINTNode == null) {
// Direct connection if either source or sink pin cannot be projected to INT tile
directConnections.add(connection);
connection.setDirect(true);
} else {
if (connection.getSourceRnode() == null) {
assert(sourceINTNode != null);
if (sourceINTRnode == null) {
sourceINTRnode = routingGraph.getOrCreate(sourceINTNode, RouteNodeType.EXCLUSIVE_SOURCE);
// Where only a single primary source exists, always preserve
// its projected-to-INT source node, since it could
// be a projection from LAGUNA/RXQ* -> RXD* (node for INT/LOGIC_OUTS_*)
assert(sourceINTRnode != null);
if (!config.isBackwardRouting()) {
// Only preserve source node if forward routing, otherwise it will be
// excluded during expansion
routingGraph.preserve(sourceINTNode, net);
}
netWrapper.setSourceRnode(sourceINTRnode);
}
connection.setSourceRnode(sourceINTRnode);
}
indirectConnections.add(connection);
RouteNode sinkRnode = routingGraph.getOrCreate(sinkINTNode);
RouteNodeType sinkType = sinkRnode.getType();
assert(sinkType.isAnyLocal());
connection.setSinkRnode(sinkRnode);
if (sinkINTNode.getTile() != sink.getTile()) {
TileTypeEnum sinkTileType = sink.getTile().getTileTypeEnum();
if (Utils.isLaguna(sinkTileType)) {
// Sinks in Laguna tiles must be Laguna registers (but will be projected into the INT tile)
// however, it's possible for another net to use the sink node as a bounce -- prevent that here
assert(sinkINTNode.getTile().getTileTypeEnum() == TileTypeEnum.INT);
routingGraph.preserve(sink.getConnectedNode(), net);
}
}
// Where appropriate, allow all 6 LUT pins to be swapped to begin with
char lutLetter = sink.getName().charAt(0);
int numberOfSwappablePins = (lutPinSwapping && sink.isLUTInputPin())
? LUTTools.MAX_LUT_SIZE : 0;
if (numberOfSwappablePins > 0) {
for (Cell cell : DesignTools.getConnectedCells(sink)) {
BEL bel = cell.getBEL();
assert(bel.isLUT());
String belName = bel.getName();
String cellType = cell.getType();
if (belName.charAt(0) != lutLetter) {
assert(cellType.startsWith("RAM"));
// This pin connects to other LUTs! (e.g. SLICEM.H[1-6] also serves
// as the WA for A-G LUTs used as distributed RAM) -- do not allow any swapping
// TODO: Relax this when https://github.com/Xilinx/RapidWright/issues/901 is fixed
numberOfSwappablePins = 0;
break;
}
if (bel.getName().startsWith("H") && cellType.startsWith("RAM")) {
// Similarly, disallow swapping of any RAMs on the "H" BELs since their
// "A" and "WA" inputs are shared and require extra care to keep in sync
numberOfSwappablePins = 0;
break;
}
if (cellType.startsWith("SRL")) {
// SRL* cells cannot support any pin swaps
numberOfSwappablePins = 0;
break;
}
if (belName.charAt(1) == '5') {
// Since a 5LUT cell exists, only allow bottom 5 pins to be swapped
numberOfSwappablePins = 5;
}
}
}
Site site = sink.getSite();
for (int i = 1; i <= numberOfSwappablePins; i++) {
Node node = site.getConnectedNode(lutLetter + Integer.toString(i));
assert(node.getTile().getTileTypeEnum() == TileTypeEnum.INT);
if (node.equals(sinkINTNode)) {
continue;
}
if (routingGraph.isPreserved(node)) {
continue;
}
RouteNode altSinkRnode = routingGraph.getOrCreate(node, sinkType);
assert(altSinkRnode.getType() == sinkType);
connection.addAltSinkRnode(altSinkRnode);
}
if (!connection.hasAltSinks()) {
// Since this connection only has a single sink target, make it exclusive
sinkType = sinkType.isEastLocal() ? RouteNodeType.EXCLUSIVE_SINK_EAST :
sinkType.isWestLocal() ? RouteNodeType.EXCLUSIVE_SINK_WEST :
sinkType == RouteNodeType.LOCAL_BOTH ? RouteNodeType.EXCLUSIVE_SINK_BOTH :
null;
assert(sinkType != null);
sinkRnode.setType(sinkType);
// And increment its usage here immediately
sinkRnode.incrementUser(netWrapper);
}
connection.setDirect(false);
indirect++;
connection.computeHpwl();
addConnectionSpanInfo(connection);
}
}
if (indirect > 0) {
netWrapper.computeHPWLAndCenterCoordinates(routingGraph);
if (config.isUseBoundingBox()) {
for (Connection connection : netWrapper.getConnections()) {
if (connection.isDirect()) continue;
connection.computeConnectionBoundingBox(config.getBoundingBoxExtensionX(),
config.getBoundingBoxExtensionY(),
routingGraph);
}
}
}
return netWrapper;
}
/**
* Adds span info of a connection.
* @param connection A connection of which span info is to be added.
*/
private void addConnectionSpanInfo(Connection connection) {
connectionSpan.merge(connection.getHpwl(), 1, Integer::sum);
}
/**
* @return ConnectionState object to be used for routing.
*/
protected ConnectionState getConnectionState() {
return connectionState;
}
/**
* Initializes routing.
*/
private void initializeRouting() {
routingGraph.initialize();
routeIteration = 1;
historicalCongestionFactor = config.getHistoricalCongestionFactor();
presentCongestionFactor = config.getInitialPresentCongestionFactor();
timingWeight = config.getTimingWeight();
wlWeight = config.getWirelengthWeight();
oneMinusTimingWeight = 1 - timingWeight;
oneMinusWlWeight = 1 - wlWeight;
printIterationHeader(config.isTimingDriven());
// On Versal only, reserve all uphills of NODE_(CLE|INTF)_CTRL sinks since
// their [BC]NODEs can also be used to reach NODE_INODEs --- not applying this
// heuristic can lead to avoidable congestion
if (routingGraph.isVersal) {
for (Connection connection : indirectConnections) {
RouteNode sinkRnode = connection.getSinkRnode();
if (sinkRnode.getType() == RouteNodeType.EXCLUSIVE_SINK_BOTH) {
IntentCode sinkIntent = sinkRnode.getIntentCode();
for (Node uphill : sinkRnode.getAllUphillNodes()) {
if (uphill.isTiedToVcc()) {
continue;
}
Net preservedNet = routingGraph.getPreservedNet(uphill);
if (preservedNet != null && preservedNet != connection.getNet()) {
continue;
}
if (sinkIntent == IntentCode.NODE_SLL_INPUT && uphill.getIntentCode() == IntentCode.NODE_SLL_OUTPUT) {
// No need to reserve NODE_SLL_OUTPUT nodes of a NODE_SLL_INPUT
continue;
}
assert((sinkIntent == IntentCode.NODE_CLE_CTRL &&
(uphill.getIntentCode() == IntentCode.NODE_CLE_CNODE || uphill.getIntentCode() == IntentCode.NODE_CLE_BNODE)) ||
(sinkIntent == IntentCode.NODE_INTF_CTRL &&
(uphill.getIntentCode() == IntentCode.NODE_INTF_CNODE || uphill.getIntentCode() == IntentCode.NODE_INTF_BNODE)) ||
(sinkIntent == IntentCode.NODE_SLL_INPUT &&
uphill.getIntentCode() == IntentCode.NODE_CLE_BNODE)
);
RouteNode rnode = routingGraph.getOrCreate(uphill, RouteNodeType.LOCAL_RESERVED);
rnode.setType(RouteNodeType.LOCAL_RESERVED);
}
}
}
}
}
/**
* Routes the design in a few routing phases and times those phases.
*/
public void route() {
// Prints the design and configuration info, if "--verbose" is configured
printDesignNetsAndConfigurationInfo(config.isVerbose());
routerTimer.createRuntimeTracker("Routing", routerTimer.getRootRuntimeTracker()).start();
MessageGenerator.printHeader("Route Design");
routerTimer.createRuntimeTracker("route clock", "Routing").start();
routeGlobalClkNets();
routerTimer.getRuntimeTracker("route clock").stop();
routerTimer.createRuntimeTracker("route static nets", "Routing").start();
// Routes static nets (VCC and GND) before signals for now.
// All the used nodes by other nets should be marked as unavailable, if static nets are routed after signals.
routeStaticNets();
// Connection-based router for indirectly connected pairs of output pin and input pin */
routerTimer.getRuntimeTracker("route static nets").stop();
RuntimeTracker routeWireNets = routerTimer.createRuntimeTracker("route wire nets", "Routing");
routeWireNets.start();
preRoutingEstimation();
routeIndirectConnectionsIteratively();
// NOTE: route direct connections after indirect connection.
// The reason is that there maybe additional direct connections in the soft preserve mode for partial routing,
// and those direct connections should be included to be routed
routeDirectConnections();
routeWireNets.stop();
// Adds child timers to "route wire nets" timer
routeWireNets.addChild(rnodesTimer);
// Do not time the cost evaluation method for routing connections, the timer itself takes time
routerTimer.createRuntimeTracker("route connections", "route wire nets").setTime(routeWireNets.getTime() - rnodesTimer.getTime() - updateTimingTimer.getTime() - updateCongestionCosts.getTime());
if (config.isTimingDriven()) {
routeWireNets.addChild(updateTimingTimer);
}
routeWireNets.addChild(updateCongestionCosts);
routerTimer.createRuntimeTracker("finalize routes", "Routing").start();
// Assigns a list of nodes to each direct and indirect connection that has been routed and fix illegal routes if any
postRouteProcess();
// Assigns net PIPs based on lists of connections
setPIPsOfNets();
routerTimer.getRuntimeTracker("finalize routes").stop();
routerTimer.getRuntimeTracker("Routing").stop();
if (config.getExportOutOfContext()) {
getDesign().setAutoIOBuffers(false);
getDesign().setDesignOutOfContext(true);
}
// Prints routing statistics, e.g. total wirelength, runtime and timing report
printRoutingStatistics();
}
/**
* Calculates initial criticality for each connection based on a simple estimation.
*/
private void preRoutingEstimation() {
if (config.isTimingDriven()) {
estimateDelayOfConnections();
maxDelayAndTimingVertex = timingManager.calculateArrivalRequiredTimes();
timingManager.calculateCriticality(indirectConnections, MAX_CRITICALITY, config.getCriticalityExponent());
System.out.printf("INFO: Estimated pre-routing max delay: %4d\n", (short) maxDelayAndTimingVertex.getFirst().floatValue());
}
}
/**
* A simple approach to estimate delay of each connection and update route delay of its timing edges.
*/
private void estimateDelayOfConnections() {
for (Connection connection : indirectConnections) {
RouteNode source = connection.getSourceRnode();
RouteNode[] children = source.getChildren(routingGraph);
if (children.length == 0) {
// output pin is blocked
swapOutputPin(connection);
source = connection.getSourceRnode();
}
short estDelay = (short) 10000;
for (RouteNode child : children) {
short tmpDelay = 113;
tmpDelay += child.getDelay();
if (tmpDelay < estDelay) {
estDelay = tmpDelay;
}
}
estDelay += source.getDelay();
connection.setTimingEdgesDelay(estDelay);
}
}
/**
* Routes direct connections.
*/
private void routeDirectConnections() {
System.out.println("\nINFO: Route " + directConnections.size() + " direct connections ");
for (Connection connection : directConnections) {
boolean success = RouterHelper.routeDirectConnection(connection);
connection.setRouted(success);
// no need to update route delay of direct connection, because it would not be changed
if (!success) System.err.println("ERROR: Failed to route direct connection " + connection);
}
}
protected void routeIndirectConnections(Collection<Connection> connections) {
for (Connection connection : connections) {
if (shouldRoute(connection)) {
routeIndirectConnection(connection);
}
}
}
/**
* Routes indirect connections iteratively.
*/
public void routeIndirectConnectionsIteratively() {
sortConnections();
initializeRouting();
long lastIterationRnodeCount = routingGraph.numNodes();
long lastIterationRnodeTime = 0;
boolean initialHus = this.hus;
while (routeIteration < config.getMaxIterations()) {
long start = RuntimeTracker.now();
connectionsRoutedThisIteration.set(0);
if (config.isTimingDriven()) {
setRerouteCriticality();
}
routingGraph.updatePresentCongestionCosts(presentCongestionFactor);
routeIndirectConnections(sortedIndirectConnections);
rnodesTimer.setTime(routingGraph.getCreateRnodeTime());
updateCostFactors();
rnodesCreatedThisIteration = routingGraph.numNodes() - lastIterationRnodeCount;
List<Connection> unroutableConnections = getUnroutableConnections();
boolean needsResorting = false;
for (Connection connection : unroutableConnections) {
System.out.printf("CRITICAL WARNING: Unroutable connection in iteration #%d\n", routeIteration);
System.out.println(" " + connection);
needsResorting = handleUnroutableConnection(connection) || needsResorting;
}
for (Connection connection : getCongestedConnections()) {
needsResorting = handleCongestedConnection(connection) || needsResorting;
}
if (needsResorting) {
sortConnections();
}
if (config.isTimingDriven()) {
updateTiming();
}
long elapsed = RuntimeTracker.elapsed(start);
printRoutingIterationStatisticsInfo(elapsed, (float) ((rnodesTimer.getTime() - lastIterationRnodeTime) * 1e-9));
if (overUsedRnodes.isEmpty()) {
if (unroutableConnections.isEmpty()) {