[PBQP] Conservativelly allocatable nodes can be spilled and give a better solution
[oota-llvm.git] / include / llvm / CodeGen / RegAllocPBQP.h
1 //===-- RegAllocPBQP.h ------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the PBQPBuilder interface, for classes which build PBQP
11 // instances to represent register allocation problems, and the RegAllocPBQP
12 // interface.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_CODEGEN_REGALLOCPBQP_H
17 #define LLVM_CODEGEN_REGALLOCPBQP_H
18
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"
24
25 namespace llvm {
26
27 class raw_ostream;
28
29 namespace PBQP {
30 namespace RegAlloc {
31
32 /// @brief Spill option index.
33 inline unsigned getSpillOptionIdx() { return 0; }
34
35 /// \brief Metadata to speed allocatability test.
36 ///
37 /// Keeps track of the number of infinities in each row and column.
38 class MatrixMetadata {
39 private:
40   MatrixMetadata(const MatrixMetadata&);
41   void operator=(const MatrixMetadata&);
42 public:
43   MatrixMetadata(const Matrix& M)
44     : WorstRow(0), WorstCol(0),
45       UnsafeRows(new bool[M.getRows() - 1]()),
46       UnsafeCols(new bool[M.getCols() - 1]()) {
47
48     unsigned* ColCounts = new unsigned[M.getCols() - 1]();
49
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()) {
54           ++RowCount;
55           ++ColCounts[j - 1];
56           UnsafeRows[i - 1] = true;
57           UnsafeCols[j - 1] = true;
58         }
59       }
60       WorstRow = std::max(WorstRow, RowCount);
61     }
62     unsigned WorstColCountForCurRow =
63       *std::max_element(ColCounts, ColCounts + M.getCols() - 1);
64     WorstCol = std::max(WorstCol, WorstColCountForCurRow);
65     delete[] ColCounts;
66   }
67
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(); }
72
73 private:
74   unsigned WorstRow, WorstCol;
75   std::unique_ptr<bool[]> UnsafeRows;
76   std::unique_ptr<bool[]> UnsafeCols;
77 };
78
79 /// \brief Holds a vector of the allowed physical regs for a vreg.
80 class AllowedRegVector {
81   friend hash_code hash_value(const AllowedRegVector &);
82 public:
83
84   AllowedRegVector() : NumOpts(0), Opts(nullptr) {}
85
86   AllowedRegVector(const std::vector<unsigned> &OptVec)
87     : NumOpts(OptVec.size()), Opts(new unsigned[NumOpts]) {
88     std::copy(OptVec.begin(), OptVec.end(), Opts.get());
89   }
90
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());
94   }
95
96   AllowedRegVector(AllowedRegVector &&Other)
97     : NumOpts(std::move(Other.NumOpts)), Opts(std::move(Other.Opts)) {}
98
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());
103     return *this;
104   }
105
106   AllowedRegVector& operator=(AllowedRegVector &&Other) {
107     NumOpts = std::move(Other.NumOpts);
108     Opts = std::move(Other.Opts);
109     return *this;
110   }
111
112   unsigned size() const { return NumOpts; }
113   unsigned operator[](size_t I) const { return Opts[I]; }
114
115   bool operator==(const AllowedRegVector &Other) const {
116     if (NumOpts != Other.NumOpts)
117       return false;
118     return std::equal(Opts.get(), Opts.get() + NumOpts, Other.Opts.get());
119   }
120
121   bool operator!=(const AllowedRegVector &Other) const {
122     return !(*this == Other);
123   }
124
125 private:
126   unsigned NumOpts;
127   std::unique_ptr<unsigned[]> Opts;
128 };
129
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));
135 }
136
137 /// \brief Holds graph-level metadata relevent to PBQP RA problems.
138 class GraphMetadata {
139 private:
140   typedef ValuePool<AllowedRegVector> AllowedRegVecPool;
141 public:
142
143   typedef AllowedRegVecPool::PoolRef AllowedRegVecRef;
144
145   GraphMetadata(MachineFunction &MF,
146                 LiveIntervals &LIS,
147                 MachineBlockFrequencyInfo &MBFI)
148     : MF(MF), LIS(LIS), MBFI(MBFI) {}
149
150   MachineFunction &MF;
151   LiveIntervals &LIS;
152   MachineBlockFrequencyInfo &MBFI;
153
154   void setNodeIdForVReg(unsigned VReg, GraphBase::NodeId NId) {
155     VRegToNodeId[VReg] = NId;
156   }
157
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;
163   }
164
165   void eraseNodeIdForVReg(unsigned VReg) {
166     VRegToNodeId.erase(VReg);
167   }
168
169   AllowedRegVecRef getAllowedRegs(AllowedRegVector Allowed) {
170     return AllowedRegVecs.getValue(std::move(Allowed));
171   }
172
173 private:
174   DenseMap<unsigned, GraphBase::NodeId> VRegToNodeId;
175   AllowedRegVecPool AllowedRegVecs;
176 };
177
178 /// \brief Holds solver state and other metadata relevant to each PBQP RA node.
179 class NodeMetadata {
180 public:
181   typedef RegAlloc::AllowedRegVector AllowedRegVector;
182
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.
186   typedef enum {
187     Unprocessed,
188     NotProvablyAllocatable,
189     ConservativelyAllocatable,
190     OptimallyReducible
191   } ReductionState;
192
193   NodeMetadata()
194     : RS(Unprocessed), NumOpts(0), DeniedOpts(0), OptUnsafeEdges(nullptr),
195       VReg(0) {}
196
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) {
203     if (NumOpts > 0) {
204       std::copy(&Other.OptUnsafeEdges[0], &Other.OptUnsafeEdges[NumOpts],
205                 &OptUnsafeEdges[0]);
206     }
207   }
208
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)) {}
215
216   // FIXME: Re-implementing default behavior to work around MSVC. Remove once
217   // MSVC synthesizes move constructors properly.
218   NodeMetadata& operator=(const NodeMetadata &Other) {
219     RS = Other.RS;
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());
225     VReg = Other.VReg;
226     AllowedRegs = Other.AllowedRegs;
227     return *this;
228   }
229
230   // FIXME: Re-implementing default behavior to work around MSVC. Remove once
231   // MSVC synthesizes move constructors properly.
232   NodeMetadata& operator=(NodeMetadata &&Other) {
233     RS = Other.RS;
234     NumOpts = Other.NumOpts;
235     DeniedOpts = Other.DeniedOpts;
236     OptUnsafeEdges = std::move(Other.OptUnsafeEdges);
237     VReg = Other.VReg;
238     AllowedRegs = std::move(Other.AllowedRegs);
239     return *this;
240   }
241
242   void setVReg(unsigned VReg) { this->VReg = VReg; }
243   unsigned getVReg() const { return VReg; }
244
245   void setAllowedRegs(GraphMetadata::AllowedRegVecRef AllowedRegs) {
246     this->AllowedRegs = std::move(AllowedRegs);
247   }
248   const AllowedRegVector& getAllowedRegs() const { return *AllowedRegs; }
249
250   void setup(const Vector& Costs) {
251     NumOpts = Costs.getLength() - 1;
252     OptUnsafeEdges = std::unique_ptr<unsigned[]>(new unsigned[NumOpts]());
253   }
254
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");
258     this->RS = RS;
259   }
260
261   void handleAddEdge(const MatrixMetadata& MD, bool Transpose) {
262     DeniedOpts += Transpose ? MD.getWorstRow() : MD.getWorstCol();
263     const bool* UnsafeOpts =
264       Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
265     for (unsigned i = 0; i < NumOpts; ++i)
266       OptUnsafeEdges[i] += UnsafeOpts[i];
267   }
268
269   void handleRemoveEdge(const MatrixMetadata& MD, bool Transpose) {
270     DeniedOpts -= Transpose ? MD.getWorstRow() : MD.getWorstCol();
271     const bool* UnsafeOpts =
272       Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
273     for (unsigned i = 0; i < NumOpts; ++i)
274       OptUnsafeEdges[i] -= UnsafeOpts[i];
275   }
276
277   bool isConservativelyAllocatable() const {
278     return (DeniedOpts < NumOpts) ||
279       (std::find(&OptUnsafeEdges[0], &OptUnsafeEdges[NumOpts], 0) !=
280        &OptUnsafeEdges[NumOpts]);
281   }
282
283 private:
284   ReductionState RS;
285   unsigned NumOpts;
286   unsigned DeniedOpts;
287   std::unique_ptr<unsigned[]> OptUnsafeEdges;
288   unsigned VReg;
289   GraphMetadata::AllowedRegVecRef AllowedRegs;
290 };
291
292 class RegAllocSolverImpl {
293 private:
294   typedef MDMatrix<MatrixMetadata> RAMatrix;
295 public:
296   typedef PBQP::Vector RawVector;
297   typedef PBQP::Matrix RawMatrix;
298   typedef PBQP::Vector Vector;
299   typedef RAMatrix     Matrix;
300   typedef PBQP::PoolCostAllocator<Vector, Matrix> CostAllocator;
301
302   typedef GraphBase::NodeId NodeId;
303   typedef GraphBase::EdgeId EdgeId;
304
305   typedef RegAlloc::NodeMetadata NodeMetadata;
306   struct EdgeMetadata { };
307   typedef RegAlloc::GraphMetadata GraphMetadata;
308
309   typedef PBQP::Graph<RegAllocSolverImpl> Graph;
310
311   RegAllocSolverImpl(Graph &G) : G(G) {}
312
313   Solution solve() {
314     G.setSolver(*this);
315     Solution S;
316     setup();
317     S = backpropagate(G, reduce());
318     G.unsetSolver();
319     return S;
320   }
321
322   void handleAddNode(NodeId NId) {
323     assert(G.getNodeCosts(NId).getLength() > 1 &&
324            "PBQP Graph should not contain single or zero-option nodes");
325     G.getNodeMetadata(NId).setup(G.getNodeCosts(NId));
326   }
327   void handleRemoveNode(NodeId NId) {}
328   void handleSetNodeCosts(NodeId NId, const Vector& newCosts) {}
329
330   void handleAddEdge(EdgeId EId) {
331     handleReconnectEdge(EId, G.getEdgeNode1Id(EId));
332     handleReconnectEdge(EId, G.getEdgeNode2Id(EId));
333   }
334
335   void handleRemoveEdge(EdgeId EId) {
336     handleDisconnectEdge(EId, G.getEdgeNode1Id(EId));
337     handleDisconnectEdge(EId, G.getEdgeNode2Id(EId));
338   }
339
340   void handleDisconnectEdge(EdgeId EId, NodeId NId) {
341     NodeMetadata& NMd = G.getNodeMetadata(NId);
342     const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
343     NMd.handleRemoveEdge(MMd, NId == G.getEdgeNode2Id(EId));
344     promote(NId, NMd);
345   }
346
347   void handleReconnectEdge(EdgeId EId, NodeId NId) {
348     NodeMetadata& NMd = G.getNodeMetadata(NId);
349     const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
350     NMd.handleAddEdge(MMd, NId == G.getEdgeNode2Id(EId));
351   }
352
353   void handleUpdateCosts(EdgeId EId, const Matrix& NewCosts) {
354     NodeId N1Id = G.getEdgeNode1Id(EId);
355     NodeId N2Id = G.getEdgeNode2Id(EId);
356     NodeMetadata& N1Md = G.getNodeMetadata(N1Id);
357     NodeMetadata& N2Md = G.getNodeMetadata(N2Id);
358     bool Transpose = N1Id != G.getEdgeNode1Id(EId);
359
360     // Metadata are computed incrementally. First, update them
361     // by removing the old cost.
362     const MatrixMetadata& OldMMd = G.getEdgeCosts(EId).getMetadata();
363     N1Md.handleRemoveEdge(OldMMd, Transpose);
364     N2Md.handleRemoveEdge(OldMMd, !Transpose);
365
366     // And update now the metadata with the new cost.
367     const MatrixMetadata& MMd = NewCosts.getMetadata();
368     N1Md.handleAddEdge(MMd, Transpose);
369     N2Md.handleAddEdge(MMd, !Transpose);
370
371     // As the metadata may have changed with the update, the nodes may have
372     // become ConservativelyAllocatable or OptimallyReducible.
373     promote(N1Id, N1Md);
374     promote(N2Id, N2Md);
375   }
376
377 private:
378
379   void promote(NodeId NId, NodeMetadata& NMd) {
380     if (G.getNodeDegree(NId) == 3) {
381       // This node is becoming optimally reducible.
382       moveToOptimallyReducibleNodes(NId);
383     } else if (NMd.getReductionState() ==
384                NodeMetadata::NotProvablyAllocatable &&
385                NMd.isConservativelyAllocatable()) {
386       // This node just became conservatively allocatable.
387       moveToConservativelyAllocatableNodes(NId);
388     }
389   }
390
391   void removeFromCurrentSet(NodeId NId) {
392     switch (G.getNodeMetadata(NId).getReductionState()) {
393     case NodeMetadata::Unprocessed: break;
394     case NodeMetadata::OptimallyReducible:
395       assert(OptimallyReducibleNodes.find(NId) !=
396              OptimallyReducibleNodes.end() &&
397              "Node not in optimally reducible set.");
398       OptimallyReducibleNodes.erase(NId);
399       break;
400     case NodeMetadata::ConservativelyAllocatable:
401       assert(ConservativelyAllocatableNodes.find(NId) !=
402              ConservativelyAllocatableNodes.end() &&
403              "Node not in conservatively allocatable set.");
404       ConservativelyAllocatableNodes.erase(NId);
405       break;
406     case NodeMetadata::NotProvablyAllocatable:
407       assert(NotProvablyAllocatableNodes.find(NId) !=
408              NotProvablyAllocatableNodes.end() &&
409              "Node not in not-provably-allocatable set.");
410       NotProvablyAllocatableNodes.erase(NId);
411       break;
412     }
413   }
414
415   void moveToOptimallyReducibleNodes(NodeId NId) {
416     removeFromCurrentSet(NId);
417     OptimallyReducibleNodes.insert(NId);
418     G.getNodeMetadata(NId).setReductionState(
419       NodeMetadata::OptimallyReducible);
420   }
421
422   void moveToConservativelyAllocatableNodes(NodeId NId) {
423     removeFromCurrentSet(NId);
424     ConservativelyAllocatableNodes.insert(NId);
425     G.getNodeMetadata(NId).setReductionState(
426       NodeMetadata::ConservativelyAllocatable);
427   }
428
429   void moveToNotProvablyAllocatableNodes(NodeId NId) {
430     removeFromCurrentSet(NId);
431     NotProvablyAllocatableNodes.insert(NId);
432     G.getNodeMetadata(NId).setReductionState(
433       NodeMetadata::NotProvablyAllocatable);
434   }
435
436   void setup() {
437     // Set up worklists.
438     for (auto NId : G.nodeIds()) {
439       if (G.getNodeDegree(NId) < 3)
440         moveToOptimallyReducibleNodes(NId);
441       else if (G.getNodeMetadata(NId).isConservativelyAllocatable())
442         moveToConservativelyAllocatableNodes(NId);
443       else
444         moveToNotProvablyAllocatableNodes(NId);
445     }
446   }
447
448   // Compute a reduction order for the graph by iteratively applying PBQP
449   // reduction rules. Locally optimal rules are applied whenever possible (R0,
450   // R1, R2). If no locally-optimal rules apply then any conservatively
451   // allocatable node is reduced. Finally, if no conservatively allocatable
452   // node exists then the node with the lowest spill-cost:degree ratio is
453   // selected.
454   std::vector<GraphBase::NodeId> reduce() {
455     assert(!G.empty() && "Cannot reduce empty graph.");
456
457     typedef GraphBase::NodeId NodeId;
458     std::vector<NodeId> NodeStack;
459
460     // Consume worklists.
461     while (true) {
462       if (!OptimallyReducibleNodes.empty()) {
463         NodeSet::iterator NItr = OptimallyReducibleNodes.begin();
464         NodeId NId = *NItr;
465         OptimallyReducibleNodes.erase(NItr);
466         NodeStack.push_back(NId);
467         switch (G.getNodeDegree(NId)) {
468         case 0:
469           break;
470         case 1:
471           applyR1(G, NId);
472           break;
473         case 2:
474           applyR2(G, NId);
475           break;
476         default: llvm_unreachable("Not an optimally reducible node.");
477         }
478       } else if (!ConservativelyAllocatableNodes.empty()) {
479         // Conservatively allocatable nodes will never spill. For now just
480         // take the first node in the set and push it on the stack. When we
481         // start optimizing more heavily for register preferencing, it may
482         // would be better to push nodes with lower 'expected' or worst-case
483         // register costs first (since early nodes are the most
484         // constrained).
485         NodeSet::iterator NItr = ConservativelyAllocatableNodes.begin();
486         NodeId NId = *NItr;
487         ConservativelyAllocatableNodes.erase(NItr);
488         NodeStack.push_back(NId);
489         G.disconnectAllNeighborsFromNode(NId);
490
491       } else if (!NotProvablyAllocatableNodes.empty()) {
492         NodeSet::iterator NItr =
493           std::min_element(NotProvablyAllocatableNodes.begin(),
494                            NotProvablyAllocatableNodes.end(),
495                            SpillCostComparator(G));
496         NodeId NId = *NItr;
497         NotProvablyAllocatableNodes.erase(NItr);
498         NodeStack.push_back(NId);
499         G.disconnectAllNeighborsFromNode(NId);
500       } else
501         break;
502     }
503
504     return NodeStack;
505   }
506
507   class SpillCostComparator {
508   public:
509     SpillCostComparator(const Graph& G) : G(G) {}
510     bool operator()(NodeId N1Id, NodeId N2Id) {
511       PBQPNum N1SC = G.getNodeCosts(N1Id)[0] / G.getNodeDegree(N1Id);
512       PBQPNum N2SC = G.getNodeCosts(N2Id)[0] / G.getNodeDegree(N2Id);
513       return N1SC < N2SC;
514     }
515   private:
516     const Graph& G;
517   };
518
519   Graph& G;
520   typedef std::set<NodeId> NodeSet;
521   NodeSet OptimallyReducibleNodes;
522   NodeSet ConservativelyAllocatableNodes;
523   NodeSet NotProvablyAllocatableNodes;
524 };
525
526 class PBQPRAGraph : public PBQP::Graph<RegAllocSolverImpl> {
527 private:
528   typedef PBQP::Graph<RegAllocSolverImpl> BaseT;
529 public:
530   PBQPRAGraph(GraphMetadata Metadata) : BaseT(Metadata) {}
531
532   /// @brief Dump this graph to dbgs().
533   void dump() const;
534
535   /// @brief Dump this graph to an output stream.
536   /// @param OS Output stream to print on.
537   void dump(raw_ostream &OS) const;
538
539   /// @brief Print a representation of this graph in DOT format.
540   /// @param OS Output stream to print on.
541   void printDot(raw_ostream &OS) const;
542 };
543
544 inline Solution solve(PBQPRAGraph& G) {
545   if (G.empty())
546     return Solution();
547   RegAllocSolverImpl RegAllocSolver(G);
548   return RegAllocSolver.solve();
549 }
550
551 } // namespace RegAlloc
552 } // namespace PBQP
553
554 /// @brief Create a PBQP register allocator instance.
555 FunctionPass *
556 createPBQPRegisterAllocator(char *customPassID = nullptr);
557
558 } // namespace llvm
559
560 #endif /* LLVM_CODEGEN_REGALLOCPBQP_H */