forked from The-OpenROAD-Project/OpenROAD
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNegotiationLegalizer.cpp
More file actions
1432 lines (1311 loc) · 45.5 KB
/
Copy pathNegotiationLegalizer.cpp
File metadata and controls
1432 lines (1311 loc) · 45.5 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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2018-2026, The OpenROAD Authors
#include "NegotiationLegalizer.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <functional>
#include <limits>
#include <queue>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "PlacementDRC.h"
#include "dpl/Opendp.h"
#include "graphics/DplObserver.h"
#include "infrastructure/Grid.h"
#include "infrastructure/Objects.h"
#include "infrastructure/Padding.h"
#include "infrastructure/architecture.h"
#include "infrastructure/network.h"
#include "odb/db.h"
#include "odb/geom.h"
#include "utl/Logger.h"
#include "utl/timer.h"
namespace dpl {
// ===========================================================================
// FenceRegion
// ===========================================================================
bool FenceRegion::contains(int x, int y, int w, int h) const
{
for (const auto& r : rects) {
if (x >= r.xlo && y >= r.ylo && x + w <= r.xhi && y + h <= r.yhi) {
return true;
}
}
return false;
}
FenceRect FenceRegion::nearestRect(int cx, int cy) const
{
assert(!rects.empty());
const FenceRect* best = rects.data();
int best_dist = std::numeric_limits<int>::max();
for (const auto& r : rects) {
const int d = odb::manhattanDistance(odb::Rect(r.xlo, r.ylo, r.xhi, r.yhi),
odb::Point(cx, cy));
if (d < best_dist) {
best_dist = d;
best = &r;
}
}
return *best;
}
// ===========================================================================
// Constructor
// ===========================================================================
NegotiationLegalizer::NegotiationLegalizer(Opendp* opendp,
odb::dbDatabase* db,
utl::Logger* logger,
const Padding* padding,
DplObserver* debug_observer,
Network* network)
: opendp_(opendp),
db_(db),
logger_(logger),
padding_(padding),
debug_observer_(debug_observer),
network_(network)
{
}
// ===========================================================================
// legalize – top-level entry point
// ===========================================================================
void NegotiationLegalizer::legalize()
{
debugPrint(logger_,
utl::DPL,
"negotiation",
1,
"NegotiationLegalizer: starting legalization.");
double init_from_db_s{0}, build_grid_s{0}, fence_regions_s{0}, abacus_s{0};
double negotiation_s{0}, post_neg_sync_s{0}, metrics_s{0}, flush_s{0},
orient_s{0};
const utl::Timer total_timer;
{
utl::DebugScopedTimer t(init_from_db_s,
logger_,
utl::DPL,
"negotiation_runtime",
1,
"initFromDb: {}");
if (!initFromDb()) {
return;
}
}
if (debug_observer_) {
debug_observer_->startPlacement(db_->getChip()->getBlock());
debugPause("Pause after initFromDb.");
}
{
utl::DebugScopedTimer t(build_grid_s,
logger_,
utl::DPL,
"negotiation_runtime",
1,
"buildGrid: {}");
buildGrid();
}
{
utl::DebugScopedTimer t(fence_regions_s,
logger_,
utl::DPL,
"negotiation_runtime",
1,
"initFenceRegions: {}");
initFenceRegions();
}
debugPrint(logger_,
utl::DPL,
"negotiation",
1,
"NegotiationLegalizer: {} cells, grid {}x{}.",
cells_.size(),
grid_w_,
grid_h_);
// --- Part 1: Abacus (handles the majority of cells cheaply) -------------
std::vector<int> illegal;
if (run_abacus_) {
debugPrint(logger_,
utl::DPL,
"negotiation",
1,
"NegotiationLegalizer: running Abacus pass.");
{
utl::DebugScopedTimer t(abacus_s,
logger_,
utl::DPL,
"negotiation_runtime",
1,
"runAbacus: {}");
illegal = runAbacus();
}
debugPrint(logger_,
utl::DPL,
"negotiation",
1,
"NegotiationLegalizer: Abacus done, {} cells still illegal.",
illegal.size());
} else {
debugPrint(logger_,
utl::DPL,
"negotiation",
1,
"NegotiationLegalizer: skipping Abacus pass.");
{
utl::DebugScopedTimer t(abacus_s,
logger_,
utl::DPL,
"negotiation_runtime",
1,
"skip-Abacus addUsage: {}");
// Populate usage from initial coordinates
for (int i = 0; i < static_cast<int>(cells_.size()); ++i) {
if (!cells_[i].fixed) {
addUsage(i, 1);
}
}
}
{
utl::DebugScopedTimer t(abacus_s,
logger_,
utl::DPL,
"negotiation_runtime",
1,
"skip-Abacus syncAllCellsToDplGrid: {}");
// Sync all movable cells to the DPL Grid so PlacementDRC neighbour
// lookups see the correct placement state.
syncAllCellsToDplGrid();
}
{
utl::DebugScopedTimer t(abacus_s,
logger_,
utl::DPL,
"negotiation_runtime",
1,
"skip-Abacus isCellLegal scan: {}");
for (int i = 0; i < static_cast<int>(cells_.size()); ++i) {
if (!cells_[i].fixed) {
cells_[i].legal = isCellLegal(i);
if (!cells_[i].legal) {
illegal.push_back(i);
}
}
}
}
debugPrint(logger_,
utl::DPL,
"negotiation",
1,
"{} illegal cells",
illegal.size());
}
if (debug_observer_) {
setDplPositions();
// this flush may imply functional changes. It hides initial movements for
// clean debugging negotiation phase.
flushToDb();
pushNegotiationPixels();
logger_->report("Pause after Abacus pass.");
debug_observer_->redrawAndPause();
}
// --- Part 2: Negotiation (main legalization) -------------------
if (!illegal.empty()) {
debugPrint(logger_,
utl::DPL,
"negotiation",
1,
"NegotiationLegalizer: negotiation pass on {} cells.",
illegal.size());
utl::DebugScopedTimer t(negotiation_s,
logger_,
utl::DPL,
"negotiation_runtime",
1,
"runNegotiation: {}");
runNegotiation(illegal);
}
// Re-sync the DPL pixel grid after negotiation. During negotiation,
// overlapping cells share a single pixel->cell slot; when one is ripped
// up, the other's presence is lost. A full re-sync ensures every cell
// is correctly painted so subsequent DRC checks (numViolations, etc.)
// see the true placement state.
{
utl::DebugScopedTimer t(post_neg_sync_s,
logger_,
utl::DPL,
"negotiation_runtime",
1,
"post-negotiation syncAllCellsToDplGrid: {}");
syncAllCellsToDplGrid();
}
debugPause("Pause after negotiation pass");
// --- Part 3: Post-optimisation ------------------------------------------
debugPrint(logger_,
utl::DPL,
"negotiation",
1,
"NegotiationLegalizer: post-optimisation.");
// greedyImprove(5);
// cellSwap();
// greedyImprove(1);
double avgDisp{0};
int maxDisp{0}, nViol{0};
{
utl::DebugScopedTimer t(metrics_s,
logger_,
utl::DPL,
"negotiation_runtime",
1,
"metrics (avgDisp/maxDisp/violations): {}");
avgDisp = avgDisplacement();
maxDisp = maxDisplacement();
nViol = numViolations();
}
debugPrint(
logger_,
utl::DPL,
"negotiation",
1,
"NegotiationLegalizer: done. AvgDisp={:.2f} MaxDisp={} Violations={}.",
avgDisp,
maxDisp,
nViol);
{
utl::DebugScopedTimer t(
flush_s, logger_, utl::DPL, "negotiation_runtime", 1, "flushToDb: {}");
flushToDb();
}
{
utl::DebugScopedTimer t(orient_s,
logger_,
utl::DPL,
"negotiation_runtime",
1,
"orientation update: {}");
const Grid* dplGrid = opendp_->grid_.get();
for (const auto& cell : cells_) {
if (cell.fixed || cell.db_inst == nullptr) {
continue;
}
// Set orientation from the row so cells are properly flipped.
odb::dbSite* site = cell.db_inst->getMaster()->getSite();
if (site != nullptr) {
auto orient
= dplGrid->getSiteOrientation(GridX{cell.x}, GridY{cell.y}, site);
if (orient.has_value()) {
cell.db_inst->setOrient(orient.value());
}
}
}
}
const double total_s = total_timer.elapsed();
auto pct
= [total_s](double t) { return total_s > 0 ? 100.0 * t / total_s : 0.0; };
auto to_ms = [](double s) { return s * 1e3; };
debugPrint(logger_,
utl::DPL,
"negotiation_runtime",
1,
"legalize() total {:.1f}ms breakdown: "
"initFromDb {:.1f}ms ({:.0f}%), "
"buildGrid {:.1f}ms ({:.0f}%), "
"initFenceRegions {:.1f}ms ({:.0f}%), "
"abacus {:.1f}ms ({:.0f}%), "
"negotiation {:.1f}ms ({:.0f}%), "
"postNegSync {:.1f}ms ({:.0f}%), "
"metrics {:.1f}ms ({:.0f}%), "
"flushToDb {:.1f}ms ({:.0f}%), "
"orientUpdate {:.1f}ms ({:.0f}%)",
to_ms(total_s),
to_ms(init_from_db_s),
pct(init_from_db_s),
to_ms(build_grid_s),
pct(build_grid_s),
to_ms(fence_regions_s),
pct(fence_regions_s),
to_ms(abacus_s),
pct(abacus_s),
to_ms(negotiation_s),
pct(negotiation_s),
to_ms(post_neg_sync_s),
pct(post_neg_sync_s),
to_ms(metrics_s),
pct(metrics_s),
to_ms(flush_s),
pct(flush_s),
to_ms(orient_s),
pct(orient_s));
}
// ===========================================================================
// flushToDb – write current cell positions to ODB so the GUI reflects them
// ===========================================================================
void NegotiationLegalizer::flushToDb()
{
const Grid* dplGrid = opendp_->grid_.get();
for (const auto& cell : cells_) {
if (cell.fixed || cell.db_inst == nullptr) {
continue;
}
const int db_x = die_xlo_ + cell.x * site_width_;
const int db_y = die_ylo_ + dplGrid->gridYToDbu(GridY{cell.y}).v;
cell.db_inst->setPlacementStatus(odb::dbPlacementStatus::PLACED);
cell.db_inst->setLocation(db_x, db_y);
}
}
// ===========================================================================
// pushNegotiationPixels – send grid state to the debug observer for rendering
// ===========================================================================
void NegotiationLegalizer::pushNegotiationPixels()
{
if (!debug_observer_) {
return;
}
std::vector<NegotiationPixelState> pixels(static_cast<size_t>(grid_w_)
* grid_h_);
for (int gy = 0; gy < grid_h_; ++gy) {
for (int gx = 0; gx < grid_w_; ++gx) {
const Pixel& g = gridAt(gx, gy);
const int idx = gy * grid_w_ + gx;
if (g.capacity == 0) {
pixels[idx] = (g.usage > 0) ? NegotiationPixelState::kBlocked
: NegotiationPixelState::kNoRow;
} else if (g.overuse() > 0) {
pixels[idx] = NegotiationPixelState::kOveruse;
} else if (g.usage > 0) {
pixels[idx] = NegotiationPixelState::kOccupied;
} else {
pixels[idx] = NegotiationPixelState::kFree;
}
}
}
// Overlay cells that fail PlacementDRC checks.
if (opendp_->drc_engine_ && network_) {
for (const auto& cell : cells_) {
if (cell.fixed) {
continue;
}
Node* node = network_->getNode(cell.db_inst);
if (node == nullptr) {
continue;
}
if (!opendp_->drc_engine_->checkDRC(
node, GridX{cell.x}, GridY{cell.y}, node->getOrient())) {
for (int dy = 0; dy < cell.height; ++dy) {
for (int gx = cell.x; gx < cell.x + cell.width; ++gx) {
const int pidx = (cell.y + dy) * grid_w_ + gx;
if (pidx >= 0 && pidx < static_cast<int>(pixels.size())) {
pixels[pidx] = NegotiationPixelState::kDrcViolation;
}
}
}
}
}
}
const Grid* dplGrid = opendp_->grid_.get();
std::vector<int> row_y_dbu(grid_h_ + 1);
for (int r = 0; r <= grid_h_; ++r) {
row_y_dbu[r] = dplGrid->gridYToDbu(GridY{r}).v;
}
debug_observer_->setNegotiationPixels(
pixels, grid_w_, grid_h_, die_xlo_, die_ylo_, site_width_, row_y_dbu);
}
void NegotiationLegalizer::debugPause(const std::string& msg)
{
if (!debug_observer_) {
return;
}
setDplPositions();
pushNegotiationPixels();
logger_->report("{}", msg);
debug_observer_->redrawAndPause();
}
// ===========================================================================
// setDplPositions – pass the positions to the DPL original structure (Node)
// ===========================================================================
void NegotiationLegalizer::setDplPositions()
{
if (!network_) {
return;
}
std::unordered_map<odb::dbInst*, Node*> inst_to_node;
inst_to_node.reserve(network_->getNodes().size());
for (const auto& node_ptr : network_->getNodes()) {
if (node_ptr->getDbInst()) {
inst_to_node[node_ptr->getDbInst()] = node_ptr.get();
}
}
for (const auto& cell : cells_) {
if (cell.fixed || cell.db_inst == nullptr) {
continue;
}
auto it = inst_to_node.find(cell.db_inst);
if (it != inst_to_node.end()) {
const int coreX = cell.x * site_width_;
const int coreY = opendp_->grid_->gridYToDbu(GridY{cell.y}).v;
it->second->setLeft(DbuX(coreX));
it->second->setBottom(DbuY(coreY));
it->second->setPlaced(true);
// Update orientation to match the row.
odb::dbSite* site = cell.db_inst->getMaster()->getSite();
if (site != nullptr) {
auto orient = opendp_->grid_->getSiteOrientation(
GridX{cell.x}, GridY{cell.y}, site);
if (orient.has_value()) {
it->second->setOrient(orient.value());
}
}
}
}
}
// ===========================================================================
// Initialisation
// ===========================================================================
bool NegotiationLegalizer::initFromDb()
{
if (db_->getChip() == nullptr || !opendp_ || !opendp_->grid_) {
return false;
}
auto* block = db_->getChip()->getBlock();
if (block == nullptr) {
return false;
}
const Grid* dpl_grid = opendp_->grid_.get();
const odb::Rect core_area = dpl_grid->getCore();
die_xlo_ = core_area.xMin();
die_ylo_ = core_area.yMin();
die_xhi_ = core_area.xMax();
die_yhi_ = core_area.yMax();
// Site width from the DPL grid; row height from the first DB row.
site_width_ = dpl_grid->getSiteWidth().v;
for (auto* row : block->getRows()) {
row_height_ = row->getSite()->getHeight();
break;
}
assert(site_width_ > 0 && row_height_ > 0);
// Grid dimensions from the DPL grid (accounts for actual DB rows).
grid_w_ = dpl_grid->getRowSiteCount().v;
grid_h_ = dpl_grid->getRowCount().v;
// Assign power-rail types from DB row orientations.
// R0/MY = right-side-up → VSS rail at bottom; MX/R180 = flipped → VDD at
// bottom. Rows missing from the DB default to VSS.
row_rail_.clear();
row_rail_.resize(grid_h_, NLPowerRailType::kVss);
for (auto* db_row : block->getRows()) {
const int y_dbu = db_row->getOrigin().y() - die_ylo_;
if (y_dbu < 0 || y_dbu % row_height_ != 0) {
continue;
}
const int r = y_dbu / row_height_;
if (r >= grid_h_) {
continue;
}
const auto orient = db_row->getOrient();
row_rail_[r]
= (orient == odb::dbOrientType::MX || orient == odb::dbOrientType::R180)
? NLPowerRailType::kVdd
: NLPowerRailType::kVss;
}
// Build NegCell records from all placed instances.
cells_.clear();
cells_.reserve(block->getInsts().size());
// Cache region boundaries converted to grid coordinates, keyed by dbRegion*.
struct RegionRectInline
{
int xlo, ylo, xhi, yhi;
};
std::unordered_map<odb::dbRegion*, std::vector<RegionRectInline>>
region_rect_cache;
for (auto* db_inst : block->getInsts()) {
const auto status = db_inst->getPlacementStatus();
if (status == odb::dbPlacementStatus::NONE) {
continue;
}
// Skip non-core-auto-placeable instances (pads, blocks, etc.) — these
// are absent from the Opendp network so DRC/legality checks can't be
// performed on them. They are handled separately by setFixedGridCells().
if (!db_inst->getMaster()->isCoreAutoPlaceable()) {
continue;
}
NegCell cell;
cell.db_inst = db_inst;
cell.fixed = status.isFixed();
int db_x = 0;
int db_y = 0;
db_inst->getLocation(db_x, db_y);
// Snap to grid, findBestLocation() and snapToLegal() iterate over grid
// positions
cell.init_x = dpl_grid->gridX(DbuX{db_x - die_xlo_}).v;
cell.init_y = dpl_grid->gridRoundY(DbuY{db_y - die_ylo_}).v;
// Width/height must be computed before clamping so the upper bounds
// account for the full cell footprint (x + width <= grid_w_, etc.).
auto* master = db_inst->getMaster();
cell.width = std::max(
1,
static_cast<int>(
std::round(static_cast<double>(master->getWidth()) / site_width_)));
cell.height = std::max(
1,
static_cast<int>(std::round(static_cast<double>(master->getHeight())
/ row_height_)));
// Clamp to valid grid range – gridRoundY can return grid_h_ when the
// instance is near the top edge. Use (grid_w_ - width) so the full
// footprint stays within the grid (matches Opendp::legalPt behaviour).
cell.init_x = std::max(0, std::min(cell.init_x, grid_w_ - cell.width));
cell.init_y = std::max(0, std::min(cell.init_y, grid_h_ - cell.height));
cell.x = cell.init_x;
cell.y = cell.init_y;
// gridX() / gridRoundY() are purely arithmetic and don't check whether a
// site actually exists at the computed position. Instances near the chip
// boundary or in sparse-row designs can land on invalid (is_valid=false)
// pixels pixels or on pixels that don't support this cell's site type. Fix
// those with a diamond search from the initial position; we only check site
// validity here, not blockages — the negotiation part handles those.
if (!cell.fixed) {
odb::dbSite* site = master->getSite();
// Check that the full cell footprint (width x height) fits on valid
// sites.
auto isValidSite = [&](int gx, int gy) -> bool {
if (gx < 0 || gx + cell.width > grid_w_ || gy < 0
|| gy + cell.height > grid_h_) {
return false;
}
// Site type check at the anchor row is representative for all rows.
if (site != nullptr
&& !dpl_grid->getSiteOrientation(GridX{gx}, GridY{gy}, site)
.has_value()) {
return false;
}
for (int dy = 0; dy < cell.height; ++dy) {
for (int dx = 0; dx < cell.width; ++dx) {
if (!dpl_grid->pixel(GridY{gy + dy}, GridX{gx + dx}).is_valid) {
return false;
}
}
}
return true;
};
// The snapping here is actually quite similar to the "hopeless" approach
// in original DPL.
// they achieve the same objective, and the previous is more simple,
// consider replacing this.
// For region-constrained cells, collect the region rects in grid
// coordinates so the BFS below can verify containment.
// initFenceRegions() has not run yet, so we read ODB directly.
// Instances reach their region via a GROUP, not via dbInst::region_,
// so we must check both paths.
odb::dbRegion* odb_region = db_inst->getRegion();
if (odb_region == nullptr) {
auto* grp = db_inst->getGroup();
if (grp != nullptr) {
odb_region = grp->getRegion();
}
}
// Look up (or populate) the cache for this region.
const std::vector<RegionRectInline>* region_rects_ptr = nullptr;
if (odb_region != nullptr) {
auto it = region_rect_cache.find(odb_region);
if (it == region_rect_cache.end()) {
std::vector<RegionRectInline> rects;
for (auto* box : odb_region->getBoundaries()) {
RegionRectInline r;
r.xlo = (box->xMin() - die_xlo_) / site_width_;
r.ylo = (box->yMin() - die_ylo_) / row_height_;
r.xhi = (box->xMax() - die_xlo_) / site_width_;
r.yhi = (box->yMax() - die_ylo_) / row_height_;
rects.push_back(r);
}
it = region_rect_cache.emplace(odb_region, std::move(rects)).first;
}
region_rects_ptr = &it->second;
}
// Returns true when (gx,gy) satisfies the region constraint:
// region-constrained cells must land inside their region;
// unconstrained cells have no restriction here (negotiation handles it).
auto isInRegionOk = [&](int gx, int gy) -> bool {
if (region_rects_ptr == nullptr) {
return true;
}
for (const auto& r : *region_rects_ptr) {
if (gx >= r.xlo && gy >= r.ylo && gx + cell.width <= r.xhi
&& gy + cell.height <= r.yhi) {
return true;
}
}
return false;
};
if (!isValidSite(cell.init_x, cell.init_y)
|| !isInRegionOk(cell.init_x, cell.init_y)) {
debugPrint(logger_,
utl::DPL,
"negotiation",
1,
"Instance {} at ({}, {}) snaps to invalid site at "
"({}, {}). Searching for nearest valid site.",
cell.db_inst->getName(),
db_x,
db_y,
die_xlo_ + cell.init_x * site_width_,
die_ylo_ + cell.init_y * row_height_);
// Priority queue keyed on physical Manhattan distance (DBU) so the
// search expands in true physical proximity, not grid-unit proximity.
// One step in X = site_width_ DBU; one step in Y = row_height_ DBU.
using PQEntry = std::tuple<int, int, int>; // physDist, gx, gy
std::
priority_queue<PQEntry, std::vector<PQEntry>, std::greater<PQEntry>>
pq;
std::unordered_set<int> visited;
auto tryEnqueue = [&](int gx, int gy) {
// Leave room for the full cell footprint before enqueueing.
if (gx < 0 || gx + cell.width > grid_w_ || gy < 0
|| gy + cell.height > grid_h_) {
return;
}
if (!visited.insert(gy * grid_w_ + gx).second) {
return;
}
const int dist = std::abs(gx - cell.init_x) * site_width_
+ std::abs(gy - cell.init_y) * row_height_;
pq.emplace(dist, gx, gy);
};
tryEnqueue(cell.init_x, cell.init_y);
constexpr std::array<std::pair<int, int>, 4> kNeighbors{
{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}};
while (!pq.empty()) {
auto [dist, gx, gy] = pq.top();
pq.pop();
if (isValidSite(gx, gy) && isInRegionOk(gx, gy)) {
cell.init_x = gx;
cell.init_y = gy;
cell.x = cell.init_x;
cell.y = cell.init_y;
break;
}
for (auto [ox, oy] : kNeighbors) {
tryEnqueue(gx + ox, gy + oy);
}
}
}
}
// Derive power-rail types directly from the LEF geometry stored by the
// Network — never infer from the cell's current row or orientation.
//
// rail_type = bottom rail in R0 (unflipped) orientation.
// For most CORE cells this is kVss (VSS at bottom).
// rail_type_flipped = bottom rail in MX (flipped) orientation, which
// equals the TOP rail in R0. For most cells: kVdd.
// For symmetric multi-height cells whose VSS appears
// at both top and bottom (e.g. some double-height
// flops): kVss — meaning a flip cannot resolve a
// VDD-bottom row mismatch.
{
int bot_pwr = Architecture::Row::Power_UNK;
int top_pwr = Architecture::Row::Power_UNK;
if (network_ != nullptr) {
if (Master* dpl_master = network_->getMaster(master)) {
bot_pwr = dpl_master->getBottomPowerType();
top_pwr = dpl_master->getTopPowerType();
}
}
auto toRailType = [](int pwr, NLPowerRailType fallback) {
if (pwr == Architecture::Row::Power_VSS) {
return NLPowerRailType::kVss;
}
if (pwr == Architecture::Row::Power_VDD) {
return NLPowerRailType::kVdd;
}
return fallback;
};
cell.rail_type = toRailType(bot_pwr, NLPowerRailType::kVss);
cell.rail_type_flipped = toRailType(top_pwr, NLPowerRailType::kVdd);
}
cell.flippable
= master->getSymmetryX(); // X-symmetry allows vertical flip (MX)
if (cell.height == 1) {
// Consider all single height cells flippable
cell.flippable = true;
}
debugPrint(
logger_,
utl::DPL,
"negotiation",
1,
"DEBUG cell init: {} height={} flippable={} rail_type={} "
"rail_type_flipped={}",
db_inst->getName(),
cell.height,
cell.flippable,
cell.rail_type == NLPowerRailType::kVss ? "kVss" : "kVdd",
cell.rail_type_flipped == NLPowerRailType::kVss ? "kVss" : "kVdd");
if (padding_ != nullptr) {
cell.pad_left = padding_->padLeft(db_inst).v;
cell.pad_right = padding_->padRight(db_inst).v;
}
cells_.push_back(cell);
}
return true;
}
void NegotiationLegalizer::buildGrid()
{
Grid* dplGrid = opendp_->grid_.get();
// Reset all pixels to default negotiation state. Also clear any cell
// and padding pointers (including dummy_cell_ set by groupInitPixels2 for
// region boundaries) — fixed cells and movable cells are re-painted later
// by syncAllCellsToDplGrid() before any DRC check runs.
for (int gy = 0; gy < grid_h_; ++gy) {
for (int gx = 0; gx < grid_w_; ++gx) {
Pixel& pixel = dplGrid->pixel(GridY{gy}, GridX{gx});
pixel.capacity = pixel.is_valid ? 1 : 0;
pixel.usage = 0;
pixel.hist_cost = 1.0;
pixel.cell = nullptr;
pixel.padding_reserved_by = nullptr;
}
}
// Derive per-row existence: a row "has sites" if at least one site
// on that row has capacity > 0.
row_has_sites_.assign(grid_h_, false);
for (int gy = 0; gy < grid_h_; ++gy) {
for (int gx = 0; gx < grid_w_; ++gx) {
if (gridAt(gx, gy).capacity > 0) {
row_has_sites_[gy] = true;
break;
}
}
}
// Mark blockages and record fixed-cell usage in one pass.
// The padded range of fixed cells is also blocked so movable cells
// cannot violate padding constraints relative to fixed instances.
for (const NegCell& cell : cells_) {
if (!cell.fixed) {
continue;
}
const int xBegin = effXBegin(cell);
const int xEnd = effXEnd(cell);
for (int dy = 0; dy < cell.height; ++dy) {
const int gy = cell.y + dy;
for (int gx = xBegin; gx < xEnd; ++gx) {
if (gridExists(gx, gy)) {
gridAt(gx, gy).capacity = 0;
// Physical footprint carries usage=1; padding slots do not.
if (gx >= cell.x && gx < cell.x + cell.width) {
gridAt(gx, gy).usage = 1;
}
}
}
}
}
}
void NegotiationLegalizer::initFenceRegions()
{
fences_.clear(); // Guard against double-population if legalize() is re-run.
auto* block = db_->getChip()->getBlock();
for (auto* region : block->getRegions()) {
FenceRegion fr;
fr.id = region->getId();
for (auto* box : region->getBoundaries()) {
FenceRect r;
r.xlo = (box->xMin() - die_xlo_) / site_width_;
r.ylo = (box->yMin() - die_ylo_) / row_height_;
r.xhi = (box->xMax() - die_xlo_) / site_width_;
r.yhi = (box->yMax() - die_ylo_) / row_height_;
fr.rects.push_back(r);
}
if (!fr.rects.empty()) {
fences_.push_back(std::move(fr));
}
}
// Map each instance to its fence region (if any).
// Instances are assigned to regions via GROUPS in DEF, which sets
// dbInst::group_ but NOT dbInst::region_. We must go through the group.
for (auto& cell : cells_) {
if (cell.db_inst == nullptr) {
continue;
}
// Try direct region first, then group-based region.
odb::dbRegion* region = cell.db_inst->getRegion();
if (region == nullptr) {
auto* grp = cell.db_inst->getGroup();
if (grp != nullptr) {
region = grp->getRegion();
}
}
if (region == nullptr) {
continue;
}
const int rid = region->getId();
for (int fi = 0; fi < static_cast<int>(fences_.size()); ++fi) {
if (fences_[fi].id == rid) {
cell.fence_id = fi;
break;
}
}
}
}
// ===========================================================================
// Grid helpers for Negotiation Legalizer
// ===========================================================================
void NegotiationLegalizer::addUsage(int cell_idx, int delta)
{
const NegCell& cell = cells_[cell_idx];
const int xBegin = effXBegin(cell);
const int xEnd = effXEnd(cell);
for (int dy = 0; dy < cell.height; ++dy) {
const int gy = cell.y + dy;
for (int gx = xBegin; gx < xEnd; ++gx) {
if (gridExists(gx, gy)) {
gridAt(gx, gy).usage += delta;
}
}
}
}
// ===========================================================================
// DPL Grid synchronisation
// ===========================================================================
void NegotiationLegalizer::syncCellToDplGrid(int cell_idx)
{
if (!opendp_ || !opendp_->grid_ || !network_) {
return;
}
const NegCell& neg_cell = cells_[cell_idx];
if (neg_cell.db_inst == nullptr) {
return;
}
Node* node = network_->getNode(neg_cell.db_inst);
if (node == nullptr) {
return;
}
// Update the Node's position to match the NegCell so Grid operations
// (which read Node left/bottom) see the current placement.
node->setLeft(DbuX(neg_cell.x * site_width_));
node->setBottom(DbuY(opendp_->grid_->gridYToDbu(GridY{neg_cell.y}).v));
// Update orientation to match the row.
odb::dbSite* site = neg_cell.db_inst->getMaster()->getSite();
if (site != nullptr) {
auto orient = opendp_->grid_->getSiteOrientation(
GridX{neg_cell.x}, GridY{neg_cell.y}, site);
if (orient.has_value()) {
node->setOrient(orient.value());
}
}
opendp_->grid_->paintPixel(node, GridX{neg_cell.x}, GridY{neg_cell.y});
}
void NegotiationLegalizer::eraseCellFromDplGrid(int cell_idx)
{
if (!opendp_ || !opendp_->grid_ || !network_) {
return;
}
const NegCell& neg_cell = cells_[cell_idx];
if (neg_cell.db_inst == nullptr) {
return;
}
Node* node = network_->getNode(neg_cell.db_inst);
if (node == nullptr) {
return;
}
// Ensure the Node's position matches the current NegCell position so
// erasePixel clears the correct pixels (it reads gridCoveringPadded).
node->setLeft(DbuX(neg_cell.x * site_width_));
node->setBottom(DbuY(opendp_->grid_->gridYToDbu(GridY{neg_cell.y}).v));
opendp_->grid_->erasePixel(node);
}
void NegotiationLegalizer::syncAllCellsToDplGrid()
{
if (!opendp_ || !opendp_->grid_ || !network_) {
return;