[PBQP] Provide more information in the debug prints
[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   typedef enum { Unprocessed,
184                  OptimallyReducible,
185                  ConservativelyAllocatable,
186                  NotProvablyAllocatable } ReductionState;
187
188   NodeMetadata()
189     : RS(Unprocessed), NumOpts(0), DeniedOpts(0), OptUnsafeEdges(nullptr),
190       VReg(0) {}
191
192   // FIXME: Re-implementing default behavior to work around MSVC. Remove once
193   // MSVC synthesizes move constructors properly.
194   NodeMetadata(const NodeMetadata &Other)
195     : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
196       OptUnsafeEdges(new unsigned[NumOpts]), VReg(Other.VReg),
197       AllowedRegs(Other.AllowedRegs) {
198     if (NumOpts > 0) {
199       std::copy(&Other.OptUnsafeEdges[0], &Other.OptUnsafeEdges[NumOpts],
200                 &OptUnsafeEdges[0]);
201     }
202   }
203
204   // FIXME: Re-implementing default behavior to work around MSVC. Remove once
205   // MSVC synthesizes move constructors properly.
206   NodeMetadata(NodeMetadata &&Other)
207     : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
208       OptUnsafeEdges(std::move(Other.OptUnsafeEdges)), VReg(Other.VReg),
209       AllowedRegs(std::move(Other.AllowedRegs)) {}
210
211   // FIXME: Re-implementing default behavior to work around MSVC. Remove once
212   // MSVC synthesizes move constructors properly.
213   NodeMetadata& operator=(const NodeMetadata &Other) {
214     RS = Other.RS;
215     NumOpts = Other.NumOpts;
216     DeniedOpts = Other.DeniedOpts;
217     OptUnsafeEdges.reset(new unsigned[NumOpts]);
218     std::copy(Other.OptUnsafeEdges.get(), Other.OptUnsafeEdges.get() + NumOpts,
219               OptUnsafeEdges.get());
220     VReg = Other.VReg;
221     AllowedRegs = Other.AllowedRegs;
222     return *this;
223   }
224
225   // FIXME: Re-implementing default behavior to work around MSVC. Remove once
226   // MSVC synthesizes move constructors properly.
227   NodeMetadata& operator=(NodeMetadata &&Other) {
228     RS = Other.RS;
229     NumOpts = Other.NumOpts;
230     DeniedOpts = Other.DeniedOpts;
231     OptUnsafeEdges = std::move(Other.OptUnsafeEdges);
232     VReg = Other.VReg;
233     AllowedRegs = std::move(Other.AllowedRegs);
234     return *this;
235   }
236
237   void setVReg(unsigned VReg) { this->VReg = VReg; }
238   unsigned getVReg() const { return VReg; }
239
240   void setAllowedRegs(GraphMetadata::AllowedRegVecRef AllowedRegs) {
241     this->AllowedRegs = std::move(AllowedRegs);
242   }
243   const AllowedRegVector& getAllowedRegs() const { return *AllowedRegs; }
244
245   void setup(const Vector& Costs) {
246     NumOpts = Costs.getLength() - 1;
247     OptUnsafeEdges = std::unique_ptr<unsigned[]>(new unsigned[NumOpts]());
248   }
249
250   ReductionState getReductionState() const { return RS; }
251   void setReductionState(ReductionState RS) { this->RS = RS; }
252
253   void handleAddEdge(const MatrixMetadata& MD, bool Transpose) {
254     DeniedOpts += Transpose ? MD.getWorstRow() : MD.getWorstCol();
255     const bool* UnsafeOpts =
256       Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
257     for (unsigned i = 0; i < NumOpts; ++i)
258       OptUnsafeEdges[i] += UnsafeOpts[i];
259   }
260
261   void handleRemoveEdge(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   bool isConservativelyAllocatable() const {
270     return (DeniedOpts < NumOpts) ||
271       (std::find(&OptUnsafeEdges[0], &OptUnsafeEdges[NumOpts], 0) !=
272        &OptUnsafeEdges[NumOpts]);
273   }
274
275 private:
276   ReductionState RS;
277   unsigned NumOpts;
278   unsigned DeniedOpts;
279   std::unique_ptr<unsigned[]> OptUnsafeEdges;
280   unsigned VReg;
281   GraphMetadata::AllowedRegVecRef AllowedRegs;
282 };
283
284 class RegAllocSolverImpl {
285 private:
286   typedef MDMatrix<MatrixMetadata> RAMatrix;
287 public:
288   typedef PBQP::Vector RawVector;
289   typedef PBQP::Matrix RawMatrix;
290   typedef PBQP::Vector Vector;
291   typedef RAMatrix     Matrix;
292   typedef PBQP::PoolCostAllocator<Vector, Matrix> CostAllocator;
293
294   typedef GraphBase::NodeId NodeId;
295   typedef GraphBase::EdgeId EdgeId;
296
297   typedef RegAlloc::NodeMetadata NodeMetadata;
298   struct EdgeMetadata { };
299   typedef RegAlloc::GraphMetadata GraphMetadata;
300
301   typedef PBQP::Graph<RegAllocSolverImpl> Graph;
302
303   RegAllocSolverImpl(Graph &G) : G(G) {}
304
305   Solution solve() {
306     G.setSolver(*this);
307     Solution S;
308     setup();
309     S = backpropagate(G, reduce());
310     G.unsetSolver();
311     return S;
312   }
313
314   void handleAddNode(NodeId NId) {
315     assert(G.getNodeCosts(NId).getLength() > 1 &&
316            "PBQP Graph should not contain single or zero-option nodes");
317     G.getNodeMetadata(NId).setup(G.getNodeCosts(NId));
318   }
319   void handleRemoveNode(NodeId NId) {}
320   void handleSetNodeCosts(NodeId NId, const Vector& newCosts) {}
321
322   void handleAddEdge(EdgeId EId) {
323     handleReconnectEdge(EId, G.getEdgeNode1Id(EId));
324     handleReconnectEdge(EId, G.getEdgeNode2Id(EId));
325   }
326
327   void handleRemoveEdge(EdgeId EId) {
328     handleDisconnectEdge(EId, G.getEdgeNode1Id(EId));
329     handleDisconnectEdge(EId, G.getEdgeNode2Id(EId));
330   }
331
332   void handleDisconnectEdge(EdgeId EId, NodeId NId) {
333     NodeMetadata& NMd = G.getNodeMetadata(NId);
334     const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
335     NMd.handleRemoveEdge(MMd, NId == G.getEdgeNode2Id(EId));
336     if (G.getNodeDegree(NId) == 3) {
337       // This node is becoming optimally reducible.
338       moveToOptimallyReducibleNodes(NId);
339     } else if (NMd.getReductionState() ==
340                NodeMetadata::NotProvablyAllocatable &&
341                NMd.isConservativelyAllocatable()) {
342       // This node just became conservatively allocatable.
343       moveToConservativelyAllocatableNodes(NId);
344     }
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 handleSetEdgeCosts(EdgeId EId, const Matrix& NewCosts) {
354     handleRemoveEdge(EId);
355
356     NodeId N1Id = G.getEdgeNode1Id(EId);
357     NodeId N2Id = G.getEdgeNode2Id(EId);
358     NodeMetadata& N1Md = G.getNodeMetadata(N1Id);
359     NodeMetadata& N2Md = G.getNodeMetadata(N2Id);
360     const MatrixMetadata& MMd = NewCosts.getMetadata();
361     N1Md.handleAddEdge(MMd, N1Id != G.getEdgeNode1Id(EId));
362     N2Md.handleAddEdge(MMd, N2Id != G.getEdgeNode1Id(EId));
363   }
364
365 private:
366
367   void removeFromCurrentSet(NodeId NId) {
368     switch (G.getNodeMetadata(NId).getReductionState()) {
369     case NodeMetadata::Unprocessed: break;
370     case NodeMetadata::OptimallyReducible:
371       assert(OptimallyReducibleNodes.find(NId) !=
372              OptimallyReducibleNodes.end() &&
373              "Node not in optimally reducible set.");
374       OptimallyReducibleNodes.erase(NId);
375       break;
376     case NodeMetadata::ConservativelyAllocatable:
377       assert(ConservativelyAllocatableNodes.find(NId) !=
378              ConservativelyAllocatableNodes.end() &&
379              "Node not in conservatively allocatable set.");
380       ConservativelyAllocatableNodes.erase(NId);
381       break;
382     case NodeMetadata::NotProvablyAllocatable:
383       assert(NotProvablyAllocatableNodes.find(NId) !=
384              NotProvablyAllocatableNodes.end() &&
385              "Node not in not-provably-allocatable set.");
386       NotProvablyAllocatableNodes.erase(NId);
387       break;
388     }
389   }
390
391   void moveToOptimallyReducibleNodes(NodeId NId) {
392     removeFromCurrentSet(NId);
393     OptimallyReducibleNodes.insert(NId);
394     G.getNodeMetadata(NId).setReductionState(
395       NodeMetadata::OptimallyReducible);
396   }
397
398   void moveToConservativelyAllocatableNodes(NodeId NId) {
399     removeFromCurrentSet(NId);
400     ConservativelyAllocatableNodes.insert(NId);
401     G.getNodeMetadata(NId).setReductionState(
402       NodeMetadata::ConservativelyAllocatable);
403   }
404
405   void moveToNotProvablyAllocatableNodes(NodeId NId) {
406     removeFromCurrentSet(NId);
407     NotProvablyAllocatableNodes.insert(NId);
408     G.getNodeMetadata(NId).setReductionState(
409       NodeMetadata::NotProvablyAllocatable);
410   }
411
412   void setup() {
413     // Set up worklists.
414     for (auto NId : G.nodeIds()) {
415       if (G.getNodeDegree(NId) < 3)
416         moveToOptimallyReducibleNodes(NId);
417       else if (G.getNodeMetadata(NId).isConservativelyAllocatable())
418         moveToConservativelyAllocatableNodes(NId);
419       else
420         moveToNotProvablyAllocatableNodes(NId);
421     }
422   }
423
424   // Compute a reduction order for the graph by iteratively applying PBQP
425   // reduction rules. Locally optimal rules are applied whenever possible (R0,
426   // R1, R2). If no locally-optimal rules apply then any conservatively
427   // allocatable node is reduced. Finally, if no conservatively allocatable
428   // node exists then the node with the lowest spill-cost:degree ratio is
429   // selected.
430   std::vector<GraphBase::NodeId> reduce() {
431     assert(!G.empty() && "Cannot reduce empty graph.");
432
433     typedef GraphBase::NodeId NodeId;
434     std::vector<NodeId> NodeStack;
435
436     // Consume worklists.
437     while (true) {
438       if (!OptimallyReducibleNodes.empty()) {
439         NodeSet::iterator NItr = OptimallyReducibleNodes.begin();
440         NodeId NId = *NItr;
441         OptimallyReducibleNodes.erase(NItr);
442         NodeStack.push_back(NId);
443         switch (G.getNodeDegree(NId)) {
444         case 0:
445           break;
446         case 1:
447           applyR1(G, NId);
448           break;
449         case 2:
450           applyR2(G, NId);
451           break;
452         default: llvm_unreachable("Not an optimally reducible node.");
453         }
454       } else if (!ConservativelyAllocatableNodes.empty()) {
455         // Conservatively allocatable nodes will never spill. For now just
456         // take the first node in the set and push it on the stack. When we
457         // start optimizing more heavily for register preferencing, it may
458         // would be better to push nodes with lower 'expected' or worst-case
459         // register costs first (since early nodes are the most
460         // constrained).
461         NodeSet::iterator NItr = ConservativelyAllocatableNodes.begin();
462         NodeId NId = *NItr;
463         ConservativelyAllocatableNodes.erase(NItr);
464         NodeStack.push_back(NId);
465         G.disconnectAllNeighborsFromNode(NId);
466
467       } else if (!NotProvablyAllocatableNodes.empty()) {
468         NodeSet::iterator NItr =
469           std::min_element(NotProvablyAllocatableNodes.begin(),
470                            NotProvablyAllocatableNodes.end(),
471                            SpillCostComparator(G));
472         NodeId NId = *NItr;
473         NotProvablyAllocatableNodes.erase(NItr);
474         NodeStack.push_back(NId);
475         G.disconnectAllNeighborsFromNode(NId);
476       } else
477         break;
478     }
479
480     return NodeStack;
481   }
482
483   class SpillCostComparator {
484   public:
485     SpillCostComparator(const Graph& G) : G(G) {}
486     bool operator()(NodeId N1Id, NodeId N2Id) {
487       PBQPNum N1SC = G.getNodeCosts(N1Id)[0] / G.getNodeDegree(N1Id);
488       PBQPNum N2SC = G.getNodeCosts(N2Id)[0] / G.getNodeDegree(N2Id);
489       return N1SC < N2SC;
490     }
491   private:
492     const Graph& G;
493   };
494
495   Graph& G;
496   typedef std::set<NodeId> NodeSet;
497   NodeSet OptimallyReducibleNodes;
498   NodeSet ConservativelyAllocatableNodes;
499   NodeSet NotProvablyAllocatableNodes;
500 };
501
502 class PBQPRAGraph : public PBQP::Graph<RegAllocSolverImpl> {
503 private:
504   typedef PBQP::Graph<RegAllocSolverImpl> BaseT;
505 public:
506   PBQPRAGraph(GraphMetadata Metadata) : BaseT(Metadata) {}
507
508   /// @brief Dump this graph to dbgs().
509   void dump() const;
510
511   /// @brief Dump this graph to an output stream.
512   /// @param OS Output stream to print on.
513   void dump(raw_ostream &OS) const;
514
515   /// @brief Print a representation of this graph in DOT format.
516   /// @param OS Output stream to print on.
517   void printDot(raw_ostream &OS) const;
518 };
519
520 inline Solution solve(PBQPRAGraph& G) {
521   if (G.empty())
522     return Solution();
523   RegAllocSolverImpl RegAllocSolver(G);
524   return RegAllocSolver.solve();
525 }
526
527 } // namespace RegAlloc
528 } // namespace PBQP
529
530 /// @brief Create a PBQP register allocator instance.
531 FunctionPass *
532 createPBQPRegisterAllocator(char *customPassID = nullptr);
533
534 } // namespace llvm
535
536 #endif /* LLVM_CODEGEN_REGALLOCPBQP_H */