1 //===-- RegAllocPBQP.h ------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the PBQPBuilder interface, for classes which build PBQP
11 // instances to represent register allocation problems, and the RegAllocPBQP
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CODEGEN_REGALLOCPBQP_H
17 #define LLVM_CODEGEN_REGALLOCPBQP_H
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/PBQP/CostAllocator.h"
21 #include "llvm/CodeGen/PBQP/ReductionRules.h"
22 #include "llvm/CodeGen/PBQPRAConstraint.h"
23 #include "llvm/Support/ErrorHandling.h"
32 /// @brief Spill option index.
33 inline unsigned getSpillOptionIdx() { return 0; }
35 /// \brief Metadata to speed allocatability test.
37 /// Keeps track of the number of infinities in each row and column.
38 class MatrixMetadata {
40 MatrixMetadata(const MatrixMetadata&);
41 void operator=(const MatrixMetadata&);
43 MatrixMetadata(const Matrix& M)
44 : WorstRow(0), WorstCol(0),
45 UnsafeRows(new bool[M.getRows() - 1]()),
46 UnsafeCols(new bool[M.getCols() - 1]()) {
48 unsigned* ColCounts = new unsigned[M.getCols() - 1]();
50 for (unsigned i = 1; i < M.getRows(); ++i) {
51 unsigned RowCount = 0;
52 for (unsigned j = 1; j < M.getCols(); ++j) {
53 if (M[i][j] == std::numeric_limits<PBQPNum>::infinity()) {
56 UnsafeRows[i - 1] = true;
57 UnsafeCols[j - 1] = true;
60 WorstRow = std::max(WorstRow, RowCount);
62 unsigned WorstColCountForCurRow =
63 *std::max_element(ColCounts, ColCounts + M.getCols() - 1);
64 WorstCol = std::max(WorstCol, WorstColCountForCurRow);
68 unsigned getWorstRow() const { return WorstRow; }
69 unsigned getWorstCol() const { return WorstCol; }
70 const bool* getUnsafeRows() const { return UnsafeRows.get(); }
71 const bool* getUnsafeCols() const { return UnsafeCols.get(); }
74 unsigned WorstRow, WorstCol;
75 std::unique_ptr<bool[]> UnsafeRows;
76 std::unique_ptr<bool[]> UnsafeCols;
79 /// \brief Holds a vector of the allowed physical regs for a vreg.
80 class AllowedRegVector {
81 friend hash_code hash_value(const AllowedRegVector &);
84 AllowedRegVector() : NumOpts(0), Opts(nullptr) {}
86 AllowedRegVector(const std::vector<unsigned> &OptVec)
87 : NumOpts(OptVec.size()), Opts(new unsigned[NumOpts]) {
88 std::copy(OptVec.begin(), OptVec.end(), Opts.get());
91 AllowedRegVector(const AllowedRegVector &Other)
92 : NumOpts(Other.NumOpts), Opts(new unsigned[NumOpts]) {
93 std::copy(Other.Opts.get(), Other.Opts.get() + NumOpts, Opts.get());
96 AllowedRegVector(AllowedRegVector &&Other)
97 : NumOpts(std::move(Other.NumOpts)), Opts(std::move(Other.Opts)) {}
99 AllowedRegVector& operator=(const AllowedRegVector &Other) {
100 NumOpts = Other.NumOpts;
101 Opts.reset(new unsigned[NumOpts]);
102 std::copy(Other.Opts.get(), Other.Opts.get() + NumOpts, Opts.get());
106 AllowedRegVector& operator=(AllowedRegVector &&Other) {
107 NumOpts = std::move(Other.NumOpts);
108 Opts = std::move(Other.Opts);
112 unsigned size() const { return NumOpts; }
113 unsigned operator[](size_t I) const { return Opts[I]; }
115 bool operator==(const AllowedRegVector &Other) const {
116 if (NumOpts != Other.NumOpts)
118 return std::equal(Opts.get(), Opts.get() + NumOpts, Other.Opts.get());
121 bool operator!=(const AllowedRegVector &Other) const {
122 return !(*this == Other);
127 std::unique_ptr<unsigned[]> Opts;
130 inline hash_code hash_value(const AllowedRegVector &OptRegs) {
131 unsigned *OStart = OptRegs.Opts.get();
132 unsigned *OEnd = OptRegs.Opts.get() + OptRegs.NumOpts;
133 return hash_combine(OptRegs.NumOpts,
134 hash_combine_range(OStart, OEnd));
137 /// \brief Holds graph-level metadata relevent to PBQP RA problems.
138 class GraphMetadata {
140 typedef ValuePool<AllowedRegVector> AllowedRegVecPool;
143 typedef AllowedRegVecPool::PoolRef AllowedRegVecRef;
145 GraphMetadata(MachineFunction &MF,
147 MachineBlockFrequencyInfo &MBFI)
148 : MF(MF), LIS(LIS), MBFI(MBFI) {}
152 MachineBlockFrequencyInfo &MBFI;
154 void setNodeIdForVReg(unsigned VReg, GraphBase::NodeId NId) {
155 VRegToNodeId[VReg] = NId;
158 GraphBase::NodeId getNodeIdForVReg(unsigned VReg) const {
159 auto VRegItr = VRegToNodeId.find(VReg);
160 if (VRegItr == VRegToNodeId.end())
161 return GraphBase::invalidNodeId();
162 return VRegItr->second;
165 void eraseNodeIdForVReg(unsigned VReg) {
166 VRegToNodeId.erase(VReg);
169 AllowedRegVecRef getAllowedRegs(AllowedRegVector Allowed) {
170 return AllowedRegVecs.getValue(std::move(Allowed));
174 DenseMap<unsigned, GraphBase::NodeId> VRegToNodeId;
175 AllowedRegVecPool AllowedRegVecs;
178 /// \brief Holds solver state and other metadata relevant to each PBQP RA node.
181 typedef RegAlloc::AllowedRegVector AllowedRegVector;
183 // The node's reduction state. The order in this enum is important,
184 // as it is assumed nodes can only progress up (i.e. towards being
185 // optimally reducible) when reducing the graph.
188 NotProvablyAllocatable,
189 ConservativelyAllocatable,
194 : RS(Unprocessed), NumOpts(0), DeniedOpts(0), OptUnsafeEdges(nullptr),
195 VReg(0), everConservativelyAllocatable(false) {}
197 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
198 // MSVC synthesizes move constructors properly.
199 NodeMetadata(const NodeMetadata &Other)
200 : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
201 OptUnsafeEdges(new unsigned[NumOpts]), VReg(Other.VReg),
202 AllowedRegs(Other.AllowedRegs) {
204 std::copy(&Other.OptUnsafeEdges[0], &Other.OptUnsafeEdges[NumOpts],
209 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
210 // MSVC synthesizes move constructors properly.
211 NodeMetadata(NodeMetadata &&Other)
212 : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
213 OptUnsafeEdges(std::move(Other.OptUnsafeEdges)), VReg(Other.VReg),
214 AllowedRegs(std::move(Other.AllowedRegs)) {}
216 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
217 // MSVC synthesizes move constructors properly.
218 NodeMetadata& operator=(const NodeMetadata &Other) {
220 NumOpts = Other.NumOpts;
221 DeniedOpts = Other.DeniedOpts;
222 OptUnsafeEdges.reset(new unsigned[NumOpts]);
223 std::copy(Other.OptUnsafeEdges.get(), Other.OptUnsafeEdges.get() + NumOpts,
224 OptUnsafeEdges.get());
226 AllowedRegs = Other.AllowedRegs;
230 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
231 // MSVC synthesizes move constructors properly.
232 NodeMetadata& operator=(NodeMetadata &&Other) {
234 NumOpts = Other.NumOpts;
235 DeniedOpts = Other.DeniedOpts;
236 OptUnsafeEdges = std::move(Other.OptUnsafeEdges);
238 AllowedRegs = std::move(Other.AllowedRegs);
242 void setVReg(unsigned VReg) { this->VReg = VReg; }
243 unsigned getVReg() const { return VReg; }
245 void setAllowedRegs(GraphMetadata::AllowedRegVecRef AllowedRegs) {
246 this->AllowedRegs = std::move(AllowedRegs);
248 const AllowedRegVector& getAllowedRegs() const { return *AllowedRegs; }
250 void setup(const Vector& Costs) {
251 NumOpts = Costs.getLength() - 1;
252 OptUnsafeEdges = std::unique_ptr<unsigned[]>(new unsigned[NumOpts]());
255 ReductionState getReductionState() const { return RS; }
256 void setReductionState(ReductionState RS) {
257 assert(RS >= this->RS && "A node's reduction state can not be downgraded");
260 // Remember this state to assert later that a non-infinite register
261 // option was available.
262 if (RS == ConservativelyAllocatable)
263 everConservativelyAllocatable = true;
267 void handleAddEdge(const MatrixMetadata& MD, bool Transpose) {
268 DeniedOpts += Transpose ? MD.getWorstRow() : MD.getWorstCol();
269 const bool* UnsafeOpts =
270 Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
271 for (unsigned i = 0; i < NumOpts; ++i)
272 OptUnsafeEdges[i] += UnsafeOpts[i];
275 void handleRemoveEdge(const MatrixMetadata& MD, bool Transpose) {
276 DeniedOpts -= Transpose ? MD.getWorstRow() : MD.getWorstCol();
277 const bool* UnsafeOpts =
278 Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
279 for (unsigned i = 0; i < NumOpts; ++i)
280 OptUnsafeEdges[i] -= UnsafeOpts[i];
283 bool isConservativelyAllocatable() const {
284 return (DeniedOpts < NumOpts) ||
285 (std::find(&OptUnsafeEdges[0], &OptUnsafeEdges[NumOpts], 0) !=
286 &OptUnsafeEdges[NumOpts]);
289 bool wasConservativelyAllocatable() const {
290 return everConservativelyAllocatable;
297 std::unique_ptr<unsigned[]> OptUnsafeEdges;
299 GraphMetadata::AllowedRegVecRef AllowedRegs;
300 bool everConservativelyAllocatable;
303 class RegAllocSolverImpl {
305 typedef MDMatrix<MatrixMetadata> RAMatrix;
307 typedef PBQP::Vector RawVector;
308 typedef PBQP::Matrix RawMatrix;
309 typedef PBQP::Vector Vector;
310 typedef RAMatrix Matrix;
311 typedef PBQP::PoolCostAllocator<Vector, Matrix> CostAllocator;
313 typedef GraphBase::NodeId NodeId;
314 typedef GraphBase::EdgeId EdgeId;
316 typedef RegAlloc::NodeMetadata NodeMetadata;
317 struct EdgeMetadata { };
318 typedef RegAlloc::GraphMetadata GraphMetadata;
320 typedef PBQP::Graph<RegAllocSolverImpl> Graph;
322 RegAllocSolverImpl(Graph &G) : G(G) {}
328 S = backpropagate(G, reduce());
333 void handleAddNode(NodeId NId) {
334 assert(G.getNodeCosts(NId).getLength() > 1 &&
335 "PBQP Graph should not contain single or zero-option nodes");
336 G.getNodeMetadata(NId).setup(G.getNodeCosts(NId));
338 void handleRemoveNode(NodeId NId) {}
339 void handleSetNodeCosts(NodeId NId, const Vector& newCosts) {}
341 void handleAddEdge(EdgeId EId) {
342 handleReconnectEdge(EId, G.getEdgeNode1Id(EId));
343 handleReconnectEdge(EId, G.getEdgeNode2Id(EId));
346 void handleRemoveEdge(EdgeId EId) {
347 handleDisconnectEdge(EId, G.getEdgeNode1Id(EId));
348 handleDisconnectEdge(EId, G.getEdgeNode2Id(EId));
351 void handleDisconnectEdge(EdgeId EId, NodeId NId) {
352 NodeMetadata& NMd = G.getNodeMetadata(NId);
353 const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
354 NMd.handleRemoveEdge(MMd, NId == G.getEdgeNode2Id(EId));
358 void handleReconnectEdge(EdgeId EId, NodeId NId) {
359 NodeMetadata& NMd = G.getNodeMetadata(NId);
360 const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
361 NMd.handleAddEdge(MMd, NId == G.getEdgeNode2Id(EId));
364 void handleUpdateCosts(EdgeId EId, const Matrix& NewCosts) {
365 NodeId N1Id = G.getEdgeNode1Id(EId);
366 NodeId N2Id = G.getEdgeNode2Id(EId);
367 NodeMetadata& N1Md = G.getNodeMetadata(N1Id);
368 NodeMetadata& N2Md = G.getNodeMetadata(N2Id);
369 bool Transpose = N1Id != G.getEdgeNode1Id(EId);
371 // Metadata are computed incrementally. First, update them
372 // by removing the old cost.
373 const MatrixMetadata& OldMMd = G.getEdgeCosts(EId).getMetadata();
374 N1Md.handleRemoveEdge(OldMMd, Transpose);
375 N2Md.handleRemoveEdge(OldMMd, !Transpose);
377 // And update now the metadata with the new cost.
378 const MatrixMetadata& MMd = NewCosts.getMetadata();
379 N1Md.handleAddEdge(MMd, Transpose);
380 N2Md.handleAddEdge(MMd, !Transpose);
382 // As the metadata may have changed with the update, the nodes may have
383 // become ConservativelyAllocatable or OptimallyReducible.
390 void promote(NodeId NId, NodeMetadata& NMd) {
391 if (G.getNodeDegree(NId) == 3) {
392 // This node is becoming optimally reducible.
393 moveToOptimallyReducibleNodes(NId);
394 } else if (NMd.getReductionState() ==
395 NodeMetadata::NotProvablyAllocatable &&
396 NMd.isConservativelyAllocatable()) {
397 // This node just became conservatively allocatable.
398 moveToConservativelyAllocatableNodes(NId);
402 void removeFromCurrentSet(NodeId NId) {
403 switch (G.getNodeMetadata(NId).getReductionState()) {
404 case NodeMetadata::Unprocessed: break;
405 case NodeMetadata::OptimallyReducible:
406 assert(OptimallyReducibleNodes.find(NId) !=
407 OptimallyReducibleNodes.end() &&
408 "Node not in optimally reducible set.");
409 OptimallyReducibleNodes.erase(NId);
411 case NodeMetadata::ConservativelyAllocatable:
412 assert(ConservativelyAllocatableNodes.find(NId) !=
413 ConservativelyAllocatableNodes.end() &&
414 "Node not in conservatively allocatable set.");
415 ConservativelyAllocatableNodes.erase(NId);
417 case NodeMetadata::NotProvablyAllocatable:
418 assert(NotProvablyAllocatableNodes.find(NId) !=
419 NotProvablyAllocatableNodes.end() &&
420 "Node not in not-provably-allocatable set.");
421 NotProvablyAllocatableNodes.erase(NId);
426 void moveToOptimallyReducibleNodes(NodeId NId) {
427 removeFromCurrentSet(NId);
428 OptimallyReducibleNodes.insert(NId);
429 G.getNodeMetadata(NId).setReductionState(
430 NodeMetadata::OptimallyReducible);
433 void moveToConservativelyAllocatableNodes(NodeId NId) {
434 removeFromCurrentSet(NId);
435 ConservativelyAllocatableNodes.insert(NId);
436 G.getNodeMetadata(NId).setReductionState(
437 NodeMetadata::ConservativelyAllocatable);
440 void moveToNotProvablyAllocatableNodes(NodeId NId) {
441 removeFromCurrentSet(NId);
442 NotProvablyAllocatableNodes.insert(NId);
443 G.getNodeMetadata(NId).setReductionState(
444 NodeMetadata::NotProvablyAllocatable);
449 for (auto NId : G.nodeIds()) {
450 if (G.getNodeDegree(NId) < 3)
451 moveToOptimallyReducibleNodes(NId);
452 else if (G.getNodeMetadata(NId).isConservativelyAllocatable())
453 moveToConservativelyAllocatableNodes(NId);
455 moveToNotProvablyAllocatableNodes(NId);
459 // Compute a reduction order for the graph by iteratively applying PBQP
460 // reduction rules. Locally optimal rules are applied whenever possible (R0,
461 // R1, R2). If no locally-optimal rules apply then any conservatively
462 // allocatable node is reduced. Finally, if no conservatively allocatable
463 // node exists then the node with the lowest spill-cost:degree ratio is
465 std::vector<GraphBase::NodeId> reduce() {
466 assert(!G.empty() && "Cannot reduce empty graph.");
468 typedef GraphBase::NodeId NodeId;
469 std::vector<NodeId> NodeStack;
471 // Consume worklists.
473 if (!OptimallyReducibleNodes.empty()) {
474 NodeSet::iterator NItr = OptimallyReducibleNodes.begin();
476 OptimallyReducibleNodes.erase(NItr);
477 NodeStack.push_back(NId);
478 switch (G.getNodeDegree(NId)) {
487 default: llvm_unreachable("Not an optimally reducible node.");
489 } else if (!ConservativelyAllocatableNodes.empty()) {
490 // Conservatively allocatable nodes will never spill. For now just
491 // take the first node in the set and push it on the stack. When we
492 // start optimizing more heavily for register preferencing, it may
493 // would be better to push nodes with lower 'expected' or worst-case
494 // register costs first (since early nodes are the most
496 NodeSet::iterator NItr = ConservativelyAllocatableNodes.begin();
498 ConservativelyAllocatableNodes.erase(NItr);
499 NodeStack.push_back(NId);
500 G.disconnectAllNeighborsFromNode(NId);
502 } else if (!NotProvablyAllocatableNodes.empty()) {
503 NodeSet::iterator NItr =
504 std::min_element(NotProvablyAllocatableNodes.begin(),
505 NotProvablyAllocatableNodes.end(),
506 SpillCostComparator(G));
508 NotProvablyAllocatableNodes.erase(NItr);
509 NodeStack.push_back(NId);
510 G.disconnectAllNeighborsFromNode(NId);
518 class SpillCostComparator {
520 SpillCostComparator(const Graph& G) : G(G) {}
521 bool operator()(NodeId N1Id, NodeId N2Id) {
522 PBQPNum N1SC = G.getNodeCosts(N1Id)[0] / G.getNodeDegree(N1Id);
523 PBQPNum N2SC = G.getNodeCosts(N2Id)[0] / G.getNodeDegree(N2Id);
531 typedef std::set<NodeId> NodeSet;
532 NodeSet OptimallyReducibleNodes;
533 NodeSet ConservativelyAllocatableNodes;
534 NodeSet NotProvablyAllocatableNodes;
537 class PBQPRAGraph : public PBQP::Graph<RegAllocSolverImpl> {
539 typedef PBQP::Graph<RegAllocSolverImpl> BaseT;
541 PBQPRAGraph(GraphMetadata Metadata) : BaseT(Metadata) {}
543 /// @brief Dump this graph to dbgs().
546 /// @brief Dump this graph to an output stream.
547 /// @param OS Output stream to print on.
548 void dump(raw_ostream &OS) const;
550 /// @brief Print a representation of this graph in DOT format.
551 /// @param OS Output stream to print on.
552 void printDot(raw_ostream &OS) const;
555 inline Solution solve(PBQPRAGraph& G) {
558 RegAllocSolverImpl RegAllocSolver(G);
559 return RegAllocSolver.solve();
562 } // namespace RegAlloc
565 /// @brief Create a PBQP register allocator instance.
567 createPBQPRegisterAllocator(char *customPassID = nullptr);
571 #endif /* LLVM_CODEGEN_REGALLOCPBQP_H */