MLIR-AIE 1.4.6.dev
AIEPathFinder.h
Go to the documentation of this file.
1//===- AIEPathFinder.h ------------------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2021-2022 Xilinx, Inc.
4// Copyright (C) 2022-2026 Advanced Micro Devices, Inc.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef AIE_PATHFINDER_H
10#define AIE_PATHFINDER_H
11
15
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/BitmaskEnum.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/Hashing.h"
22#include "llvm/ADT/IntEqClasses.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/Support/Error.h"
26#include "llvm/Support/raw_ostream.h"
27
28#include <functional>
29#include <map>
30#include <optional>
31#include <set>
32#include <string>
33#include <tuple>
34#include <vector>
35
36namespace xilinx::AIE {
37
38// A shim's DMA, NOC and PLIO ports reach its switchbox through the shim mux,
39// on the South channel these return for a port that sends or receives.
41int shimMuxChannelTo(Port dst);
42
43// The connections from the source ports to the destination ports of a
44// switchbox's crossbar, if `isCrossbar`, or of the wires from one switchbox to
45// the one at `dstCoords`.
47 // A connection from a source port to a destination port.
48 struct Cell {
49 bool available = false;
50 // weight of Dijkstra's shortest path
51 double demand = 0;
52 // iterations the connection was over capacity
53 int overCapacity = 0;
54 // circuit streams using the connection
55 int usedCapacity = 0;
56 // packet streams using the connection
58 // only packet streams of this group may share the connection
59 int packetGroupId = -1;
60 // packet ids routed through the connection (and its crossbar row and
61 // column), by the flow routing each; it may be shared only among distinct
62 // ids.
63 llvm::SmallDenseMap<int, int, 2> packetIds;
64 // whether a prioritized flow uses the connection
65 bool isPriority = false;
66 // added to the demand, so routes keep off the connection where they can
67 double avoidance = 0;
68 };
69
70 SwitchboxConnect() = default;
71 SwitchboxConnect(TileID coords) : srcCoords(coords), dstCoords(coords) {}
74
76 bool isCrossbar = true;
77 std::vector<Port> srcPorts;
78 std::vector<Port> dstPorts;
79 // The connection from srcPorts[i] to dstPorts[j] is cells[i * dstPorts.size()
80 // + j].
81 std::vector<Cell> cells;
82 // Units of dst ports tied to one arbiter (see planArbiters in
83 // AIECreatePathFindFlows.cpp); a unit's leader lists the packet flows
84 // (indices into the router's flows) leaving by any of its ports
85 llvm::IntEqClasses dstUnits;
86 std::vector<llvm::SmallVector<int, 2>> unitPacketFlows;
87 // source ports the design already gives packet rules, which circuit streams
88 // cannot enter
89 llvm::BitVector packetOnlySrc;
90 // dst ports packet streams may no longer take
91 llvm::BitVector circuitOnlyDst;
92 // TileControl dst ports the control packet overlay drives, which packet
93 // streams may join and circuit streams cannot take
94 llvm::BitVector packetJoinDst;
95
96 Cell &at(size_t i, size_t j) { return cells[i * dstPorts.size() + j]; }
97 const Cell &at(size_t i, size_t j) const {
98 return cells[i * dstPorts.size() + j];
99 }
100
101 // The index of `p` in srcPorts or dstPorts, or -1.
102 int srcIndex(Port p) const { return indexIn(srcPorts, p); }
103 int dstIndex(Port p) const { return indexIn(dstPorts, p); }
104
105 // Size the cells and the per-port state to srcPorts and dstPorts.
106 void resize() {
107 cells.assign(srcPorts.size() * dstPorts.size(), Cell());
108 packetOnlySrc = llvm::BitVector(srcPorts.size());
109 circuitOnlyDst = llvm::BitVector(dstPorts.size());
110 packetJoinDst = llvm::BitVector(dstPorts.size());
111 unitPacketFlows.resize(dstPorts.size());
112 resetUnits();
113 }
114
115 void resetUnits() {
116 dstUnits.clear();
117 dstUnits.grow(dstPorts.size());
118 for (auto &flows : unitPacketFlows)
119 flows.clear();
120 }
121
122 llvm::ArrayRef<int> unitFlows(int j) const {
123 return unitPacketFlows[dstUnits.findLeader(j)];
124 }
125
126 void addToUnit(int j, int flow) {
127 auto &flows = unitPacketFlows[dstUnits.findLeader(j)];
128 if (!llvm::is_contained(flows, flow))
129 flows.push_back(flow);
130 }
131
132 void joinUnits(int j, int k) {
133 j = dstUnits.findLeader(j);
134 k = dstUnits.findLeader(k);
135 if (j == k)
136 return;
137 int leader = dstUnits.join(j, k);
138 int other = leader == j ? k : j;
139 for (int flow : unitPacketFlows[other])
140 addToUnit(leader, flow);
141 unitPacketFlows[other].clear();
142 }
143
144 // update demand at the beginning of each dijkstraShortestPaths iteration
145 void updateDemand();
146
147 // Bumps the demand of the connection from srcPorts[i] to dstPorts[j] if it
148 // is at capacity, all but ruling it out if a prioritized flow uses it, to
149 // keep prioritized flows' routes.
150 void bumpDemand(size_t i, size_t j);
151
152private:
153 static int indexIn(llvm::ArrayRef<Port> ports, Port p) {
154 const Port *it = llvm::find(ports, p);
155 return it == ports.end() ? -1 : it - ports.begin();
156 }
157};
158
160 PathEndPoint() = default;
162
165
166 friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
167 const PathEndPoint &s) {
168 return os << describeTilePort(s.coords, s.port);
169 }
170
171 bool operator<(const PathEndPoint &rhs) const {
172 return std::tie(coords, port) < std::tie(rhs.coords, rhs.port);
173 }
174
175 bool operator==(const PathEndPoint &rhs) const {
176 return std::tie(coords, port) == std::tie(rhs.coords, rhs.port);
177 }
178};
179
180struct Flow {
181 // -1 for a circuit flow.
183 bool isPriorityFlow = false;
185 std::vector<PathEndPoint> dsts;
186 // packet id carried by this flow (nullopt for circuit flows); a channel may
187 // be shared only among distinct ids so same-id flows never merge then fan
188 // out.
189 std::optional<int> packetId;
190};
191
192// A SwitchSetting defines the required settings for a Switchbox for a flow
193// SwitchSetting.srcs is the fanin
194// SwitchSetting.dsts is the fanout
196 SwitchSetting() = default;
197 SwitchSetting(std::vector<Port> srcs) : srcs(std::move(srcs)) {}
198 SwitchSetting(std::vector<Port> srcs, std::vector<Port> dsts)
199 : srcs(std::move(srcs)), dsts(std::move(dsts)) {}
200
201 std::vector<Port> srcs;
202 std::vector<Port> dsts;
203
204 friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
205 const SwitchSetting &s) {
206 os << "{";
207 llvm::interleaveComma(llvm::map_range(s.srcs, describePort), os);
208 os << "} -> {";
209 llvm::interleaveComma(llvm::map_range(s.dsts, describePort), os);
210 return os << "}";
211 }
212
213 bool operator<(const SwitchSetting &rhs) const { return srcs < rhs.srcs; }
214};
215
216using SwitchSettings = std::map<TileID, SwitchSetting>;
217
218inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
219 const SwitchSettings &ss) {
220 os << "\tSwitchSettings: ";
221 for (const auto &[coords, setting] : ss)
222 os << coords << ": " << setting << " | ";
223 return os << "\n";
224}
225
226// A hop of a packet flow's tree, from one port to the next; `joined` when the
227// flow takes it by joining another flow's tree, `isCrossbar` when it crosses a
228// switchbox rather than a wire.
229struct TreeHop {
231 bool joined;
233
234 bool operator==(const TreeHop &rhs) const {
235 return from == rhs.from && to == rhs.to && joined == rhs.joined &&
236 isCrossbar == rhs.isCrossbar;
237 }
238};
239using PacketTrees = std::map<PathEndPoint, std::vector<TreeHop>>;
240
241// Whether packet flows from the two sources, with ids among the two sets, can
242// deadlock if they share an arbiter; see StreamConflicts::conflict.
244 std::function<bool(const PathEndPoint &, const std::set<int> &,
245 const PathEndPoint &, const std::set<int> &)>;
246
247// Described packet streams, and why the first two conflict.
249 std::vector<std::string> flows;
250 std::string why;
251};
252// The most pairwise-conflicting packet streams found crossing from the tiles
253// `low` holds to the others if `up` (else back), searching no further than
254// `limit` + 1; see Pathfinder::cutOverflow.
255using PacketsApartAcross = std::function<PacketsApart(
256 llvm::function_ref<bool(TileID)> low, bool up, size_t limit)>;
257
258// Packets `src` sends with ids `a` and `b` share a master port they leave
259// tile `at` by, which puts them on one arbiter. If `apart` is set, the
260// packets with id `b` for that destination on the tile reach it by a slave
261// port of their own instead.
262struct TreeSplit {
265 int a, b;
266 std::optional<PathEndPoint> apart;
267
268 bool operator<(const TreeSplit &rhs) const {
269 return std::tie(src, at, a, b, apart) <
270 std::tie(rhs.src, rhs.at, rhs.a, rhs.b, rhs.apart);
271 }
272};
273
274// What makes a routing unusable: switchbox connections to move, and where a
275// source's tree has to branch, and crowded tiles (see Pathfinder::relax).
277 std::vector<std::pair<TileID, Connect>> connections;
278 std::vector<TreeSplit> splits;
279 std::vector<TileID> crowded;
280 // Sources whose packet flows the routing put on one arbiter or link in a
281 // hold cycle, to keep apart like conflicting ones from then on.
282 std::vector<std::pair<PathEndPoint, PathEndPoint>> apart;
283 // Sources whose packet flows wait on each other at receivers they share
284 // in a hold cycle, so their trees should meet: each routes the ids the
285 // other does not send as a part of their own from then on.
286 std::vector<std::pair<PathEndPoint, PathEndPoint>> together;
287 // Sources whose tree waits on an arbiter it holds itself; they stop
288 // trunking (see RouteState::trunked).
289 std::vector<PathEndPoint> untrunk;
290 // Whether every rejected connection would change a pinned master set.
292};
293
294// A routing findPaths found.
295struct Routing {
296 // The switch settings of each source's flows.
297 std::map<PathEndPoint, SwitchSettings> settings;
298 // The packet flows' trees, by source.
300 // The switch settings of the packets a source sends with an id, where they
301 // are routed apart from the others the source sends.
302 std::map<std::pair<PathEndPoint, int>, SwitchSettings> idSettings;
303};
304
305// How the router's message starts when the flows do not fit the links.
306inline constexpr llvm::StringLiteral kNoLegalRouting =
307 "Unable to find a legal routing";
308
309// Why no legal routing was found, reported at `loc`, or the device if unset,
310// with `reason` if the router can say. A routing check's failure also names
311// the faults the router has to move.
312class RoutingFailure : public llvm::ErrorInfo<RoutingFailure> {
313public:
314 static char ID;
315
316 explicit RoutingFailure(std::string reason, RoutingFaults faults = {},
317 std::optional<mlir::Location> loc = std::nullopt)
318 : reason(std::move(reason)), faults(std::move(faults)), loc(loc) {}
319
320 void log(llvm::raw_ostream &os) const override;
321 std::error_code convertToErrorCode() const override {
322 return llvm::inconvertibleErrorCode();
323 }
324
325 // Another failure of this error's own dynamic type, naming `reason`,
326 // `faults` and `loc`: how the replay ladder reconstructs a kept attempt's
327 // failure from its stored fields without a classID switch at each site
328 // that needs one.
329 virtual std::unique_ptr<RoutingFailure>
331 std::optional<mlir::Location> loc) const {
332 return std::make_unique<RoutingFailure>(std::move(reason),
333 std::move(faults), loc);
334 }
335
336 std::string reason;
338 std::optional<mlir::Location> loc;
339};
340
341// A routing that can deadlock only where allow-deadlock-prone lets it: usable,
342// though the router would rather move the faults it names.
344 : public llvm::ErrorInfo<DeadlockProneRouting, RoutingFailure> {
345public:
346 static char ID;
347 using ErrorInfo::ErrorInfo;
348 std::unique_ptr<RoutingFailure>
349 clone(std::string reason, RoutingFaults faults,
350 std::optional<mlir::Location> loc) const override {
351 return std::make_unique<DeadlockProneRouting>(std::move(reason),
352 std::move(faults), loc);
353 }
354};
355
356// No legal routing around the routes prioritized flows keep, which the reason
357// already blames.
359 : public llvm::ErrorInfo<PinnedRoutingFailure, RoutingFailure> {
360public:
361 static char ID;
362 using ErrorInfo::ErrorInfo;
363 std::unique_ptr<RoutingFailure>
364 clone(std::string reason, RoutingFaults faults,
365 std::optional<mlir::Location> loc) const override {
366 return std::make_unique<PinnedRoutingFailure>(std::move(reason),
367 std::move(faults), loc);
368 }
369};
370
371// Checks a routing that fits the fabric: a RoutingFailure if it is unusable,
372// success if it is accepted.
373using RoutingCheck = std::function<llvm::Error(const Routing &)>;
374
375// What packet flows are routed under.
377 // Routings the check rejects count as illegal; the connections it names
378 // are penalized like overused channels so later iterations avoid them, and
379 // the trees it splits branch where it says from then on. A routing it
380 // rejects as a DeadlockProneRouting is kept, and found if no better one is
381 // soon.
383 // Packet flows that conflict are steered off each other's master ports; see
384 // edgeWeight.
387 // The prioritized packet flows from these sources take these trees
388 // instead of being routed.
390 // The packet ids each pinned tree carries. A pinned source's other flows
391 // route with the rest of the design, prioritized or not.
392 std::map<PathEndPoint, std::set<int>> pinnedIds;
393 // Whether prioritized packet flows not pinned route first, keeping
394 // other flows off their channels; otherwise they route like the others.
395 bool prioritize = true;
396};
397
398// The relax settings an attempt reads while it routes (see Pathfinder::relax).
399enum class Relax : uint8_t {
400 None = 0,
401 IdsApart = 1 << 0,
402 SplitShared = 1 << 1,
403 // Trees that share destinations no longer meet (see TreeBuilder::meet), so
404 // what is left of their hazard is a hold cycle through those receivers.
405 MeetApart = 1 << 2,
406 // A flow meets another id's tree ahead of a same-id partner that has not
407 // routed yet (see Pathfinder::meetAhead).
409 LLVM_MARK_AS_BITMASK_ENUM(MeetAheadOfPartners)
410};
412
413// What one attempt of a relax ladder read that a relax step changes, and what
414// it found. A later attempt of the ladder that reads the same replays it
415// exactly, as routing is deterministic and the ladder's constraints are fixed.
417 std::vector<Flow> flows;
418 std::vector<llvm::BitVector> circuitOnly;
419 // The settings' values, and which of them the attempt read.
421 // The routing found, else the failure: a clone of it (so reconstructing a
422 // replay's failure needs no classID switch, just prototype->clone()) and
423 // its contents.
424 std::optional<Routing> routing;
425 std::unique_ptr<RoutingFailure> prototype;
426 std::string reason;
428 std::optional<mlir::Location> loc;
429 // What relax reads after the attempt.
430 llvm::DenseSet<TileID> crowdedTiles;
431 bool packetsFailed = false;
432 std::string checkReason;
433 // Each iteration's routing, kept under -aie-pathfinder-verify-replays.
434 std::vector<llvm::hash_code> trajectory;
435};
436
437// The boundary the wires from tile `a` to its neighbour `b` cross: between
438// rows (else columns) `below` and the next, upward (else back).
439std::tuple<bool, int, bool> boundaryOf(TileID a, TileID b);
440
441// Congestion-negotiated routing: each iteration routes every flow by
442// Dijkstra, given each connection's demand, and raises the demand of the
443// connections used over capacity, until no connection is.
445public:
446 void initialize(int maxCol, int maxRow, const AIETargetModel &targetModel);
447 // Adds a flow from `src` to `dst`; failures to route it are reported at
448 // `loc` when given.
449 void addFlow(TileID srcCoords, Port srcPort, TileID dstCoords, Port dstPort,
450 std::optional<int> packetId, bool isPriorityFlow,
451 std::optional<mlir::Location> loc = std::nullopt);
452 void sortFlows();
453 // Reserves the connections `switchboxOp` already makes, so routing avoids
454 // them. Fails if it makes one the switchbox cannot.
455 mlir::LogicalResult addFixedConnection(SwitchboxOp switchboxOp);
456 // Keeps routes out of the switchbox at `coords`.
457 void excludeTile(TileID coords);
458 // Keeps routes off an output port of a switchbox where another is free.
459 void avoidPort(TileID coords, Port port);
460 // A RoutingFailure if no legal routing is found in `maxIterations`. An
461 // attempt that replays one in `attempts` returns what that one found.
462 llvm::Expected<Routing> findPaths(int maxIterations);
463 // The attempts of the relax ladder being routed, if the caller keeps them;
464 // it routes one design under one set of constraints meanwhile.
465 std::vector<PathfinderAttempt> *attempts = nullptr;
466 void setPacketConstraints(PacketConstraints c) { constraints = std::move(c); }
467 // Loosens the packet constraints by one step after findPaths found no
468 // routing; false once no step is left or no packet stream took part in the
469 // failure. Packet flows start sharing channels only within their
470 // destination group. The steps, each skipped if it changes nothing: share
471 // channels with any packet flow; cap the fan-out of tiles the routing check
472 // found out of packet rules or msels to packetFanoutCap channels per
473 // direction; route the second id of an unbranchable split apart, which
474 // restarts sharing and caps; then share and cap again; route the ids a
475 // source sends that a source it must keep apart from does not as a part of
476 // their own, which restarts sharing and caps; then share and cap again;
477 // route each other source of a cluster that has to meet first, one per
478 // attempt (see rotateLeads); meet ahead of same-id partners; then stop
479 // meeting, which runs the steps before rotating again.
480 bool relax();
481
482private:
483 // A directed edge in the dense routing graph: from some node to node `dst`,
484 // realized by cell (i, j) of `sb`. `sb` points into `graph`, so demand reads
485 // always see the current iteration's weights.
486 struct Edge {
487 int dst;
489 int i;
490 int j;
491 };
492
493 // A `Port` is (bundle, channel) with no direction, so one dense node stands
494 // for both a switchbox port's input side and its output side. Dijkstra
495 // therefore searches over states, not nodes: a state is a node paired with
496 // the side of that port the stream is currently on. A stream enters a
497 // switchbox on an input port, crosses the crossbar once to an output port,
498 // and then rides the wire to the neighbour's input port -- so In only ever
499 // takes intra-switchbox edges and Out only ever takes inter-switchbox ones.
500 // Without the split, Dijkstra can chain two crossbar hops through one port
501 // and turn the stream around inside a switchbox; the settings it emits then
502 // dead-end and AIECreatePathFindFlows reports the flow as unroutable.
503 enum PortSide : int { In = 0, Out = 1 };
504 static int stateId(int nodeId, PortSide side) { return 2 * nodeId + side; }
505 static int stateNode(int state) { return state >> 1; }
506
507 // Build the dense integer node numbering and per-node adjacency from `graph`
508 // and `flows`. Topology is fixed across congestion iterations, so this runs
509 // once. A node's crossbar edges come before its wire edges, each in the order
510 // of the PathEndPoints they reach, so Dijkstra breaks ties the same way every
511 // run.
512 void buildRoutingGraph();
513
514 // The cost of taking `e`, as dijkstraShortestPaths weighs it.
515 double edgeWeight(const Edge &e, std::optional<int> packetId,
516 const llvm::BitVector *avoid,
517 const llvm::BitVector *avoidBranch) const;
518
519 // Dijkstra over the dense graph from the states in `seeds`, each starting at
520 // its cost in `seedCosts`. Fills `preds` (predecessor state id, or -1) and
521 // `predEdge` (the edge taken to reach each state). Reuses the scratch buffers
522 // below. Each edge costs its edgeWeight given `packetId`, `avoid` and, from a
523 // state in `branchAvoid`, the flows it maps to. States in `stops` are reached
524 // but not left, and a crossbar hop is taken only if `mayCross` allows it. The
525 // search ends once every state in `targets` is settled; only their `distance`
526 // and paths are final then.
527 void dijkstraShortestPaths(
528 llvm::ArrayRef<int> seeds, llvm::ArrayRef<double> seedCosts,
529 std::optional<int> packetId, const llvm::BitVector *avoid = nullptr,
530 const llvm::DenseMap<int, llvm::BitVector> *branchAvoid = nullptr,
531 const llvm::DenseSet<int> *stops = nullptr,
532 llvm::ArrayRef<int> targets = {},
533 llvm::function_ref<bool(int, int)> mayCross = nullptr);
534
535 struct RouteState;
536 struct TreeBuilder;
537 // Route `flow`'s tree around those routed before it this iteration. A
538 // RoutingFailure if it reaches no path to a destination.
539 llvm::Error routePart(RouteState &st, int flow);
540 // findPaths' iterations, once it has set the graph up; each routing's hash
541 // goes to `trajectory` if given.
542 llvm::Expected<Routing> negotiate(int maxIterations,
543 std::vector<llvm::hash_code> *trajectory);
544 // Steer the next iteration away from what the routing check faulted.
545 // Returns the illegal edges the faults count as; `pinnedOnly` counts those
546 // of them that are connections only pinned trees take, which no penalty
547 // moves.
548 int applyRoutingFaults(RouteState &st, const RoutingFaults &faults,
549 int &pinnedOnly);
550 // A RoutingFailure saying why the last iteration's routing does not fit.
551 llvm::Error explainNoRouting(const RouteState &st) const;
552 // A RoutingFailure if the flows crossing some row or column boundary need
553 // more channels across it than it has, however they are routed.
554 llvm::Error cutOverflow() const;
555 bool hasRoom(const SwitchboxConnect &sb) const;
556 // The steps of relax.
557 bool shareAllChannels();
558 bool capCrowdedFanOut();
559 bool routeIdsApart();
560 bool splitSharedIds();
561 bool stopMeeting();
562 bool rotateLeads();
563 bool meetAhead();
564
565 // Flows to be routed
566 std::vector<Flow> flows;
567 // The packet ids each source sends each destination.
568 std::map<std::pair<PathEndPoint, PathEndPoint>, llvm::SmallVector<int, 2>>
569 packetIdsTo;
570 // The packet ids each source sends, to any destination.
571 std::map<PathEndPoint, std::set<int>> idsBySource() const;
572 // The packet ids each source sends in prioritized flows.
573 std::map<PathEndPoint, std::set<int>> priorityIds;
574 // Where each source's flow to each destination was declared.
575 std::map<PathEndPoint, std::map<PathEndPoint, mlir::Location>> flowLocs;
576 std::optional<mlir::Location> flowLoc(const PathEndPoint &src,
577 const PathEndPoint *dst) const;
578 // The routing graph, by the tiles a SwitchboxConnect connects and whether it
579 // is a crossbar: a tile to itself for its switchbox, or to a neighbour for
580 // the wires between them.
581 using GraphKey = std::tuple<TileID, TileID, bool>;
582 static GraphKey crossbarKey(TileID tile) { return {tile, tile, true}; }
583 static GraphKey wireKey(TileID src, TileID dst) { return {src, dst, false}; }
584 std::map<GraphKey, SwitchboxConnect> graph;
585
586 // Dense routing graph (built once by buildRoutingGraph()).
587 bool graphBuilt = false;
588 std::map<PathEndPoint, int> nodeIds; // PathEndPoint -> dense id
589 std::vector<PathEndPoint> nodes; // dense id -> PathEndPoint
590 std::vector<std::vector<Edge>> adjacency; // dense id -> out-edges
591 std::vector<size_t> wireEdgesBegin; // dense id -> first wire edge
592
593 // Dijkstra scratch, indexed by state id (2 * nodes.size()) and reused across
594 // calls.
595 std::vector<double> distance;
596 std::vector<uint64_t> indexInHeap;
597 std::vector<int8_t> colors;
598 std::vector<int> preds;
599 std::vector<Edge> predEdge;
600
601 int getOrAddNodeId(const PathEndPoint &pep);
602
603 PacketConstraints constraints;
604 // Why the routing check rejected the last routing it rejected.
605 std::string checkReason;
606 // Whether packet streams took part in the last failure: the routing check
607 // rejected a routing, or packet streams cross a link left overused, or the
608 // boundary it crosses.
609 bool packetsFailed = true;
610 bool shareChannels = false;
611 Relax settings = Relax::None;
612 // Whether a tree met another in any attempt, so stopping meeting can change
613 // anything.
614 bool treesMet = false;
615 // The device's columns and rows; the graph has tiles one past each.
616 int columns = 0, rows = 0;
617 size_t relaxStep = 0;
618 // The sources that route first among those that have to meet, and how many
619 // turns of rotateLeads they have taken.
620 std::set<PathEndPoint> leads;
621 size_t leadStep = 0;
622 llvm::DenseSet<TileID> crowdedTiles, cappedTiles;
623 // The relax settings this attempt read; sortFlows and findPaths fold in
624 // the others (shareChannels, leads, cappedTiles) before it routes.
625 Relax consulted = Relax::None;
626 // Whether `setting` is on, noting that this attempt read it.
627 bool consult(Relax setting) {
628 consulted |= setting;
629 return any(settings & setting);
630 }
631};
632
633// Routes the flows of a device with a Pathfinder, and finds or creates the
634// tiles, switchboxes and shim muxes the routing is lowered onto.
636public:
637 // A RoutingFailure if the flows in `device` have no legal routing.
638 llvm::Error runAnalysis(DeviceOp &device);
639
640 int getMaxCol() const { return maxCol; }
641 int getMaxRow() const { return maxRow; }
642
643 TileOp getTile(mlir::OpBuilder &builder, int col, int row);
644 TileOp getTile(mlir::OpBuilder &builder, const TileID &tileId);
645 SwitchboxOp getSwitchbox(mlir::OpBuilder &builder, int col, int row);
646 ShimMuxOp getShimMux(mlir::OpBuilder &builder, int col);
647
648 // The ops at `tile` the analysis has found or created, or null.
649 TileOp lookupTile(TileID tile) const { return coordToTile.lookup(tile); }
650 SwitchboxOp lookupSwitchbox(TileID tile) const {
651 return coordToSwitchbox.lookup(tile);
652 }
653 ShimMuxOp lookupShimMux(int col) const {
654 return coordToShimMux.lookup({col, 0});
655 }
656
658 // Passed to Pathfinder::avoidPort.
659 std::vector<std::pair<TileID, Port>> avoidedPorts;
660 // The routing runAnalysis found.
662 // The sources of the circuit flows lowered so far.
663 std::set<PathEndPoint> processedFlows;
664
665private:
666 // how long until declared unroutable
667 static constexpr int maxIterations = 1000;
668
669 int maxCol = 0, maxRow = 0;
670 llvm::DenseMap<TileID, TileOp> coordToTile;
671 llvm::DenseMap<TileID, SwitchboxOp> coordToSwitchbox;
672 llvm::DenseMap<TileID, ShimMuxOp> coordToShimMux;
673};
674
675} // namespace xilinx::AIE
676
677#endif
std::unique_ptr< RoutingFailure > clone(std::string reason, RoutingFaults faults, std::optional< mlir::Location > loc) const override
ShimMuxOp getShimMux(mlir::OpBuilder &builder, int col)
SwitchboxOp getSwitchbox(mlir::OpBuilder &builder, int col, int row)
SwitchboxOp lookupSwitchbox(TileID tile) const
TileOp getTile(mlir::OpBuilder &builder, const TileID &tileId)
TileOp lookupTile(TileID tile) const
TileOp getTile(mlir::OpBuilder &builder, int col, int row)
llvm::Error runAnalysis(DeviceOp &device)
std::set< PathEndPoint > processedFlows
ShimMuxOp lookupShimMux(int col) const
std::vector< std::pair< TileID, Port > > avoidedPorts
void avoidPort(TileID coords, Port port)
std::vector< PathfinderAttempt > * attempts
llvm::Expected< Routing > findPaths(int maxIterations)
void setPacketConstraints(PacketConstraints c)
void excludeTile(TileID coords)
void addFlow(TileID srcCoords, Port srcPort, TileID dstCoords, Port dstPort, std::optional< int > packetId, bool isPriorityFlow, std::optional< mlir::Location > loc=std::nullopt)
void initialize(int maxCol, int maxRow, const AIETargetModel &targetModel)
mlir::LogicalResult addFixedConnection(SwitchboxOp switchboxOp)
std::unique_ptr< RoutingFailure > clone(std::string reason, RoutingFaults faults, std::optional< mlir::Location > loc) const override
void log(llvm::raw_ostream &os) const override
RoutingFailure(std::string reason, RoutingFaults faults={}, std::optional< mlir::Location > loc=std::nullopt)
std::optional< mlir::Location > loc
virtual std::unique_ptr< RoutingFailure > clone(std::string reason, RoutingFaults faults, std::optional< mlir::Location > loc) const
std::error_code convertToErrorCode() const override
std::function< llvm::Error(const Routing &)> RoutingCheck
int shimMuxChannelTo(Port dst)
struct TileID { friend std::ostream &operator<<(std::ostream &os, const TileID &s) { os<< "TileID("<< s.col<< ", "<< s.row<< ")"; return os; } friend std::string to_string(const TileID &s) { std::ostringstream ss; ss<< s; return ss.str(); } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const TileID &s) { os<< to_string(s); return os; } inline bool operator<(const TileID &rhs) const { return std::tie(col, row)< std::tie(rhs.col, rhs.row); } bool operator==(const TileID &rhs) const { return std::tie(col, row)==std::tie(rhs.col, rhs.row); } bool operator!=(const TileID &rhs) const { return !(*this==rhs);} int col, row;} TileID
std::function< bool(const PathEndPoint &, const std::set< int > &, const PathEndPoint &, const std::set< int > &)> PacketConflict
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const SwitchSettings &ss)
std::tuple< bool, int, bool > boundaryOf(TileID a, TileID b)
std::function< PacketsApart( llvm::function_ref< bool(TileID)> low, bool up, size_t limit)> PacketsApartAcross
int shimMuxChannelFrom(Port src)
std::string describeTilePort(TileID tile, Port port)
Names a tile port the way diagnostics do, e.g. "(0, 2) DMA:1".
struct Port { WireBundle bundle; int channel; bool operator==(const Port &rhs) const { return std::tie(bundle, channel)==std::tie(rhs.bundle, rhs.channel); } bool operator!=(const Port &rhs) const { return !(*this==rhs);} bool operator<(const Port &rhs) const { return std::tie(bundle, channel)< std::tie(rhs.bundle, rhs.channel); } friend std::ostream &operator<<(std::ostream &os, const Port &port) { os<< "("; os<< stringifyWireBundle(port.bundle).str(); os<< ": "<< std::to_string(port.channel)<< ")"; return os; } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const Port &port) { os<< to_string(port); return os; } } Port
Definition AIEDialect.h:265
LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE()
std::map< TileID, SwitchSetting > SwitchSettings
constexpr llvm::StringLiteral kNoLegalRouting
std::string describePort(Port port)
Names a port the way diagnostics do, e.g. "DMA:1".
std::map< PathEndPoint, std::vector< TreeHop > > PacketTrees
std::vector< PathEndPoint > dsts
std::optional< int > packetId
std::map< PathEndPoint, std::set< int > > pinnedIds
std::vector< std::string > flows
PathEndPoint(TileID coords, Port port)
bool operator==(const PathEndPoint &rhs) const
friend llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const PathEndPoint &s)
bool operator<(const PathEndPoint &rhs) const
std::optional< mlir::Location > loc
std::vector< llvm::BitVector > circuitOnly
std::vector< llvm::hash_code > trajectory
std::unique_ptr< RoutingFailure > prototype
llvm::DenseSet< TileID > crowdedTiles
std::optional< Routing > routing
std::vector< std::pair< TileID, Connect > > connections
std::vector< PathEndPoint > untrunk
std::vector< std::pair< PathEndPoint, PathEndPoint > > together
std::vector< TreeSplit > splits
std::vector< TileID > crowded
std::vector< std::pair< PathEndPoint, PathEndPoint > > apart
std::map< PathEndPoint, SwitchSettings > settings
std::map< std::pair< PathEndPoint, int >, SwitchSettings > idSettings
std::vector< Port > dsts
bool operator<(const SwitchSetting &rhs) const
friend llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const SwitchSetting &s)
SwitchSetting(std::vector< Port > srcs)
SwitchSetting(std::vector< Port > srcs, std::vector< Port > dsts)
std::vector< Port > srcs
llvm::SmallDenseMap< int, int, 2 > packetIds
llvm::IntEqClasses dstUnits
llvm::ArrayRef< int > unitFlows(int j) const
std::vector< Port > dstPorts
std::vector< Port > srcPorts
std::vector< llvm::SmallVector< int, 2 > > unitPacketFlows
SwitchboxConnect(TileID srcCoords, TileID dstCoords)
void addToUnit(int j, int flow)
Cell & at(size_t i, size_t j)
void bumpDemand(size_t i, size_t j)
std::vector< Cell > cells
const Cell & at(size_t i, size_t j) const
bool operator==(const TreeHop &rhs) const
std::optional< PathEndPoint > apart
bool operator<(const TreeSplit &rhs) const