<div dir="ltr"><br><div class="gmail_extra"><br><br><div class="gmail_quote">On Fri, Feb 28, 2014 at 2:25 PM, Lang Hames <span dir="ltr"><<a href="mailto:lhames@gmail.com" target="_blank">lhames@gmail.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">Author: lhames<br>
Date: Fri Feb 28 16:25:24 2014<br>
New Revision: 202551<br>
<br>
URL: <a href="http://llvm.org/viewvc/llvm-project?rev=202551&view=rev" target="_blank">http://llvm.org/viewvc/llvm-project?rev=202551&view=rev</a><br>
Log:<br>
New PBQP solver, and updates to the PBQP graph.<br>
<br>
The previous PBQP solver was very robust but consumed a lot of memory,<br>
performed a lot of redundant computation, and contained some unnecessarily tight<br>
coupling that prevented experimentation with novel solution techniques. This new<br>
solver is an attempt to address these shortcomings.<br>
<br>
Important/interesting changes:<br>
<br>
1) The domain-independent PBQP solver class, HeuristicSolverImpl, is gone.<br>
It is replaced by a register allocation specific solver, PBQP::RegAlloc::Solver<br>
(see RegAllocSolver.h).<br>
<br>
The optimal reduction rules and the backpropagation algorithm have been extracted<br>
into stand-alone functions (see ReductionRules.h), which can be used to build<br>
domain specific PBQP solvers. This provides many more opportunities for<br>
domain-specific knowledge to inform the PBQP solvers' decisions. In theory this<br>
should allow us to generate better solutions. In practice, we can at least test<br>
out ideas now.<br>
<br>
As a side benefit, I believe the new solver is more readable than the old one.<br>
<br>
2) The solver type is now a template parameter of the PBQP graph.<br>
<br>
This allows the graph to notify the solver of any modifications made (e.g. by<br>
domain independent rules) without the overhead of a virtual call. It also allows<br>
the solver to supply policy information to the graph (see below).<br>
<br>
3) Significantly reduced memory overhead.<br>
<br>
Memory management policy is now an explicit property of the PBQP graph (via<br>
the CostAllocator typedef on the graph's solver template argument). Because PBQP<br>
graphs for register allocation tend to contain many redundant instances of<br>
single values (E.g. the value representing an interference constraint between<br>
GPRs), the new RASolver class uses a uniquing scheme. This massively reduces<br>
memory consumption for large register allocation problems. For example, looking<br>
at the largest interference graph in each of the SPEC2006 benchmarks (the<br>
largest graph will always set the memory consumption high-water mark for PBQP),<br>
the average memory reduction for the PBQP costs was 400x. That's times, not<br>
percent. The highest was 1400x. Yikes. So - this is fixed.<br>
<br>
"PBQP: No longer feasting upon every last byte of your RAM".<br></blockquote><div><br></div><div>Omnomnom. Do you have any (even rough) numbers on the memory footprint reduction factor?</div><div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
<br>
Minor details:<br>
<br>
- Fully C++11'd. Never copy-construct another vector/matrix!<br>
<br>
- Cute tricks with cost metadata: Metadata that is derived solely from cost<br>
matrices/vectors is attached directly to the cost instances themselves. That way<br>
if you unique the costs you never have to recompute the metadata. 400x less<br>
memory means 400x less cost metadata (re)computation.<br>
<br>
Special thanks to Arnaud de Grandmaison, who has been the source of much<br>
encouragement, and of many very useful test cases.<br>
<br>
This new solver forms the basis for future work, of which there's plenty to do.<br>
I will be adding TODO notes shortly.<br>
<br>
- Lang.<br>
<br>
<br>
Added:<br>
llvm/trunk/include/llvm/CodeGen/PBQP/CostAllocator.h<br>
llvm/trunk/include/llvm/CodeGen/PBQP/ReductionRules.h<br>
llvm/trunk/include/llvm/CodeGen/PBQP/RegAllocSolver.h<br>
Removed:<br>
llvm/trunk/include/llvm/CodeGen/PBQP/HeuristicBase.h<br>
llvm/trunk/include/llvm/CodeGen/PBQP/HeuristicSolver.h<br>
llvm/trunk/include/llvm/CodeGen/PBQP/Heuristics/<br>
Modified:<br>
llvm/trunk/include/llvm/CodeGen/PBQP/Graph.h<br>
llvm/trunk/include/llvm/CodeGen/PBQP/Math.h<br>
llvm/trunk/include/llvm/CodeGen/PBQP/Solution.h<br>
llvm/trunk/include/llvm/CodeGen/RegAllocPBQP.h<br>
llvm/trunk/lib/CodeGen/RegAllocPBQP.cpp<br>
<br>
Added: llvm/trunk/include/llvm/CodeGen/PBQP/CostAllocator.h<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/CostAllocator.h?rev=202551&view=auto" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/CostAllocator.h?rev=202551&view=auto</a><br>
==============================================================================<br>
--- llvm/trunk/include/llvm/CodeGen/PBQP/CostAllocator.h (added)<br>
+++ llvm/trunk/include/llvm/CodeGen/PBQP/CostAllocator.h Fri Feb 28 16:25:24 2014<br>
@@ -0,0 +1,147 @@<br>
+//===---------- CostAllocator.h - PBQP Cost Allocator -----------*- C++ -*-===//<br>
+//<br>
+// The LLVM Compiler Infrastructure<br>
+//<br>
+// This file is distributed under the University of Illinois Open Source<br>
+// License. See LICENSE.TXT for details.<br>
+//<br>
+//===----------------------------------------------------------------------===//<br>
+//<br>
+// Defines classes conforming to the PBQP cost value manager concept.<br>
+//<br>
+// Cost value managers are memory managers for PBQP cost values (vectors and<br>
+// matrices). Since PBQP graphs can grow very large (E.g. hundreds of thousands<br>
+// of edges on the largest function in SPEC2006).<br>
+//<br>
+//===----------------------------------------------------------------------===//<br>
+<br>
+#ifndef LLVM_COSTALLOCATOR_H<br>
+#define LLVM_COSTALLOCATOR_H<br>
+<br>
+#include <set><br>
+#include <type_traits><br>
+<br>
+namespace PBQP {<br>
+<br>
+template <typename CostT,<br>
+ typename CostKeyTComparator><br>
+class CostPool {<br>
+public:<br>
+<br>
+ class PoolEntry {<br>
+ public:<br>
+ template <typename CostKeyT><br>
+ PoolEntry(CostPool &pool, CostKeyT cost)<br>
+ : pool(pool), cost(std::move(cost)), refCount(0) {}<br>
+ ~PoolEntry() { pool.removeEntry(this); }<br>
+ void incRef() { ++refCount; }<br></blockquote><br class=""><div><clippy>It looks like you're doing manual reference counting. Have you considered using a general-purpose reference counting smart pointer?</clippy> (<a href="http://llvm.org/docs/doxygen/html/classllvm_1_1IntrusiveRefCntPtr.html">http://llvm.org/docs/doxygen/html/classllvm_1_1IntrusiveRefCntPtr.html</a> or std::shared_ptr, etc)</div>
<div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
+ bool decRef() { --refCount; return (refCount == 0); }<br></blockquote><div><br></div><div>() around return expression aren't necessary/are a bit weird.<br><br>(is this all run through clang-format? Having multiple statements on a single line definition seems a bit uncommon/not idiomatic in the LLVM codebase)</div>
<div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
+ CostT& getCost() { return cost; }<br>
+ const CostT& getCost() const { return cost; }<br>
+ private:<br>
+ CostPool &pool;<br>
+ CostT cost;<br>
+ std::size_t refCount;<br>
+ };<br>
+<br>
+ class PoolRef {<br>
+ public:<br>
+ PoolRef(PoolEntry *entry) : entry(entry) {<br>
+ this->entry->incRef(); </blockquote><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
+ }<br>
+ PoolRef(const PoolRef &r) {<br>
+ entry = r.entry;<br>
+ entry->incRef();<br>
+ }<br>
+ PoolRef& operator=(const PoolRef &r) {<br>
+ assert(entry != 0 && "entry should not be null.");<br>
+ PoolEntry *temp = r.entry;<br>
+ temp->incRef();<br>
+ entry->decRef();<br>
+ entry = temp;<br>
+ return *this;<br>
+ }<br>
+<br>
+ ~PoolRef() {<br>
+ if (entry->decRef())<br>
+ delete entry;<br>
+ }<br>
+ void reset(PoolEntry *entry) {<br>
+ entry->incRef();<br>
+ this->entry->decRef();<br>
+ this->entry = entry;<br>
+ }<br>
+ CostT& operator*() { return entry->getCost(); }<br>
+ const CostT& operator*() const { return entry->getCost(); }<br>
+ CostT* operator->() { return &entry->getCost(); }<br>
+ const CostT* operator->() const { return &entry->getCost(); }<br>
+ private:<br>
+ PoolEntry *entry;<br>
+ };<br>
+<br>
+private:<br>
+ class EntryComparator {<br>
+ public:<br>
+ template <typename CostKeyT><br>
+ typename std::enable_if<<br>
+ !std::is_same<PoolEntry*,<br>
+ typename std::remove_const<CostKeyT>::type>::value,<br>
+ bool>::type<br>
+ operator()(const PoolEntry* a, const CostKeyT &b) {<br>
+ return compare(a->getCost(), b);<br>
+ }<br>
+ bool operator()(const PoolEntry* a, const PoolEntry* b) {<br>
+ return compare(a->getCost(), b->getCost());<br>
+ }<br>
+ private:<br>
+ CostKeyTComparator compare;<br>
+ };<br>
+<br>
+ typedef std::set<PoolEntry*, EntryComparator> EntrySet;<br>
+<br>
+ EntrySet entrySet;<br>
+<br>
+ void removeEntry(PoolEntry *p) { entrySet.erase(p); }<br>
+<br>
+public:<br>
+<br>
+ template <typename CostKeyT><br>
+ PoolRef getCost(CostKeyT costKey) {<br>
+ typename EntrySet::iterator itr =<br>
+ std::lower_bound(entrySet.begin(), entrySet.end(), costKey,<br>
+ EntryComparator());<br>
+<br>
+ if (itr != entrySet.end() && costKey == (*itr)->getCost())<br>
+ return PoolRef(*itr);<br>
+<br>
+ PoolEntry *p = new PoolEntry(*this, std::move(costKey));<br>
+ entrySet.insert(itr, p);<br>
+ return PoolRef(p);<br>
+ }<br>
+};<br>
+<br>
+template <typename VectorT, typename VectorTComparator,<br>
+ typename MatrixT, typename MatrixTComparator><br>
+class PoolCostAllocator {<br>
+private:<br>
+ typedef CostPool<VectorT, VectorTComparator> VectorCostPool;<br>
+ typedef CostPool<MatrixT, MatrixTComparator> MatrixCostPool;<br>
+public:<br>
+ typedef VectorT Vector;<br>
+ typedef MatrixT Matrix;<br>
+ typedef typename VectorCostPool::PoolRef VectorPtr;<br>
+ typedef typename MatrixCostPool::PoolRef MatrixPtr;<br>
+<br>
+ template <typename VectorKeyT><br>
+ VectorPtr getVector(VectorKeyT v) { return vectorPool.getCost(std::move(v)); }<br>
+<br>
+ template <typename MatrixKeyT><br>
+ MatrixPtr getMatrix(MatrixKeyT m) { return matrixPool.getCost(std::move(m)); }<br>
+private:<br>
+ VectorCostPool vectorPool;<br>
+ MatrixCostPool matrixPool;<br>
+};<br>
+<br>
+}<br>
+<br>
+#endif // LLVM_COSTALLOCATOR_H<br>
<br>
Modified: llvm/trunk/include/llvm/CodeGen/PBQP/Graph.h<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/Graph.h?rev=202551&r1=202550&r2=202551&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/Graph.h?rev=202551&r1=202550&r2=202551&view=diff</a><br>
==============================================================================<br>
--- llvm/trunk/include/llvm/CodeGen/PBQP/Graph.h (original)<br>
+++ llvm/trunk/include/llvm/CodeGen/PBQP/Graph.h Fri Feb 28 16:25:24 2014<br>
@@ -15,414 +15,526 @@<br>
#ifndef LLVM_CODEGEN_PBQP_GRAPH_H<br>
#define LLVM_CODEGEN_PBQP_GRAPH_H<br>
<br>
-#include "Math.h"<br>
#include "llvm/ADT/ilist.h"<br>
#include "llvm/ADT/ilist_node.h"<br>
+#include "llvm/Support/Compiler.h"<br>
#include <list><br>
#include <map><br>
#include <set><br>
<br>
namespace PBQP {<br>
<br>
- /// PBQP Graph class.<br>
- /// Instances of this class describe PBQP problems.<br>
- class Graph {<br>
+ class GraphBase {<br>
public:<br>
-<br>
typedef unsigned NodeId;<br>
typedef unsigned EdgeId;<br>
+ };<br>
<br>
+ /// PBQP Graph class.<br>
+ /// Instances of this class describe PBQP problems.<br>
+ ///<br>
+ template <typename SolverT><br>
+ class Graph : public GraphBase {<br>
private:<br>
-<br>
- typedef std::set<NodeId> AdjEdgeList;<br>
-<br>
+ typedef typename SolverT::CostAllocator CostAllocator;<br>
public:<br>
-<br>
- typedef AdjEdgeList::iterator AdjEdgeItr;<br>
+ typedef typename SolverT::RawVector RawVector;<br>
+ typedef typename SolverT::RawMatrix RawMatrix;<br>
+ typedef typename SolverT::Vector Vector;<br>
+ typedef typename SolverT::Matrix Matrix;<br>
+ typedef typename CostAllocator::VectorPtr VectorPtr;<br>
+ typedef typename CostAllocator::MatrixPtr MatrixPtr;<br>
+ typedef typename SolverT::NodeMetadata NodeMetadata;<br>
+ typedef typename SolverT::EdgeMetadata EdgeMetadata;<br>
<br>
private:<br>
<br>
class NodeEntry {<br>
- private:<br>
- Vector costs;<br>
- AdjEdgeList adjEdges;<br>
- void *data;<br>
- NodeEntry() : costs(0, 0) {}<br>
public:<br>
- NodeEntry(const Vector &costs) : costs(costs), data(0) {}<br>
- Vector& getCosts() { return costs; }<br>
- const Vector& getCosts() const { return costs; }<br>
- unsigned getDegree() const { return adjEdges.size(); }<br>
- AdjEdgeItr edgesBegin() { return adjEdges.begin(); }<br>
- AdjEdgeItr edgesEnd() { return adjEdges.end(); }<br>
- AdjEdgeItr addEdge(EdgeId e) {<br>
- return adjEdges.insert(adjEdges.end(), e);<br>
- }<br>
- void removeEdge(AdjEdgeItr ae) {<br>
- adjEdges.erase(ae);<br>
- }<br>
- void setData(void *data) { this->data = data; }<br>
- void* getData() { return data; }<br>
+ typedef std::set<NodeId> AdjEdgeList;<br>
+ typedef AdjEdgeList::const_iterator AdjEdgeItr;<br>
+ NodeEntry(VectorPtr Costs) : Costs(Costs) {}<br>
+<br>
+ VectorPtr Costs;<br>
+ NodeMetadata Metadata;<br>
+ AdjEdgeList AdjEdgeIds;<br>
};<br>
<br>
class EdgeEntry {<br>
- private:<br>
- NodeId node1, node2;<br>
- Matrix costs;<br>
- AdjEdgeItr node1AEItr, node2AEItr;<br>
- void *data;<br>
- EdgeEntry() : costs(0, 0, 0), data(0) {}<br>
public:<br>
- EdgeEntry(NodeId node1, NodeId node2, const Matrix &costs)<br>
- : node1(node1), node2(node2), costs(costs) {}<br>
- NodeId getNode1() const { return node1; }<br>
- NodeId getNode2() const { return node2; }<br>
- Matrix& getCosts() { return costs; }<br>
- const Matrix& getCosts() const { return costs; }<br>
- void setNode1AEItr(AdjEdgeItr ae) { node1AEItr = ae; }<br>
- AdjEdgeItr getNode1AEItr() { return node1AEItr; }<br>
- void setNode2AEItr(AdjEdgeItr ae) { node2AEItr = ae; }<br>
- AdjEdgeItr getNode2AEItr() { return node2AEItr; }<br>
- void setData(void *data) { this->data = data; }<br>
- void *getData() { return data; }<br>
+ EdgeEntry(NodeId N1Id, NodeId N2Id, MatrixPtr Costs)<br>
+ : Costs(Costs), N1Id(N1Id), N2Id(N2Id) {}<br>
+ void invalidate() {<br>
+ N1Id = N2Id = Graph::invalidNodeId();<br>
+ Costs = nullptr;<br>
+ }<br>
+ NodeId getN1Id() const { return N1Id; }<br>
+ NodeId getN2Id() const { return N2Id; }<br>
+ MatrixPtr Costs;<br>
+ EdgeMetadata Metadata;<br>
+ private:<br>
+ NodeId N1Id, N2Id;<br>
};<br>
<br>
// ----- MEMBERS -----<br>
<br>
+ CostAllocator CostAlloc;<br>
+ SolverT *Solver;<br>
+<br>
typedef std::vector<NodeEntry> NodeVector;<br>
typedef std::vector<NodeId> FreeNodeVector;<br>
- NodeVector nodes;<br>
- FreeNodeVector freeNodes;<br>
+ NodeVector Nodes;<br>
+ FreeNodeVector FreeNodeIds;<br>
<br>
typedef std::vector<EdgeEntry> EdgeVector;<br>
typedef std::vector<EdgeId> FreeEdgeVector;<br>
- EdgeVector edges;<br>
- FreeEdgeVector freeEdges;<br>
+ EdgeVector Edges;<br>
+ FreeEdgeVector FreeEdgeIds;<br>
<br>
// ----- INTERNAL METHODS -----<br>
<br>
- NodeEntry& getNode(NodeId nId) { return nodes[nId]; }<br>
- const NodeEntry& getNode(NodeId nId) const { return nodes[nId]; }<br>
+ NodeEntry& getNode(NodeId NId) { return Nodes[NId]; }<br>
+ const NodeEntry& getNode(NodeId NId) const { return Nodes[NId]; }<br>
<br>
- EdgeEntry& getEdge(EdgeId eId) { return edges[eId]; }<br>
- const EdgeEntry& getEdge(EdgeId eId) const { return edges[eId]; }<br>
+ EdgeEntry& getEdge(EdgeId EId) { return Edges[EId]; }<br>
+ const EdgeEntry& getEdge(EdgeId EId) const { return Edges[EId]; }<br>
<br>
- NodeId addConstructedNode(const NodeEntry &n) {<br>
- NodeId nodeId = 0;<br>
- if (!freeNodes.empty()) {<br>
- nodeId = freeNodes.back();<br>
- freeNodes.pop_back();<br>
- nodes[nodeId] = n;<br>
+ NodeId addConstructedNode(const NodeEntry &N) {<br>
+ NodeId NId = 0;<br>
+ if (!FreeNodeIds.empty()) {<br>
+ NId = FreeNodeIds.back();<br>
+ FreeNodeIds.pop_back();<br>
+ Nodes[NId] = std::move(N);<br></blockquote><div><br></div><div>Moving from a const ref? Did you intend to take the 'N' parameter by value instead? </div><div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
} else {<br>
- nodeId = nodes.size();<br>
- nodes.push_back(n);<br>
+ NId = Nodes.size();<br>
+ Nodes.push_back(std::move(N));<br>
}<br>
- return nodeId;<br>
+ return NId;<br>
}<br>
<br>
- EdgeId addConstructedEdge(const EdgeEntry &e) {<br>
- assert(findEdge(e.getNode1(), e.getNode2()) == invalidEdgeId() &&<br>
+ EdgeId addConstructedEdge(const EdgeEntry &E) {<br>
+ assert(findEdge(E.getN1Id(), E.getN2Id()) == invalidEdgeId() &&<br>
"Attempt to add duplicate edge.");<br>
- EdgeId edgeId = 0;<br>
- if (!freeEdges.empty()) {<br>
- edgeId = freeEdges.back();<br>
- freeEdges.pop_back();<br>
- edges[edgeId] = e;<br>
+ EdgeId EId = 0;<br>
+ if (!FreeEdgeIds.empty()) {<br>
+ EId = FreeEdgeIds.back();<br>
+ FreeEdgeIds.pop_back();<br>
+ Edges[EId] = std::move(E);<br></blockquote><div><br></div><div>More move from const ref parameter.</div><div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
} else {<br>
- edgeId = edges.size();<br>
- edges.push_back(e);<br>
+ EId = Edges.size();<br>
+ Edges.push_back(std::move(E));<br>
}<br>
<br>
- EdgeEntry &ne = getEdge(edgeId);<br>
- NodeEntry &n1 = getNode(ne.getNode1());<br>
- NodeEntry &n2 = getNode(ne.getNode2());<br>
+ EdgeEntry &NE = getEdge(EId);<br></blockquote><div><br></div><div>^ could this be a const ref?</div><div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
+ NodeEntry &N1 = getNode(NE.getN1Id());<br>
+ NodeEntry &N2 = getNode(NE.getN2Id());<br>
<br>
// Sanity check on matrix dimensions:<br>
- assert((n1.getCosts().getLength() == ne.getCosts().getRows()) &&<br>
- (n2.getCosts().getLength() == ne.getCosts().getCols()) &&<br>
+ assert((N1.Costs->getLength() == NE.Costs->getRows()) &&<br>
+ (N2.Costs->getLength() == NE.Costs->getCols()) &&<br>
"Edge cost dimensions do not match node costs dimensions.");<br>
<br>
- ne.setNode1AEItr(n1.addEdge(edgeId));<br>
- ne.setNode2AEItr(n2.addEdge(edgeId));<br>
- return edgeId;<br>
+ N1.AdjEdgeIds.insert(EId);<br>
+ N2.AdjEdgeIds.insert(EId);<br>
+ return EId;<br>
}<br>
<br>
- Graph(const Graph &other) {}<br>
- void operator=(const Graph &other) {}<br>
+ Graph(const Graph &Other) {}<br>
+ void operator=(const Graph &Other) {}<br></blockquote><div><br></div><div>Do you need these explicitly? Or could you take the implicit default? (or provide an explicit "= default"?)</div><div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
<br>
public:<br>
<br>
+ typedef typename NodeEntry::AdjEdgeItr AdjEdgeItr;<br>
+<br>
class NodeItr {<br>
public:<br>
- NodeItr(NodeId nodeId, const Graph &g)<br>
- : nodeId(nodeId), endNodeId(g.nodes.size()), freeNodes(g.freeNodes) {<br>
- this->nodeId = findNextInUse(nodeId); // Move to the first in-use nodeId<br>
+ NodeItr(NodeId CurNId, const Graph &G)<br>
+ : CurNId(CurNId), EndNId(G.Nodes.size()), FreeNodeIds(G.FreeNodeIds) {<br>
+ this->CurNId = findNextInUse(CurNId); // Move to first in-use node id<br>
}<br>
<br>
- bool operator==(const NodeItr& n) const { return nodeId == n.nodeId; }<br>
- bool operator!=(const NodeItr& n) const { return !(*this == n); }<br>
- NodeItr& operator++() { nodeId = findNextInUse(++nodeId); return *this; }<br>
- NodeId operator*() const { return nodeId; }<br>
+ bool operator==(const NodeItr &O) const { return CurNId == O.CurNId; }<br>
+ bool operator!=(const NodeItr &O) const { return !(*this == O); }<br>
+ NodeItr& operator++() { CurNId = findNextInUse(++CurNId); return *this; }<br>
+ NodeId operator*() const { return CurNId; }<br>
<br>
private:<br>
- NodeId findNextInUse(NodeId n) const {<br>
- while (n < endNodeId &&<br>
- std::find(freeNodes.begin(), freeNodes.end(), n) !=<br>
- freeNodes.end()) {<br>
- ++n;<br>
+ NodeId findNextInUse(NodeId NId) const {<br>
+ while (NId < EndNId &&<br>
+ std::find(FreeNodeIds.begin(), FreeNodeIds.end(), NId) !=<br>
+ FreeNodeIds.end()) {<br>
+ ++NId;<br>
}<br></blockquote><div><br></div><div>We don't usually bother with {} on single line blocks - but I know the codebase varies on how stringently that's applied. (& local styles do happen)</div><div> </div>
<blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
- return n;<br>
+ return NId;<br>
}<br>
<br>
- NodeId nodeId, endNodeId;<br>
- const FreeNodeVector& freeNodes;<br>
+ NodeId CurNId, EndNId;<br>
+ const FreeNodeVector &FreeNodeIds;<br>
};<br>
<br>
class EdgeItr {<br>
public:<br>
- EdgeItr(EdgeId edgeId, const Graph &g)<br>
- : edgeId(edgeId), endEdgeId(g.edges.size()), freeEdges(g.freeEdges) {<br>
- this->edgeId = findNextInUse(edgeId); // Move to the first in-use edgeId<br>
+ EdgeItr(EdgeId CurEId, const Graph &G)<br>
+ : CurEId(CurEId), EndEId(G.Edges.size()), FreeEdgeIds(G.FreeEdgeIds) {<br>
+ this->CurEId = findNextInUse(CurEId); // Move to first in-use edge id<br>
}<br>
<br>
- bool operator==(const EdgeItr& n) const { return edgeId == n.edgeId; }<br>
- bool operator!=(const EdgeItr& n) const { return !(*this == n); }<br>
- EdgeItr& operator++() { edgeId = findNextInUse(++edgeId); return *this; }<br>
- EdgeId operator*() const { return edgeId; }<br>
+ bool operator==(const EdgeItr &O) const { return CurEId == O.CurEId; }<br>
+ bool operator!=(const EdgeItr &O) const { return !(*this == O); }<br>
+ EdgeItr& operator++() { CurEId = findNextInUse(++CurEId); return *this; }<br>
+ EdgeId operator*() const { return CurEId; }<br>
<br>
private:<br>
- EdgeId findNextInUse(EdgeId n) const {<br>
- while (n < endEdgeId &&<br>
- std::find(freeEdges.begin(), freeEdges.end(), n) !=<br>
- freeEdges.end()) {<br>
- ++n;<br>
+ EdgeId findNextInUse(EdgeId EId) const {<br>
+ while (EId < EndEId &&<br>
+ std::find(FreeEdgeIds.begin(), FreeEdgeIds.end(), EId) !=<br>
+ FreeEdgeIds.end()) {<br>
+ ++EId;<br>
}<br>
- return n;<br>
+ return EId;<br>
+ }<br>
+<br>
+ EdgeId CurEId, EndEId;<br>
+ const FreeEdgeVector &FreeEdgeIds;<br>
+ };<br>
+<br>
+ class NodeIdSet {<br>
+ public:<br>
+ NodeIdSet(const Graph &G) : G(G) { }<br>
+ NodeItr begin() const { return NodeItr(0, G); }<br>
+ NodeItr end() const { return NodeItr(G.Nodes.size(), G); }<br>
+ bool empty() const { return G.Nodes.empty(); }<br>
+ typename NodeVector::size_type size() const {<br>
+ return G.Nodes.size() - G.FreeNodeIds.size();<br>
}<br>
+ private:<br>
+ const Graph& G;<br>
+ };<br>
<br>
- EdgeId edgeId, endEdgeId;<br>
- const FreeEdgeVector& freeEdges;<br>
+ class EdgeIdSet {<br>
+ public:<br>
+ EdgeIdSet(const Graph &G) : G(G) { }<br>
+ EdgeItr begin() const { return EdgeItr(0, G); }<br>
+ EdgeItr end() const { return EdgeItr(G.Edges.size(), G); }<br>
+ bool empty() const { return G.Edges.empty(); }<br>
+ typename NodeVector::size_type size() const {<br>
+ return G.Edges.size() - G.FreeEdgeIds.size();<br>
+ }<br>
+ private:<br>
+ const Graph& G;<br>
+ };<br>
+<br>
+ class AdjEdgeIdSet {<br>
+ public:<br>
+ AdjEdgeIdSet(const NodeEntry &NE) : NE(NE) { }<br>
+ typename NodeEntry::AdjEdgeItr begin() const {<br>
+ return NE.AdjEdgeIds.begin();<br>
+ }<br>
+ typename NodeEntry::AdjEdgeItr end() const {<br>
+ return NE.AdjEdgeIds.end();<br>
+ }<br>
+ bool empty() const { return NE.AdjEdges.empty(); }<br>
+ typename NodeEntry::AdjEdgeList::size_type size() const {<br>
+ return NE.AdjEdgeIds.size();<br>
+ }<br>
+ private:<br>
+ const NodeEntry &NE;<br>
};<br>
<br>
/// \brief Construct an empty PBQP graph.<br>
- Graph() {}<br>
+ Graph() : Solver(nullptr) { }<br>
+<br>
+ /// \brief Lock this graph to the given solver instance in preparation<br>
+ /// for running the solver. This method will call solver.handleAddNode for<br>
+ /// each node in the graph, and handleAddEdge for each edge, to give the<br>
+ /// solver an opportunity to set up any requried metadata.<br>
+ void setSolver(SolverT &S) {<br>
+ assert(Solver == nullptr && "Solver already set. Call unsetSolver().");<br>
+ Solver = &S;<br>
+ for (auto NId : nodeIds())<br>
+ Solver->handleAddNode(NId);<br>
+ for (auto EId : edgeIds())<br>
+ Solver->handleAddEdge(EId);<br>
+ }<br>
+<br>
+ /// \brief Release from solver instance.<br>
+ void unsetSolver() {<br>
+ assert(Solver != nullptr && "Solver not set.");<br>
+ Solver = nullptr;<br>
+ }<br>
<br>
/// \brief Add a node with the given costs.<br>
- /// @param costs Cost vector for the new node.<br>
+ /// @param Costs Cost vector for the new node.<br>
/// @return Node iterator for the added node.<br>
- NodeId addNode(const Vector &costs) {<br>
- return addConstructedNode(NodeEntry(costs));<br>
+ template <typename OtherVectorT><br>
+ NodeId addNode(OtherVectorT Costs) {<br>
+ // Get cost vector from the problem domain<br>
+ VectorPtr AllocatedCosts = CostAlloc.getVector(std::move(Costs));<br>
+ NodeId NId = addConstructedNode(NodeEntry(AllocatedCosts));<br>
+ if (Solver)<br>
+ Solver->handleAddNode(NId);<br>
+ return NId;<br>
}<br>
<br>
/// \brief Add an edge between the given nodes with the given costs.<br>
- /// @param n1Id First node.<br>
- /// @param n2Id Second node.<br>
+ /// @param N1Id First node.<br>
+ /// @param N2Id Second node.<br>
/// @return Edge iterator for the added edge.<br>
- EdgeId addEdge(NodeId n1Id, NodeId n2Id, const Matrix &costs) {<br>
- assert(getNodeCosts(n1Id).getLength() == costs.getRows() &&<br>
- getNodeCosts(n2Id).getLength() == costs.getCols() &&<br>
+ template <typename OtherVectorT><br>
+ EdgeId addEdge(NodeId N1Id, NodeId N2Id, OtherVectorT Costs) {<br>
+ assert(getNodeCosts(N1Id).getLength() == Costs.getRows() &&<br>
+ getNodeCosts(N2Id).getLength() == Costs.getCols() &&<br>
"Matrix dimensions mismatch.");<br>
- return addConstructedEdge(EdgeEntry(n1Id, n2Id, costs));<br>
+ // Get cost matrix from the problem domain.<br>
+ MatrixPtr AllocatedCosts = CostAlloc.getMatrix(std::move(Costs));<br>
+ EdgeId EId = addConstructedEdge(EdgeEntry(N1Id, N2Id, AllocatedCosts));<br>
+ if (Solver)<br>
+ Solver->handleAddEdge(EId);<br>
+ return EId;<br>
}<br>
<br>
+ /// \brief Returns true if the graph is empty.<br>
+ bool empty() const { return NodeIdSet(*this).empty(); }<br>
+<br>
+ NodeIdSet nodeIds() const { return NodeIdSet(*this); }<br>
+ EdgeIdSet edgeIds() const { return EdgeIdSet(*this); }<br>
+<br>
+ AdjEdgeIdSet adjEdgeIds(NodeId NId) { return AdjEdgeIdSet(getNode(NId)); }<br>
+<br>
/// \brief Get the number of nodes in the graph.<br>
/// @return Number of nodes in the graph.<br>
- unsigned getNumNodes() const { return nodes.size() - freeNodes.size(); }<br>
+ unsigned getNumNodes() const { return NodeIdSet(*this).size(); }<br>
<br>
/// \brief Get the number of edges in the graph.<br>
/// @return Number of edges in the graph.<br>
- unsigned getNumEdges() const { return edges.size() - freeEdges.size(); }<br>
+ unsigned getNumEdges() const { return EdgeIdSet(*this).size(); }<br>
<br>
- /// \brief Get a node's cost vector.<br>
- /// @param nId Node id.<br>
+ /// \brief Set a node's cost vector.<br>
+ /// @param NId Node to update.<br>
+ /// @param Costs New costs to set.<br>
/// @return Node cost vector.<br>
- Vector& getNodeCosts(NodeId nId) { return getNode(nId).getCosts(); }<br>
+ template <typename OtherVectorT><br>
+ void setNodeCosts(NodeId NId, OtherVectorT Costs) {<br>
+ VectorPtr AllocatedCosts = CostAlloc.getVector(std::move(Costs));<br>
+ if (Solver)<br>
+ Solver->handleSetNodeCosts(NId, *AllocatedCosts);<br>
+ getNode(NId).Costs = AllocatedCosts;<br>
+ }<br>
<br>
/// \brief Get a node's cost vector (const version).<br>
- /// @param nId Node id.<br>
+ /// @param NId Node id.<br>
/// @return Node cost vector.<br>
- const Vector& getNodeCosts(NodeId nId) const {<br>
- return getNode(nId).getCosts();<br>
+ const Vector& getNodeCosts(NodeId NId) const {<br>
+ return *getNode(NId).Costs;<br>
}<br>
<br>
- /// \brief Set a node's data pointer.<br>
- /// @param nId Node id.<br>
- /// @param data Pointer to node data.<br>
- ///<br>
- /// Typically used by a PBQP solver to attach data to aid in solution.<br>
- void setNodeData(NodeId nId, void *data) { getNode(nId).setData(data); }<br>
-<br>
- /// \brief Get the node's data pointer.<br>
- /// @param nId Node id.<br>
- /// @return Pointer to node data.<br>
- void* getNodeData(NodeId nId) { return getNode(nId).getData(); }<br>
-<br>
- /// \brief Get an edge's cost matrix.<br>
- /// @param eId Edge id.<br>
- /// @return Edge cost matrix.<br>
- Matrix& getEdgeCosts(EdgeId eId) { return getEdge(eId).getCosts(); }<br>
-<br>
- /// \brief Get an edge's cost matrix (const version).<br>
- /// @param eId Edge id.<br>
- /// @return Edge cost matrix.<br>
- const Matrix& getEdgeCosts(EdgeId eId) const {<br>
- return getEdge(eId).getCosts();<br>
+ NodeMetadata& getNodeMetadata(NodeId NId) {<br>
+ return getNode(NId).Metadata;<br>
}<br>
<br>
- /// \brief Set an edge's data pointer.<br>
- /// @param eId Edge id.<br>
- /// @param data Pointer to edge data.<br>
- ///<br>
- /// Typically used by a PBQP solver to attach data to aid in solution.<br>
- void setEdgeData(EdgeId eId, void *data) { getEdge(eId).setData(data); }<br>
-<br>
- /// \brief Get an edge's data pointer.<br>
- /// @param eId Edge id.<br>
- /// @return Pointer to edge data.<br>
- void* getEdgeData(EdgeId eId) { return getEdge(eId).getData(); }<br>
-<br>
- /// \brief Get a node's degree.<br>
- /// @param nId Node id.<br>
- /// @return The degree of the node.<br>
- unsigned getNodeDegree(NodeId nId) const {<br>
- return getNode(nId).getDegree();<br>
+ const NodeMetadata& getNodeMetadata(NodeId NId) const {<br>
+ return getNode(NId).Metadata;<br>
}<br>
<br>
- /// \brief Begin iterator for node set.<br>
- NodeItr nodesBegin() const { return NodeItr(0, *this); }<br>
-<br>
- /// \brief End iterator for node set.<br>
- NodeItr nodesEnd() const { return NodeItr(nodes.size(), *this); }<br>
+ typename NodeEntry::AdjEdgeList::size_type getNodeDegree(NodeId NId) const {<br>
+ return getNode(NId).AdjEdgeIds.size();<br>
+ }<br>
<br>
- /// \brief Begin iterator for edge set.<br>
- EdgeItr edgesBegin() const { return EdgeItr(0, *this); }<br>
+ /// \brief Set an edge's cost matrix.<br>
+ /// @param EId Edge id.<br>
+ /// @param Costs New cost matrix.<br>
+ template <typename OtherMatrixT><br>
+ void setEdgeCosts(EdgeId EId, OtherMatrixT Costs) {<br>
+ MatrixPtr AllocatedCosts = CostAlloc.getMatrix(std::move(Costs));<br>
+ if (Solver)<br>
+ Solver->handleSetEdgeCosts(EId, *AllocatedCosts);<br>
+ getEdge(EId).Costs = AllocatedCosts;<br>
+ }<br>
<br>
- /// \brief End iterator for edge set.<br>
- EdgeItr edgesEnd() const { return EdgeItr(edges.size(), *this); }<br>
+ /// \brief Get an edge's cost matrix (const version).<br>
+ /// @param EId Edge id.<br>
+ /// @return Edge cost matrix.<br>
+ const Matrix& getEdgeCosts(EdgeId EId) const { return *getEdge(EId).Costs; }<br>
<br>
- /// \brief Get begin iterator for adjacent edge set.<br>
- /// @param nId Node id.<br>
- /// @return Begin iterator for the set of edges connected to the given node.<br>
- AdjEdgeItr adjEdgesBegin(NodeId nId) {<br>
- return getNode(nId).edgesBegin();<br>
+ EdgeMetadata& getEdgeMetadata(EdgeId NId) {<br>
+ return getEdge(NId).Metadata;<br>
}<br>
<br>
- /// \brief Get end iterator for adjacent edge set.<br>
- /// @param nId Node id.<br>
- /// @return End iterator for the set of edges connected to the given node.<br>
- AdjEdgeItr adjEdgesEnd(NodeId nId) {<br>
- return getNode(nId).edgesEnd();<br>
+ const EdgeMetadata& getEdgeMetadata(EdgeId NId) const {<br>
+ return getEdge(NId).Metadata;<br>
}<br>
<br>
/// \brief Get the first node connected to this edge.<br>
- /// @param eId Edge id.<br>
+ /// @param EId Edge id.<br>
/// @return The first node connected to the given edge.<br>
- NodeId getEdgeNode1(EdgeId eId) {<br>
- return getEdge(eId).getNode1();<br>
+ NodeId getEdgeNode1Id(EdgeId EId) {<br>
+ return getEdge(EId).getN1Id();<br>
}<br>
<br>
/// \brief Get the second node connected to this edge.<br>
- /// @param eId Edge id.<br>
+ /// @param EId Edge id.<br>
/// @return The second node connected to the given edge.<br>
- NodeId getEdgeNode2(EdgeId eId) {<br>
- return getEdge(eId).getNode2();<br>
+ NodeId getEdgeNode2Id(EdgeId EId) {<br>
+ return getEdge(EId).getN2Id();<br>
}<br>
<br>
/// \brief Get the "other" node connected to this edge.<br>
- /// @param eId Edge id.<br>
- /// @param nId Node id for the "given" node.<br>
+ /// @param EId Edge id.<br>
+ /// @param NId Node id for the "given" node.<br>
/// @return The iterator for the "other" node connected to this edge.<br>
- NodeId getEdgeOtherNode(EdgeId eId, NodeId nId) {<br>
- EdgeEntry &e = getEdge(eId);<br>
- if (e.getNode1() == nId) {<br>
- return e.getNode2();<br>
+ NodeId getEdgeOtherNodeId(EdgeId EId, NodeId NId) {<br>
+ EdgeEntry &E = getEdge(EId);<br>
+ if (E.getN1Id() == NId) {<br>
+ return E.getN2Id();<br>
} // else<br>
- return e.getNode1();<br>
+ return E.getN1Id();<br>
}<br>
<br>
- EdgeId invalidEdgeId() const {<br>
+ /// \brief Returns a value representing an invalid (non-existant) node.<br>
+ static NodeId invalidNodeId() {<br>
+ return std::numeric_limits<NodeId>::max();<br>
+ }<br>
+<br>
+ /// \brief Returns a value representing an invalid (non-existant) edge.<br>
+ static EdgeId invalidEdgeId() {<br>
return std::numeric_limits<EdgeId>::max();<br>
}<br>
<br>
/// \brief Get the edge connecting two nodes.<br>
- /// @param n1Id First node id.<br>
- /// @param n2Id Second node id.<br>
- /// @return An id for edge (n1Id, n2Id) if such an edge exists,<br>
+ /// @param N1Id First node id.<br>
+ /// @param N2Id Second node id.<br>
+ /// @return An id for edge (N1Id, N2Id) if such an edge exists,<br>
/// otherwise returns an invalid edge id.<br>
- EdgeId findEdge(NodeId n1Id, NodeId n2Id) {<br>
- for (AdjEdgeItr aeItr = adjEdgesBegin(n1Id), aeEnd = adjEdgesEnd(n1Id);<br>
- aeItr != aeEnd; ++aeItr) {<br>
- if ((getEdgeNode1(*aeItr) == n2Id) ||<br>
- (getEdgeNode2(*aeItr) == n2Id)) {<br>
- return *aeItr;<br>
+ EdgeId findEdge(NodeId N1Id, NodeId N2Id) {<br>
+ for (auto AEId : adjEdgeIds(N1Id)) {<br>
+ if ((getEdgeNode1Id(AEId) == N2Id) ||<br>
+ (getEdgeNode2Id(AEId) == N2Id)) {<br>
+ return AEId;<br>
}<br>
}<br>
return invalidEdgeId();<br>
}<br>
<br>
/// \brief Remove a node from the graph.<br>
- /// @param nId Node id.<br>
- void removeNode(NodeId nId) {<br>
- NodeEntry &n = getNode(nId);<br>
- for (AdjEdgeItr itr = n.edgesBegin(), end = n.edgesEnd(); itr != end; ++itr) {<br>
- EdgeId eId = *itr;<br>
- removeEdge(eId);<br>
+ /// @param NId Node id.<br>
+ void removeNode(NodeId NId) {<br>
+ if (Solver)<br>
+ Solver->handleRemoveNode(NId);<br>
+ NodeEntry &N = getNode(NId);<br>
+ // TODO: Can this be for-each'd?<br>
+ for (AdjEdgeItr AEItr = N.adjEdgesBegin(),<br>
+ AEEnd = N.adjEdgesEnd();<br>
+ AEItr != AEEnd;) {<br>
+ EdgeId EId = *AEItr;<br>
+ ++AEItr;<br>
+ removeEdge(EId);<br>
}<br>
- freeNodes.push_back(nId);<br>
+ FreeNodeIds.push_back(NId);<br>
+ }<br>
+<br>
+ /// \brief Disconnect an edge from the given node.<br>
+ ///<br>
+ /// Removes the given edge from the adjacency list of the given node.<br>
+ /// This operation leaves the edge in an 'asymmetric' state: It will no<br>
+ /// longer appear in an iteration over the given node's (NId's) edges, but<br>
+ /// will appear in an iteration over the 'other', unnamed node's edges.<br>
+ ///<br>
+ /// This does not correspond to any normal graph operation, but exists to<br>
+ /// support efficient PBQP graph-reduction based solvers. It is used to<br>
+ /// 'effectively' remove the unnamed node from the graph while the solver<br>
+ /// is performing the reduction. The solver will later call reconnectNode<br>
+ /// to restore the edge in the named node's adjacency list.<br>
+ ///<br>
+ /// Since the degree of a node is the number of connected edges,<br>
+ /// disconnecting an edge from a node 'u' will cause the degree of 'u' to<br>
+ /// drop by 1.<br>
+ ///<br>
+ /// A disconnected edge WILL still appear in an iteration over the graph<br>
+ /// edges.<br>
+ ///<br>
+ /// A disconnected edge should not be removed from the graph, it should be<br>
+ /// reconnected first.<br>
+ ///<br>
+ /// A disconnected edge can be reconnected by calling the reconnectEdge<br>
+ /// method.<br>
+ void disconnectEdge(EdgeId EId, NodeId NId) {<br>
+ if (Solver)<br>
+ Solver->handleDisconnectEdge(EId, NId);<br>
+ NodeEntry &N = getNode(NId);<br>
+ N.AdjEdgeIds.erase(EId);<br>
+ }<br>
+<br>
+ /// \brief Convenience method to disconnect all neighbours from the given<br>
+ /// node.<br>
+ void disconnectAllNeighborsFromNode(NodeId NId) {<br>
+ for (auto AEId : adjEdgeIds(NId))<br>
+ disconnectEdge(AEId, getEdgeOtherNodeId(AEId, NId));<br>
+ }<br>
+<br>
+ /// \brief Re-attach an edge to its nodes.<br>
+ ///<br>
+ /// Adds an edge that had been previously disconnected back into the<br>
+ /// adjacency set of the nodes that the edge connects.<br>
+ void reconnectEdge(EdgeId EId, NodeId NId) {<br>
+ NodeEntry &N = getNode(NId);<br>
+ N.addAdjEdge(EId);<br>
+ if (Solver)<br>
+ Solver->handleReconnectEdge(EId, NId);<br>
}<br>
<br>
/// \brief Remove an edge from the graph.<br>
- /// @param eId Edge id.<br>
- void removeEdge(EdgeId eId) {<br>
- EdgeEntry &e = getEdge(eId);<br>
- NodeEntry &n1 = getNode(e.getNode1());<br>
- NodeEntry &n2 = getNode(e.getNode2());<br>
- n1.removeEdge(e.getNode1AEItr());<br>
- n2.removeEdge(e.getNode2AEItr());<br>
- freeEdges.push_back(eId);<br>
+ /// @param EId Edge id.<br>
+ void removeEdge(EdgeId EId) {<br>
+ if (Solver)<br>
+ Solver->handleRemoveEdge(EId);<br>
+ EdgeEntry &E = getEdge(EId);<br>
+ NodeEntry &N1 = getNode(E.getNode1());<br>
+ NodeEntry &N2 = getNode(E.getNode2());<br>
+ N1.removeEdge(EId);<br>
+ N2.removeEdge(EId);<br>
+ FreeEdgeIds.push_back(EId);<br>
+ Edges[EId].invalidate();<br>
}<br>
<br>
/// \brief Remove all nodes and edges from the graph.<br>
void clear() {<br>
- nodes.clear();<br>
- freeNodes.clear();<br>
- edges.clear();<br>
- freeEdges.clear();<br>
+ Nodes.clear();<br>
+ FreeNodeIds.clear();<br>
+ Edges.clear();<br>
+ FreeEdgeIds.clear();<br>
}<br>
<br>
/// \brief Dump a graph to an output stream.<br>
template <typename OStream><br>
- void dump(OStream &os) {<br>
- os << getNumNodes() << " " << getNumEdges() << "\n";<br>
+ void dump(OStream &OS) {<br>
+ OS << nodeIds().size() << " " << edgeIds().size() << "\n";<br>
<br>
- for (NodeItr nodeItr = nodesBegin(), nodeEnd = nodesEnd();<br>
- nodeItr != nodeEnd; ++nodeItr) {<br>
- const Vector& v = getNodeCosts(*nodeItr);<br>
- os << "\n" << v.getLength() << "\n";<br>
- assert(v.getLength() != 0 && "Empty vector in graph.");<br>
- os << v[0];<br>
- for (unsigned i = 1; i < v.getLength(); ++i) {<br>
- os << " " << v[i];<br>
+ for (auto NId : nodeIds()) {<br>
+ const Vector& V = getNodeCosts(NId);<br>
+ OS << "\n" << V.getLength() << "\n";<br>
+ assert(V.getLength() != 0 && "Empty vector in graph.");<br>
+ OS << V[0];<br>
+ for (unsigned i = 1; i < V.getLength(); ++i) {<br>
+ OS << " " << V[i];<br>
}<br>
- os << "\n";<br>
+ OS << "\n";<br>
}<br>
<br>
- for (EdgeItr edgeItr = edgesBegin(), edgeEnd = edgesEnd();<br>
- edgeItr != edgeEnd; ++edgeItr) {<br>
- NodeId n1 = getEdgeNode1(*edgeItr);<br>
- NodeId n2 = getEdgeNode2(*edgeItr);<br>
- assert(n1 != n2 && "PBQP graphs shound not have self-edges.");<br>
- const Matrix& m = getEdgeCosts(*edgeItr);<br>
- os << "\n" << n1 << " " << n2 << "\n"<br>
- << m.getRows() << " " << m.getCols() << "\n";<br>
- assert(m.getRows() != 0 && "No rows in matrix.");<br>
- assert(m.getCols() != 0 && "No cols in matrix.");<br>
- for (unsigned i = 0; i < m.getRows(); ++i) {<br>
- os << m[i][0];<br>
- for (unsigned j = 1; j < m.getCols(); ++j) {<br>
- os << " " << m[i][j];<br>
+ for (auto EId : edgeIds()) {<br>
+ NodeId N1Id = getEdgeNode1Id(EId);<br>
+ NodeId N2Id = getEdgeNode2Id(EId);<br>
+ assert(N1Id != N2Id && "PBQP graphs shound not have self-edges.");<br>
+ const Matrix& M = getEdgeCosts(EId);<br>
+ OS << "\n" << N1Id << " " << N2Id << "\n"<br>
+ << M.getRows() << " " << M.getCols() << "\n";<br>
+ assert(M.getRows() != 0 && "No rows in matrix.");<br>
+ assert(M.getCols() != 0 && "No cols in matrix.");<br>
+ for (unsigned i = 0; i < M.getRows(); ++i) {<br>
+ OS << M[i][0];<br>
+ for (unsigned j = 1; j < M.getCols(); ++j) {<br>
+ OS << " " << M[i][j];<br>
}<br>
- os << "\n";<br>
+ OS << "\n";<br>
}<br>
}<br>
}<br>
@@ -430,49 +542,27 @@ namespace PBQP {<br>
/// \brief Print a representation of this graph in DOT format.<br>
/// @param os Output stream to print on.<br>
template <typename OStream><br>
- void printDot(OStream &os) {<br>
-<br>
- os << "graph {\n";<br>
-<br>
- for (NodeItr nodeItr = nodesBegin(), nodeEnd = nodesEnd();<br>
- nodeItr != nodeEnd; ++nodeItr) {<br>
-<br>
- os << " node" << *nodeItr << " [ label=\""<br>
- << *nodeItr << ": " << getNodeCosts(*nodeItr) << "\" ]\n";<br>
- }<br>
-<br>
- os << " edge [ len=" << getNumNodes() << " ]\n";<br>
-<br>
- for (EdgeItr edgeItr = edgesBegin(), edgeEnd = edgesEnd();<br>
- edgeItr != edgeEnd; ++edgeItr) {<br>
-<br>
- os << " node" << getEdgeNode1(*edgeItr)<br>
- << " -- node" << getEdgeNode2(*edgeItr)<br>
+ void printDot(OStream &OS) {<br>
+ OS << "graph {\n";<br>
+ for (auto NId : nodeIds()) {<br>
+ OS << " node" << NId << " [ label=\""<br>
+ << NId << ": " << getNodeCosts(NId) << "\" ]\n";<br>
+ }<br>
+ OS << " edge [ len=" << nodeIds().size() << " ]\n";<br>
+ for (auto EId : edgeIds()) {<br>
+ OS << " node" << getEdgeNode1Id(EId)<br>
+ << " -- node" << getEdgeNode2Id(EId)<br>
<< " [ label=\"";<br>
-<br>
- const Matrix &edgeCosts = getEdgeCosts(*edgeItr);<br>
-<br>
- for (unsigned i = 0; i < edgeCosts.getRows(); ++i) {<br>
- os << edgeCosts.getRowAsVector(i) << "\\n";<br>
+ const Matrix &EdgeCosts = getEdgeCosts(EId);<br>
+ for (unsigned i = 0; i < EdgeCosts.getRows(); ++i) {<br>
+ OS << EdgeCosts.getRowAsVector(i) << "\\n";<br>
}<br>
- os << "\" ]\n";<br>
+ OS << "\" ]\n";<br>
}<br>
- os << "}\n";<br>
+ OS << "}\n";<br>
}<br>
-<br>
};<br>
<br>
-// void Graph::copyFrom(const Graph &other) {<br>
-// std::map<Graph::ConstNodeItr, Graph::NodeItr,<br>
-// NodeItrComparator> nodeMap;<br>
-<br>
-// for (Graph::ConstNodeItr nItr = other.nodesBegin(),<br>
-// nEnd = other.nodesEnd();<br>
-// nItr != nEnd; ++nItr) {<br>
-// nodeMap[nItr] = addNode(other.getNodeCosts(nItr));<br>
-// }<br>
-// }<br>
-<br>
}<br>
<br>
#endif // LLVM_CODEGEN_PBQP_GRAPH_HPP<br>
<br>
Removed: llvm/trunk/include/llvm/CodeGen/PBQP/HeuristicBase.h<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/HeuristicBase.h?rev=202550&view=auto" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/HeuristicBase.h?rev=202550&view=auto</a><br>
==============================================================================<br>
--- llvm/trunk/include/llvm/CodeGen/PBQP/HeuristicBase.h (original)<br>
+++ llvm/trunk/include/llvm/CodeGen/PBQP/HeuristicBase.h (removed)<br>
@@ -1,247 +0,0 @@<br>
-//===-- HeuristcBase.h --- Heuristic base class for PBQP --------*- C++ -*-===//<br>
-//<br>
-// The LLVM Compiler Infrastructure<br>
-//<br>
-// This file is distributed under the University of Illinois Open Source<br>
-// License. See LICENSE.TXT for details.<br>
-//<br>
-//===----------------------------------------------------------------------===//<br>
-<br>
-#ifndef LLVM_CODEGEN_PBQP_HEURISTICBASE_H<br>
-#define LLVM_CODEGEN_PBQP_HEURISTICBASE_H<br>
-<br>
-#include "HeuristicSolver.h"<br>
-<br>
-namespace PBQP {<br>
-<br>
- /// \brief Abstract base class for heuristic implementations.<br>
- ///<br>
- /// This class provides a handy base for heuristic implementations with common<br>
- /// solver behaviour implemented for a number of methods.<br>
- ///<br>
- /// To implement your own heuristic using this class as a base you'll have to<br>
- /// implement, as a minimum, the following methods:<br>
- /// <ul><br>
- /// <li> void addToHeuristicList(Graph::NodeItr) : Add a node to the<br>
- /// heuristic reduction list.<br>
- /// <li> void heuristicReduce() : Perform a single heuristic reduction.<br>
- /// <li> void preUpdateEdgeCosts(Graph::EdgeItr) : Handle the (imminent)<br>
- /// change to the cost matrix on the given edge (by R2).<br>
- /// <li> void postUpdateEdgeCostts(Graph::EdgeItr) : Handle the new<br>
- /// costs on the given edge.<br>
- /// <li> void handleAddEdge(Graph::EdgeItr) : Handle the addition of a new<br>
- /// edge into the PBQP graph (by R2).<br>
- /// <li> void handleRemoveEdge(Graph::EdgeItr, Graph::NodeItr) : Handle the<br>
- /// disconnection of the given edge from the given node.<br>
- /// <li> A constructor for your derived class : to pass back a reference to<br>
- /// the solver which is using this heuristic.<br>
- /// </ul><br>
- ///<br>
- /// These methods are implemented in this class for documentation purposes,<br>
- /// but will assert if called.<br>
- ///<br>
- /// Note that this class uses the curiously recursive template idiom to<br>
- /// forward calls to the derived class. These methods need not be made<br>
- /// virtual, and indeed probably shouldn't for performance reasons.<br>
- ///<br>
- /// You'll also need to provide NodeData and EdgeData structs in your class.<br>
- /// These can be used to attach data relevant to your heuristic to each<br>
- /// node/edge in the PBQP graph.<br>
-<br>
- template <typename HImpl><br>
- class HeuristicBase {<br>
- private:<br>
-<br>
- typedef std::list<Graph::NodeId> OptimalList;<br>
-<br>
- HeuristicSolverImpl<HImpl> &s;<br>
- Graph &g;<br>
- OptimalList optimalList;<br>
-<br>
- // Return a reference to the derived heuristic.<br>
- HImpl& impl() { return static_cast<HImpl&>(*this); }<br>
-<br>
- // Add the given node to the optimal reductions list. Keep an iterator to<br>
- // its location for fast removal.<br>
- void addToOptimalReductionList(Graph::NodeId nId) {<br>
- optimalList.insert(optimalList.end(), nId);<br>
- }<br>
-<br>
- public:<br>
-<br>
- /// \brief Construct an instance with a reference to the given solver.<br>
- /// @param solver The solver which is using this heuristic instance.<br>
- HeuristicBase(HeuristicSolverImpl<HImpl> &solver)<br>
- : s(solver), g(s.getGraph()) { }<br>
-<br>
- /// \brief Get the solver which is using this heuristic instance.<br>
- /// @return The solver which is using this heuristic instance.<br>
- ///<br>
- /// You can use this method to get access to the solver in your derived<br>
- /// heuristic implementation.<br>
- HeuristicSolverImpl<HImpl>& getSolver() { return s; }<br>
-<br>
- /// \brief Get the graph representing the problem to be solved.<br>
- /// @return The graph representing the problem to be solved.<br>
- Graph& getGraph() { return g; }<br>
-<br>
- /// \brief Tell the solver to simplify the graph before the reduction phase.<br>
- /// @return Whether or not the solver should run a simplification phase<br>
- /// prior to the main setup and reduction.<br>
- ///<br>
- /// HeuristicBase returns true from this method as it's a sensible default,<br>
- /// however you can over-ride it in your derived class if you want different<br>
- /// behaviour.<br>
- bool solverRunSimplify() const { return true; }<br>
-<br>
- /// \brief Decide whether a node should be optimally or heuristically<br>
- /// reduced.<br>
- /// @return Whether or not the given node should be listed for optimal<br>
- /// reduction (via R0, R1 or R2).<br>
- ///<br>
- /// HeuristicBase returns true for any node with degree less than 3. This is<br>
- /// sane and sensible for many situations, but not all. You can over-ride<br>
- /// this method in your derived class if you want a different selection<br>
- /// criteria. Note however that your criteria for selecting optimal nodes<br>
- /// should be <i>at least</i> as strong as this. I.e. Nodes of degree 3 or<br>
- /// higher should not be selected under any circumstances.<br>
- bool shouldOptimallyReduce(Graph::NodeId nId) {<br>
- if (g.getNodeDegree(nId) < 3)<br>
- return true;<br>
- // else<br>
- return false;<br>
- }<br>
-<br>
- /// \brief Add the given node to the list of nodes to be optimally reduced.<br>
- /// @param nId Node id to be added.<br>
- ///<br>
- /// You probably don't want to over-ride this, except perhaps to record<br>
- /// statistics before calling this implementation. HeuristicBase relies on<br>
- /// its behaviour.<br>
- void addToOptimalReduceList(Graph::NodeId nId) {<br>
- optimalList.push_back(nId);<br>
- }<br>
-<br>
- /// \brief Initialise the heuristic.<br>
- ///<br>
- /// HeuristicBase iterates over all nodes in the problem and adds them to<br>
- /// the appropriate list using addToOptimalReduceList or<br>
- /// addToHeuristicReduceList based on the result of shouldOptimallyReduce.<br>
- ///<br>
- /// This behaviour should be fine for most situations.<br>
- void setup() {<br>
- for (Graph::NodeItr nItr = g.nodesBegin(), nEnd = g.nodesEnd();<br>
- nItr != nEnd; ++nItr) {<br>
- if (impl().shouldOptimallyReduce(*nItr)) {<br>
- addToOptimalReduceList(*nItr);<br>
- } else {<br>
- impl().addToHeuristicReduceList(*nItr);<br>
- }<br>
- }<br>
- }<br>
-<br>
- /// \brief Optimally reduce one of the nodes in the optimal reduce list.<br>
- /// @return True if a reduction takes place, false if the optimal reduce<br>
- /// list is empty.<br>
- ///<br>
- /// Selects a node from the optimal reduce list and removes it, applying<br>
- /// R0, R1 or R2 as appropriate based on the selected node's degree.<br>
- bool optimalReduce() {<br>
- if (optimalList.empty())<br>
- return false;<br>
-<br>
- Graph::NodeId nId = optimalList.front();<br>
- optimalList.pop_front();<br>
-<br>
- switch (s.getSolverDegree(nId)) {<br>
- case 0: s.applyR0(nId); break;<br>
- case 1: s.applyR1(nId); break;<br>
- case 2: s.applyR2(nId); break;<br>
- default: llvm_unreachable(<br>
- "Optimal reductions of degree > 2 nodes is invalid.");<br>
- }<br>
-<br>
- return true;<br>
- }<br>
-<br>
- /// \brief Perform the PBQP reduction process.<br>
- ///<br>
- /// Reduces the problem to the empty graph by repeated application of the<br>
- /// reduction rules R0, R1, R2 and RN.<br>
- /// R0, R1 or R2 are always applied if possible before RN is used.<br>
- void reduce() {<br>
- bool finished = false;<br>
-<br>
- while (!finished) {<br>
- if (!optimalReduce()) {<br>
- if (impl().heuristicReduce()) {<br>
- getSolver().recordRN();<br>
- } else {<br>
- finished = true;<br>
- }<br>
- }<br>
- }<br>
- }<br>
-<br>
- /// \brief Add a node to the heuristic reduce list.<br>
- /// @param nId Node id to add to the heuristic reduce list.<br>
- void addToHeuristicList(Graph::NodeId nId) {<br>
- llvm_unreachable("Must be implemented in derived class.");<br>
- }<br>
-<br>
- /// \brief Heuristically reduce one of the nodes in the heuristic<br>
- /// reduce list.<br>
- /// @return True if a reduction takes place, false if the heuristic reduce<br>
- /// list is empty.<br>
- bool heuristicReduce() {<br>
- llvm_unreachable("Must be implemented in derived class.");<br>
- return false;<br>
- }<br>
-<br>
- /// \brief Prepare a change in the costs on the given edge.<br>
- /// @param eId Edge id.<br>
- void preUpdateEdgeCosts(Graph::EdgeId eId) {<br>
- llvm_unreachable("Must be implemented in derived class.");<br>
- }<br>
-<br>
- /// \brief Handle the change in the costs on the given edge.<br>
- /// @param eId Edge id.<br>
- void postUpdateEdgeCostts(Graph::EdgeId eId) {<br>
- llvm_unreachable("Must be implemented in derived class.");<br>
- }<br>
-<br>
- /// \brief Handle the addition of a new edge into the PBQP graph.<br>
- /// @param eId Edge id for the added edge.<br>
- void handleAddEdge(Graph::EdgeId eId) {<br>
- llvm_unreachable("Must be implemented in derived class.");<br>
- }<br>
-<br>
- /// \brief Handle disconnection of an edge from a node.<br>
- /// @param eId Edge id for edge being disconnected.<br>
- /// @param nId Node id for the node being disconnected from.<br>
- ///<br>
- /// Edges are frequently removed due to the removal of a node. This<br>
- /// method allows for the effect to be computed only for the remaining<br>
- /// node in the graph.<br>
- void handleRemoveEdge(Graph::EdgeId eId, Graph::NodeId nId) {<br>
- llvm_unreachable("Must be implemented in derived class.");<br>
- }<br>
-<br>
- /// \brief Clean up any structures used by HeuristicBase.<br>
- ///<br>
- /// At present this just performs a sanity check: that the optimal reduce<br>
- /// list is empty now that reduction has completed.<br>
- ///<br>
- /// If your derived class has more complex structures which need tearing<br>
- /// down you should over-ride this method but include a call back to this<br>
- /// implementation.<br>
- void cleanup() {<br>
- assert(optimalList.empty() && "Nodes left over in optimal reduce list?");<br>
- }<br>
-<br>
- };<br>
-<br>
-}<br>
-<br>
-<br>
-#endif // LLVM_CODEGEN_PBQP_HEURISTICBASE_H<br>
<br>
Removed: llvm/trunk/include/llvm/CodeGen/PBQP/HeuristicSolver.h<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/HeuristicSolver.h?rev=202550&view=auto" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/HeuristicSolver.h?rev=202550&view=auto</a><br>
==============================================================================<br>
--- llvm/trunk/include/llvm/CodeGen/PBQP/HeuristicSolver.h (original)<br>
+++ llvm/trunk/include/llvm/CodeGen/PBQP/HeuristicSolver.h (removed)<br>
@@ -1,618 +0,0 @@<br>
-//===-- HeuristicSolver.h - Heuristic PBQP Solver --------------*- C++ -*-===//<br>
-//<br>
-// The LLVM Compiler Infrastructure<br>
-//<br>
-// This file is distributed under the University of Illinois Open Source<br>
-// License. See LICENSE.TXT for details.<br>
-//<br>
-//===----------------------------------------------------------------------===//<br>
-//<br>
-// Heuristic PBQP solver. This solver is able to perform optimal reductions for<br>
-// nodes of degree 0, 1 or 2. For nodes of degree >2 a plugable heuristic is<br>
-// used to select a node for reduction.<br>
-//<br>
-//===----------------------------------------------------------------------===//<br>
-<br>
-#ifndef LLVM_CODEGEN_PBQP_HEURISTICSOLVER_H<br>
-#define LLVM_CODEGEN_PBQP_HEURISTICSOLVER_H<br>
-<br>
-#include "Graph.h"<br>
-#include "Solution.h"<br>
-#include <limits><br>
-#include <vector><br>
-<br>
-namespace PBQP {<br>
-<br>
- /// \brief Heuristic PBQP solver implementation.<br>
- ///<br>
- /// This class should usually be created (and destroyed) indirectly via a call<br>
- /// to HeuristicSolver<HImpl>::solve(Graph&).<br>
- /// See the comments for HeuristicSolver.<br>
- ///<br>
- /// HeuristicSolverImpl provides the R0, R1 and R2 reduction rules,<br>
- /// backpropagation phase, and maintains the internal copy of the graph on<br>
- /// which the reduction is carried out (the original being kept to facilitate<br>
- /// backpropagation).<br>
- template <typename HImpl><br>
- class HeuristicSolverImpl {<br>
- private:<br>
-<br>
- typedef typename HImpl::NodeData HeuristicNodeData;<br>
- typedef typename HImpl::EdgeData HeuristicEdgeData;<br>
-<br>
- typedef std::list<Graph::EdgeId> SolverEdges;<br>
-<br>
- public:<br>
-<br>
- /// \brief Iterator type for edges in the solver graph.<br>
- typedef SolverEdges::iterator SolverEdgeItr;<br>
-<br>
- private:<br>
-<br>
- class NodeData {<br>
- public:<br>
- NodeData() : solverDegree(0) {}<br>
-<br>
- HeuristicNodeData& getHeuristicData() { return hData; }<br>
-<br>
- SolverEdgeItr addSolverEdge(Graph::EdgeId eId) {<br>
- ++solverDegree;<br>
- return solverEdges.insert(solverEdges.end(), eId);<br>
- }<br>
-<br>
- void removeSolverEdge(SolverEdgeItr seItr) {<br>
- --solverDegree;<br>
- solverEdges.erase(seItr);<br>
- }<br>
-<br>
- SolverEdgeItr solverEdgesBegin() { return solverEdges.begin(); }<br>
- SolverEdgeItr solverEdgesEnd() { return solverEdges.end(); }<br>
- unsigned getSolverDegree() const { return solverDegree; }<br>
- void clearSolverEdges() {<br>
- solverDegree = 0;<br>
- solverEdges.clear();<br>
- }<br>
-<br>
- private:<br>
- HeuristicNodeData hData;<br>
- unsigned solverDegree;<br>
- SolverEdges solverEdges;<br>
- };<br>
-<br>
- class EdgeData {<br>
- public:<br>
- HeuristicEdgeData& getHeuristicData() { return hData; }<br>
-<br>
- void setN1SolverEdgeItr(SolverEdgeItr n1SolverEdgeItr) {<br>
- this->n1SolverEdgeItr = n1SolverEdgeItr;<br>
- }<br>
-<br>
- SolverEdgeItr getN1SolverEdgeItr() { return n1SolverEdgeItr; }<br>
-<br>
- void setN2SolverEdgeItr(SolverEdgeItr n2SolverEdgeItr){<br>
- this->n2SolverEdgeItr = n2SolverEdgeItr;<br>
- }<br>
-<br>
- SolverEdgeItr getN2SolverEdgeItr() { return n2SolverEdgeItr; }<br>
-<br>
- private:<br>
-<br>
- HeuristicEdgeData hData;<br>
- SolverEdgeItr n1SolverEdgeItr, n2SolverEdgeItr;<br>
- };<br>
-<br>
- Graph &g;<br>
- HImpl h;<br>
- Solution s;<br>
- std::vector<Graph::NodeId> stack;<br>
-<br>
- typedef std::list<NodeData> NodeDataList;<br>
- NodeDataList nodeDataList;<br>
-<br>
- typedef std::list<EdgeData> EdgeDataList;<br>
- EdgeDataList edgeDataList;<br>
-<br>
- public:<br>
-<br>
- /// \brief Construct a heuristic solver implementation to solve the given<br>
- /// graph.<br>
- /// @param g The graph representing the problem instance to be solved.<br>
- HeuristicSolverImpl(Graph &g) : g(g), h(*this) {}<br>
-<br>
- /// \brief Get the graph being solved by this solver.<br>
- /// @return The graph representing the problem instance being solved by this<br>
- /// solver.<br>
- Graph& getGraph() { return g; }<br>
-<br>
- /// \brief Get the heuristic data attached to the given node.<br>
- /// @param nId Node id.<br>
- /// @return The heuristic data attached to the given node.<br>
- HeuristicNodeData& getHeuristicNodeData(Graph::NodeId nId) {<br>
- return getSolverNodeData(nId).getHeuristicData();<br>
- }<br>
-<br>
- /// \brief Get the heuristic data attached to the given edge.<br>
- /// @param eId Edge id.<br>
- /// @return The heuristic data attached to the given node.<br>
- HeuristicEdgeData& getHeuristicEdgeData(Graph::EdgeId eId) {<br>
- return getSolverEdgeData(eId).getHeuristicData();<br>
- }<br>
-<br>
- /// \brief Begin iterator for the set of edges adjacent to the given node in<br>
- /// the solver graph.<br>
- /// @param nId Node id.<br>
- /// @return Begin iterator for the set of edges adjacent to the given node<br>
- /// in the solver graph.<br>
- SolverEdgeItr solverEdgesBegin(Graph::NodeId nId) {<br>
- return getSolverNodeData(nId).solverEdgesBegin();<br>
- }<br>
-<br>
- /// \brief End iterator for the set of edges adjacent to the given node in<br>
- /// the solver graph.<br>
- /// @param nId Node id.<br>
- /// @return End iterator for the set of edges adjacent to the given node in<br>
- /// the solver graph.<br>
- SolverEdgeItr solverEdgesEnd(Graph::NodeId nId) {<br>
- return getSolverNodeData(nId).solverEdgesEnd();<br>
- }<br>
-<br>
- /// \brief Remove a node from the solver graph.<br>
- /// @param eId Edge id for edge to be removed.<br>
- ///<br>
- /// Does <i>not</i> notify the heuristic of the removal. That should be<br>
- /// done manually if necessary.<br>
- void removeSolverEdge(Graph::EdgeId eId) {<br>
- EdgeData &eData = getSolverEdgeData(eId);<br>
- NodeData &n1Data = getSolverNodeData(g.getEdgeNode1(eId)),<br>
- &n2Data = getSolverNodeData(g.getEdgeNode2(eId));<br>
-<br>
- n1Data.removeSolverEdge(eData.getN1SolverEdgeItr());<br>
- n2Data.removeSolverEdge(eData.getN2SolverEdgeItr());<br>
- }<br>
-<br>
- /// \brief Compute a solution to the PBQP problem instance with which this<br>
- /// heuristic solver was constructed.<br>
- /// @return A solution to the PBQP problem.<br>
- ///<br>
- /// Performs the full PBQP heuristic solver algorithm, including setup,<br>
- /// calls to the heuristic (which will call back to the reduction rules in<br>
- /// this class), and cleanup.<br>
- Solution computeSolution() {<br>
- setup();<br>
- h.setup();<br>
- h.reduce();<br>
- backpropagate();<br>
- h.cleanup();<br>
- cleanup();<br>
- return s;<br>
- }<br>
-<br>
- /// \brief Add to the end of the stack.<br>
- /// @param nId Node id to add to the reduction stack.<br>
- void pushToStack(Graph::NodeId nId) {<br>
- getSolverNodeData(nId).clearSolverEdges();<br>
- stack.push_back(nId);<br>
- }<br>
-<br>
- /// \brief Returns the solver degree of the given node.<br>
- /// @param nId Node id for which degree is requested.<br>
- /// @return Node degree in the <i>solver</i> graph (not the original graph).<br>
- unsigned getSolverDegree(Graph::NodeId nId) {<br>
- return getSolverNodeData(nId).getSolverDegree();<br>
- }<br>
-<br>
- /// \brief Set the solution of the given node.<br>
- /// @param nId Node id to set solution for.<br>
- /// @param selection Selection for node.<br>
- void setSolution(const Graph::NodeId &nId, unsigned selection) {<br>
- s.setSelection(nId, selection);<br>
-<br>
- for (Graph::AdjEdgeItr aeItr = g.adjEdgesBegin(nId),<br>
- aeEnd = g.adjEdgesEnd(nId);<br>
- aeItr != aeEnd; ++aeItr) {<br>
- Graph::EdgeId eId(*aeItr);<br>
- Graph::NodeId anId(g.getEdgeOtherNode(eId, nId));<br>
- getSolverNodeData(anId).addSolverEdge(eId);<br>
- }<br>
- }<br>
-<br>
- /// \brief Apply rule R0.<br>
- /// @param nId Node id for node to apply R0 to.<br>
- ///<br>
- /// Node will be automatically pushed to the solver stack.<br>
- void applyR0(Graph::NodeId nId) {<br>
- assert(getSolverNodeData(nId).getSolverDegree() == 0 &&<br>
- "R0 applied to node with degree != 0.");<br>
-<br>
- // Nothing to do. Just push the node onto the reduction stack.<br>
- pushToStack(nId);<br>
-<br>
- s.recordR0();<br>
- }<br>
-<br>
- /// \brief Apply rule R1.<br>
- /// @param xnId Node id for node to apply R1 to.<br>
- ///<br>
- /// Node will be automatically pushed to the solver stack.<br>
- void applyR1(Graph::NodeId xnId) {<br>
- NodeData &nd = getSolverNodeData(xnId);<br>
- assert(nd.getSolverDegree() == 1 &&<br>
- "R1 applied to node with degree != 1.");<br>
-<br>
- Graph::EdgeId eId = *nd.solverEdgesBegin();<br>
-<br>
- const Matrix &eCosts = g.getEdgeCosts(eId);<br>
- const Vector &xCosts = g.getNodeCosts(xnId);<br>
-<br>
- // Duplicate a little to avoid transposing matrices.<br>
- if (xnId == g.getEdgeNode1(eId)) {<br>
- Graph::NodeId ynId = g.getEdgeNode2(eId);<br>
- Vector &yCosts = g.getNodeCosts(ynId);<br>
- for (unsigned j = 0; j < yCosts.getLength(); ++j) {<br>
- PBQPNum min = eCosts[0][j] + xCosts[0];<br>
- for (unsigned i = 1; i < xCosts.getLength(); ++i) {<br>
- PBQPNum c = eCosts[i][j] + xCosts[i];<br>
- if (c < min)<br>
- min = c;<br>
- }<br>
- yCosts[j] += min;<br>
- }<br>
- h.handleRemoveEdge(eId, ynId);<br>
- } else {<br>
- Graph::NodeId ynId = g.getEdgeNode1(eId);<br>
- Vector &yCosts = g.getNodeCosts(ynId);<br>
- for (unsigned i = 0; i < yCosts.getLength(); ++i) {<br>
- PBQPNum min = eCosts[i][0] + xCosts[0];<br>
- for (unsigned j = 1; j < xCosts.getLength(); ++j) {<br>
- PBQPNum c = eCosts[i][j] + xCosts[j];<br>
- if (c < min)<br>
- min = c;<br>
- }<br>
- yCosts[i] += min;<br>
- }<br>
- h.handleRemoveEdge(eId, ynId);<br>
- }<br>
- removeSolverEdge(eId);<br>
- assert(nd.getSolverDegree() == 0 &&<br>
- "Degree 1 with edge removed should be 0.");<br>
- pushToStack(xnId);<br>
- s.recordR1();<br>
- }<br>
-<br>
- /// \brief Apply rule R2.<br>
- /// @param xnId Node id for node to apply R2 to.<br>
- ///<br>
- /// Node will be automatically pushed to the solver stack.<br>
- void applyR2(Graph::NodeId xnId) {<br>
- assert(getSolverNodeData(xnId).getSolverDegree() == 2 &&<br>
- "R2 applied to node with degree != 2.");<br>
-<br>
- NodeData &nd = getSolverNodeData(xnId);<br>
- const Vector &xCosts = g.getNodeCosts(xnId);<br>
-<br>
- SolverEdgeItr aeItr = nd.solverEdgesBegin();<br>
- Graph::EdgeId yxeId = *aeItr,<br>
- zxeId = *(++aeItr);<br>
-<br>
- Graph::NodeId ynId = g.getEdgeOtherNode(yxeId, xnId),<br>
- znId = g.getEdgeOtherNode(zxeId, xnId);<br>
-<br>
- bool flipEdge1 = (g.getEdgeNode1(yxeId) == xnId),<br>
- flipEdge2 = (g.getEdgeNode1(zxeId) == xnId);<br>
-<br>
- const Matrix *yxeCosts = flipEdge1 ?<br>
- new Matrix(g.getEdgeCosts(yxeId).transpose()) :<br>
- &g.getEdgeCosts(yxeId);<br>
-<br>
- const Matrix *zxeCosts = flipEdge2 ?<br>
- new Matrix(g.getEdgeCosts(zxeId).transpose()) :<br>
- &g.getEdgeCosts(zxeId);<br>
-<br>
- unsigned xLen = xCosts.getLength(),<br>
- yLen = yxeCosts->getRows(),<br>
- zLen = zxeCosts->getRows();<br>
-<br>
- Matrix delta(yLen, zLen);<br>
-<br>
- for (unsigned i = 0; i < yLen; ++i) {<br>
- for (unsigned j = 0; j < zLen; ++j) {<br>
- PBQPNum min = (*yxeCosts)[i][0] + (*zxeCosts)[j][0] + xCosts[0];<br>
- for (unsigned k = 1; k < xLen; ++k) {<br>
- PBQPNum c = (*yxeCosts)[i][k] + (*zxeCosts)[j][k] + xCosts[k];<br>
- if (c < min) {<br>
- min = c;<br>
- }<br>
- }<br>
- delta[i][j] = min;<br>
- }<br>
- }<br>
-<br>
- if (flipEdge1)<br>
- delete yxeCosts;<br>
-<br>
- if (flipEdge2)<br>
- delete zxeCosts;<br>
-<br>
- Graph::EdgeId yzeId = g.findEdge(ynId, znId);<br>
- bool addedEdge = false;<br>
-<br>
- if (yzeId == g.invalidEdgeId()) {<br>
- yzeId = g.addEdge(ynId, znId, delta);<br>
- addedEdge = true;<br>
- } else {<br>
- Matrix &yzeCosts = g.getEdgeCosts(yzeId);<br>
- h.preUpdateEdgeCosts(yzeId);<br>
- if (ynId == g.getEdgeNode1(yzeId)) {<br>
- yzeCosts += delta;<br>
- } else {<br>
- yzeCosts += delta.transpose();<br>
- }<br>
- }<br>
-<br>
- bool nullCostEdge = tryNormaliseEdgeMatrix(yzeId);<br>
-<br>
- if (!addedEdge) {<br>
- // If we modified the edge costs let the heuristic know.<br>
- h.postUpdateEdgeCosts(yzeId);<br>
- }<br>
-<br>
- if (nullCostEdge) {<br>
- // If this edge ended up null remove it.<br>
- if (!addedEdge) {<br>
- // We didn't just add it, so we need to notify the heuristic<br>
- // and remove it from the solver.<br>
- h.handleRemoveEdge(yzeId, ynId);<br>
- h.handleRemoveEdge(yzeId, znId);<br>
- removeSolverEdge(yzeId);<br>
- }<br>
- g.removeEdge(yzeId);<br>
- } else if (addedEdge) {<br>
- // If the edge was added, and non-null, finish setting it up, add it to<br>
- // the solver & notify heuristic.<br>
- edgeDataList.push_back(EdgeData());<br>
- g.setEdgeData(yzeId, &edgeDataList.back());<br>
- addSolverEdge(yzeId);<br>
- h.handleAddEdge(yzeId);<br>
- }<br>
-<br>
- h.handleRemoveEdge(yxeId, ynId);<br>
- removeSolverEdge(yxeId);<br>
- h.handleRemoveEdge(zxeId, znId);<br>
- removeSolverEdge(zxeId);<br>
-<br>
- pushToStack(xnId);<br>
- s.recordR2();<br>
- }<br>
-<br>
- /// \brief Record an application of the RN rule.<br>
- ///<br>
- /// For use by the HeuristicBase.<br>
- void recordRN() { s.recordRN(); }<br>
-<br>
- private:<br>
-<br>
- NodeData& getSolverNodeData(Graph::NodeId nId) {<br>
- return *static_cast<NodeData*>(g.getNodeData(nId));<br>
- }<br>
-<br>
- EdgeData& getSolverEdgeData(Graph::EdgeId eId) {<br>
- return *static_cast<EdgeData*>(g.getEdgeData(eId));<br>
- }<br>
-<br>
- void addSolverEdge(Graph::EdgeId eId) {<br>
- EdgeData &eData = getSolverEdgeData(eId);<br>
- NodeData &n1Data = getSolverNodeData(g.getEdgeNode1(eId)),<br>
- &n2Data = getSolverNodeData(g.getEdgeNode2(eId));<br>
-<br>
- eData.setN1SolverEdgeItr(n1Data.addSolverEdge(eId));<br>
- eData.setN2SolverEdgeItr(n2Data.addSolverEdge(eId));<br>
- }<br>
-<br>
- void setup() {<br>
- if (h.solverRunSimplify()) {<br>
- simplify();<br>
- }<br>
-<br>
- // Create node data objects.<br>
- for (Graph::NodeItr nItr = g.nodesBegin(), nEnd = g.nodesEnd();<br>
- nItr != nEnd; ++nItr) {<br>
- nodeDataList.push_back(NodeData());<br>
- g.setNodeData(*nItr, &nodeDataList.back());<br>
- }<br>
-<br>
- // Create edge data objects.<br>
- for (Graph::EdgeItr eItr = g.edgesBegin(), eEnd = g.edgesEnd();<br>
- eItr != eEnd; ++eItr) {<br>
- edgeDataList.push_back(EdgeData());<br>
- g.setEdgeData(*eItr, &edgeDataList.back());<br>
- addSolverEdge(*eItr);<br>
- }<br>
- }<br>
-<br>
- void simplify() {<br>
- disconnectTrivialNodes();<br>
- eliminateIndependentEdges();<br>
- }<br>
-<br>
- // Eliminate trivial nodes.<br>
- void disconnectTrivialNodes() {<br>
- unsigned numDisconnected = 0;<br>
-<br>
- for (Graph::NodeItr nItr = g.nodesBegin(), nEnd = g.nodesEnd();<br>
- nItr != nEnd; ++nItr) {<br>
-<br>
- Graph::NodeId nId = *nItr;<br>
-<br>
- if (g.getNodeCosts(nId).getLength() == 1) {<br>
-<br>
- std::vector<Graph::EdgeId> edgesToRemove;<br>
-<br>
- for (Graph::AdjEdgeItr aeItr = g.adjEdgesBegin(nId),<br>
- aeEnd = g.adjEdgesEnd(nId);<br>
- aeItr != aeEnd; ++aeItr) {<br>
-<br>
- Graph::EdgeId eId = *aeItr;<br>
-<br>
- if (g.getEdgeNode1(eId) == nId) {<br>
- Graph::NodeId otherNodeId = g.getEdgeNode2(eId);<br>
- g.getNodeCosts(otherNodeId) +=<br>
- g.getEdgeCosts(eId).getRowAsVector(0);<br>
- }<br>
- else {<br>
- Graph::NodeId otherNodeId = g.getEdgeNode1(eId);<br>
- g.getNodeCosts(otherNodeId) +=<br>
- g.getEdgeCosts(eId).getColAsVector(0);<br>
- }<br>
-<br>
- edgesToRemove.push_back(eId);<br>
- }<br>
-<br>
- if (!edgesToRemove.empty())<br>
- ++numDisconnected;<br>
-<br>
- while (!edgesToRemove.empty()) {<br>
- g.removeEdge(edgesToRemove.back());<br>
- edgesToRemove.pop_back();<br>
- }<br>
- }<br>
- }<br>
- }<br>
-<br>
- void eliminateIndependentEdges() {<br>
- std::vector<Graph::EdgeId> edgesToProcess;<br>
- unsigned numEliminated = 0;<br>
-<br>
- for (Graph::EdgeItr eItr = g.edgesBegin(), eEnd = g.edgesEnd();<br>
- eItr != eEnd; ++eItr) {<br>
- edgesToProcess.push_back(*eItr);<br>
- }<br>
-<br>
- while (!edgesToProcess.empty()) {<br>
- if (tryToEliminateEdge(edgesToProcess.back()))<br>
- ++numEliminated;<br>
- edgesToProcess.pop_back();<br>
- }<br>
- }<br>
-<br>
- bool tryToEliminateEdge(Graph::EdgeId eId) {<br>
- if (tryNormaliseEdgeMatrix(eId)) {<br>
- g.removeEdge(eId);<br>
- return true;<br>
- }<br>
- return false;<br>
- }<br>
-<br>
- bool tryNormaliseEdgeMatrix(Graph::EdgeId &eId) {<br>
-<br>
- const PBQPNum infinity = std::numeric_limits<PBQPNum>::infinity();<br>
-<br>
- Matrix &edgeCosts = g.getEdgeCosts(eId);<br>
- Vector &uCosts = g.getNodeCosts(g.getEdgeNode1(eId)),<br>
- &vCosts = g.getNodeCosts(g.getEdgeNode2(eId));<br>
-<br>
- for (unsigned r = 0; r < edgeCosts.getRows(); ++r) {<br>
- PBQPNum rowMin = infinity;<br>
-<br>
- for (unsigned c = 0; c < edgeCosts.getCols(); ++c) {<br>
- if (vCosts[c] != infinity && edgeCosts[r][c] < rowMin)<br>
- rowMin = edgeCosts[r][c];<br>
- }<br>
-<br>
- uCosts[r] += rowMin;<br>
-<br>
- if (rowMin != infinity) {<br>
- edgeCosts.subFromRow(r, rowMin);<br>
- }<br>
- else {<br>
- edgeCosts.setRow(r, 0);<br>
- }<br>
- }<br>
-<br>
- for (unsigned c = 0; c < edgeCosts.getCols(); ++c) {<br>
- PBQPNum colMin = infinity;<br>
-<br>
- for (unsigned r = 0; r < edgeCosts.getRows(); ++r) {<br>
- if (uCosts[r] != infinity && edgeCosts[r][c] < colMin)<br>
- colMin = edgeCosts[r][c];<br>
- }<br>
-<br>
- vCosts[c] += colMin;<br>
-<br>
- if (colMin != infinity) {<br>
- edgeCosts.subFromCol(c, colMin);<br>
- }<br>
- else {<br>
- edgeCosts.setCol(c, 0);<br>
- }<br>
- }<br>
-<br>
- return edgeCosts.isZero();<br>
- }<br>
-<br>
- void backpropagate() {<br>
- while (!stack.empty()) {<br>
- computeSolution(stack.back());<br>
- stack.pop_back();<br>
- }<br>
- }<br>
-<br>
- void computeSolution(Graph::NodeId nId) {<br>
-<br>
- NodeData &nodeData = getSolverNodeData(nId);<br>
-<br>
- Vector v(g.getNodeCosts(nId));<br>
-<br>
- // Solve based on existing solved edges.<br>
- for (SolverEdgeItr solvedEdgeItr = nodeData.solverEdgesBegin(),<br>
- solvedEdgeEnd = nodeData.solverEdgesEnd();<br>
- solvedEdgeItr != solvedEdgeEnd; ++solvedEdgeItr) {<br>
-<br>
- Graph::EdgeId eId(*solvedEdgeItr);<br>
- Matrix &edgeCosts = g.getEdgeCosts(eId);<br>
-<br>
- if (nId == g.getEdgeNode1(eId)) {<br>
- Graph::NodeId adjNode(g.getEdgeNode2(eId));<br>
- unsigned adjSolution = s.getSelection(adjNode);<br>
- v += edgeCosts.getColAsVector(adjSolution);<br>
- }<br>
- else {<br>
- Graph::NodeId adjNode(g.getEdgeNode1(eId));<br>
- unsigned adjSolution = s.getSelection(adjNode);<br>
- v += edgeCosts.getRowAsVector(adjSolution);<br>
- }<br>
-<br>
- }<br>
-<br>
- setSolution(nId, v.minIndex());<br>
- }<br>
-<br>
- void cleanup() {<br>
- h.cleanup();<br>
- nodeDataList.clear();<br>
- edgeDataList.clear();<br>
- }<br>
- };<br>
-<br>
- /// \brief PBQP heuristic solver class.<br>
- ///<br>
- /// Given a PBQP Graph g representing a PBQP problem, you can find a solution<br>
- /// by calling<br>
- /// <tt>Solution s = HeuristicSolver<H>::solve(g);</tt><br>
- ///<br>
- /// The choice of heuristic for the H parameter will affect both the solver<br>
- /// speed and solution quality. The heuristic should be chosen based on the<br>
- /// nature of the problem being solved.<br>
- /// Currently the only solver included with LLVM is the Briggs heuristic for<br>
- /// register allocation.<br>
- template <typename HImpl><br>
- class HeuristicSolver {<br>
- public:<br>
- static Solution solve(Graph &g) {<br>
- HeuristicSolverImpl<HImpl> hs(g);<br>
- return hs.computeSolution();<br>
- }<br>
- };<br>
-<br>
-}<br>
-<br>
-#endif // LLVM_CODEGEN_PBQP_HEURISTICSOLVER_H<br>
<br>
Modified: llvm/trunk/include/llvm/CodeGen/PBQP/Math.h<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/Math.h?rev=202551&r1=202550&r2=202551&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/Math.h?rev=202551&r1=202550&r2=202551&view=diff</a><br>
==============================================================================<br>
--- llvm/trunk/include/llvm/CodeGen/PBQP/Math.h (original)<br>
+++ llvm/trunk/include/llvm/CodeGen/PBQP/Math.h Fri Feb 28 16:25:24 2014<br>
@@ -20,268 +20,418 @@ typedef float PBQPNum;<br>
<br>
/// \brief PBQP Vector class.<br>
class Vector {<br>
- public:<br>
+ friend class VectorComparator;<br>
+public:<br>
<br>
- /// \brief Construct a PBQP vector of the given size.<br>
- explicit Vector(unsigned length) :<br>
- length(length), data(new PBQPNum[length]) {<br>
- }<br>
-<br>
- /// \brief Construct a PBQP vector with initializer.<br>
- Vector(unsigned length, PBQPNum initVal) :<br>
- length(length), data(new PBQPNum[length]) {<br>
- std::fill(data, data + length, initVal);<br>
- }<br>
-<br>
- /// \brief Copy construct a PBQP vector.<br>
- Vector(const Vector &v) :<br>
- length(v.length), data(new PBQPNum[length]) {<br>
- std::copy(v.data, v.data + length, data);<br>
- }<br>
-<br>
- /// \brief Destroy this vector, return its memory.<br>
- ~Vector() { delete[] data; }<br>
-<br>
- /// \brief Assignment operator.<br>
- Vector& operator=(const Vector &v) {<br>
- delete[] data;<br>
- length = v.length;<br>
- data = new PBQPNum[length];<br>
- std::copy(v.data, v.data + length, data);<br>
- return *this;<br>
- }<br>
-<br>
- /// \brief Return the length of the vector<br>
- unsigned getLength() const {<br>
- return length;<br>
- }<br>
-<br>
- /// \brief Element access.<br>
- PBQPNum& operator[](unsigned index) {<br>
- assert(index < length && "Vector element access out of bounds.");<br>
- return data[index];<br>
- }<br>
-<br>
- /// \brief Const element access.<br>
- const PBQPNum& operator[](unsigned index) const {<br>
- assert(index < length && "Vector element access out of bounds.");<br>
- return data[index];<br>
- }<br>
-<br>
- /// \brief Add another vector to this one.<br>
- Vector& operator+=(const Vector &v) {<br>
- assert(length == v.length && "Vector length mismatch.");<br>
- std::transform(data, data + length, v.data, data, std::plus<PBQPNum>());<br>
- return *this;<br>
- }<br>
-<br>
- /// \brief Subtract another vector from this one.<br>
- Vector& operator-=(const Vector &v) {<br>
- assert(length == v.length && "Vector length mismatch.");<br>
- std::transform(data, data + length, v.data, data, std::minus<PBQPNum>());<br>
- return *this;<br>
- }<br>
-<br>
- /// \brief Returns the index of the minimum value in this vector<br>
- unsigned minIndex() const {<br>
- return std::min_element(data, data + length) - data;<br>
- }<br>
-<br>
- private:<br>
- unsigned length;<br>
- PBQPNum *data;<br>
+ /// \brief Construct a PBQP vector of the given size.<br>
+ explicit Vector(unsigned Length)<br>
+ : Length(Length), Data(new PBQPNum[Length]) {<br>
+ // llvm::dbgs() << "Constructing PBQP::Vector "<br>
+ // << this << " (length " << Length << ")\n";<br>
+ }<br>
+<br>
+ /// \brief Construct a PBQP vector with initializer.<br>
+ Vector(unsigned Length, PBQPNum InitVal)<br>
+ : Length(Length), Data(new PBQPNum[Length]) {<br>
+ // llvm::dbgs() << "Constructing PBQP::Vector "<br>
+ // << this << " (length " << Length << ", fill "<br>
+ // << InitVal << ")\n";<br>
+ std::fill(Data, Data + Length, InitVal);<br>
+ }<br>
+<br>
+ /// \brief Copy construct a PBQP vector.<br>
+ Vector(const Vector &V)<br>
+ : Length(V.Length), Data(new PBQPNum[Length]) {<br>
+ // llvm::dbgs() << "Copy-constructing PBQP::Vector " << this<br>
+ // << " from PBQP::Vector " << &V << "\n";<br>
+ std::copy(V.Data, V.Data + Length, Data);<br>
+ }<br>
+<br>
+ /// \brief Move construct a PBQP vector.<br>
+ Vector(Vector &&V)<br>
+ : Length(V.Length), Data(V.Data) {<br>
+ V.Length = 0;<br>
+ V.Data = nullptr;<br>
+ }<br>
+<br>
+ /// \brief Destroy this vector, return its memory.<br>
+ ~Vector() {<br>
+ // llvm::dbgs() << "Deleting PBQP::Vector " << this << "\n";<br>
+ delete[] Data;<br>
+ }<br>
+<br>
+ /// \brief Copy-assignment operator.<br>
+ Vector& operator=(const Vector &V) {<br>
+ // llvm::dbgs() << "Assigning to PBQP::Vector " << this<br>
+ // << " from PBQP::Vector " << &V << "\n";<br>
+ delete[] Data;<br></blockquote><div><br></div><div>Breaks on self assignment (see comment later - Data should probably be a std::unique_ptr<Data[]> which should simplify some of this)<br><br>If you're storing teh length anyway... you could just use a std::vector<Data> - you'd pay an extra int for the "capacity" but it'd simplify a bunch of this even further.</div>
<div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
+ Length = V.Length;<br>
+ Data = new PBQPNum[Length];<br>
+ std::copy(V.Data, V.Data + Length, Data);<br>
+ return *this;<br>
+ }<br>
+<br>
+ /// \brief Move-assignment operator.<br>
+ Vector& operator=(Vector &&V) {<br>
+ delete[] Data; </blockquote><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
+ Length = V.Length;<br>
+ Data = V.Data;<br>
+ V.Length = 0;<br>
+ V.Data = nullptr;<br>
+ return *this;<br>
+ }<br>
+<br>
+ /// \brief Comparison operator.<br>
+ bool operator==(const Vector &V) const {<br>
+ assert(Length != 0 && Data != nullptr && "Invalid vector");<br>
+ if (Length != V.Length)<br>
+ return false;<br>
+ return std::equal(Data, Data + Length, V.Data);<br>
+ }<br>
+<br>
+ /// \brief Return the length of the vector<br>
+ unsigned getLength() const {<br>
+ assert(Length != 0 && Data != nullptr && "Invalid vector");<br>
+ return Length;<br>
+ }<br>
+<br>
+ /// \brief Element access.<br>
+ PBQPNum& operator[](unsigned Index) {<br>
+ assert(Length != 0 && Data != nullptr && "Invalid vector");<br>
+ assert(Index < Length && "Vector element access out of bounds.");<br>
+ return Data[Index];<br>
+ }<br>
+<br>
+ /// \brief Const element access.<br>
+ const PBQPNum& operator[](unsigned Index) const {<br>
+ assert(Length != 0 && Data != nullptr && "Invalid vector");<br>
+ assert(Index < Length && "Vector element access out of bounds.");<br>
+ return Data[Index];<br>
+ }<br>
+<br>
+ /// \brief Add another vector to this one.<br>
+ Vector& operator+=(const Vector &V) {<br>
+ assert(Length != 0 && Data != nullptr && "Invalid vector");<br>
+ assert(Length == V.Length && "Vector length mismatch.");<br>
+ std::transform(Data, Data + Length, V.Data, Data, std::plus<PBQPNum>());<br>
+ return *this;<br>
+ }<br>
+<br>
+ /// \brief Subtract another vector from this one.<br>
+ Vector& operator-=(const Vector &V) {<br>
+ assert(Length != 0 && Data != nullptr && "Invalid vector");<br>
+ assert(Length == V.Length && "Vector length mismatch.");<br>
+ std::transform(Data, Data + Length, V.Data, Data, std::minus<PBQPNum>());<br>
+ return *this;<br>
+ }<br>
+<br>
+ /// \brief Returns the index of the minimum value in this vector<br>
+ unsigned minIndex() const {<br>
+ assert(Length != 0 && Data != nullptr && "Invalid vector");<br>
+ return std::min_element(Data, Data + Length) - Data;<br>
+ }<br>
+<br>
+private:<br>
+ unsigned Length;<br>
+ PBQPNum *Data;<br></blockquote><div><br></div><div>Should this be a std::unique_ptr<PBQPNum[]>?</div><div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
+};<br>
+<br>
+class VectorComparator {<br>
+public:<br>
+ bool operator()(const Vector &A, const Vector &B) {<br>
+ if (A.Length < B.Length)<br>
+ return true;<br>
+ if (B.Length < A.Length)<br>
+ return false;<br>
+ char *AData = reinterpret_cast<char*>(A.Data);<br>
+ char *BData = reinterpret_cast<char*>(B.Data);<br>
+ return std::lexicographical_compare(AData,<br>
+ AData + A.Length * sizeof(PBQPNum),<br>
+ BData,<br>
+ BData + A.Length * sizeof(PBQPNum));<br>
+ }<br>
};<br>
<br>
/// \brief Output a textual representation of the given vector on the given<br>
/// output stream.<br>
template <typename OStream><br>
-OStream& operator<<(OStream &os, const Vector &v) {<br>
- assert((v.getLength() != 0) && "Zero-length vector badness.");<br>
+OStream& operator<<(OStream &OS, const Vector &V) {<br>
+ assert((V.getLength() != 0) && "Zero-length vector badness.");<br>
<br>
- os << "[ " << v[0];<br>
- for (unsigned i = 1; i < v.getLength(); ++i) {<br>
- os << ", " << v[i];<br>
- }<br>
- os << " ]";<br>
+ OS << "[ " << V[0];<br>
+ for (unsigned i = 1; i < V.getLength(); ++i)<br>
+ OS << ", " << V[i];<br>
+ OS << " ]";<br>
<br>
- return os;<br>
-}<br>
+ return OS;<br>
+}<br>
<br>
<br>
/// \brief PBQP Matrix class<br>
class Matrix {<br>
- public:<br>
+private:<br>
+ friend class MatrixComparator;<br>
+public:<br>
+<br>
+ /// \brief Construct a PBQP Matrix with the given dimensions.<br>
+ Matrix(unsigned Rows, unsigned Cols) :<br>
+ Rows(Rows), Cols(Cols), Data(new PBQPNum[Rows * Cols]) {<br></blockquote><div><br></div><div>More raw ownership, same solution as above (std::unique_ptr or std::array)</div><div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
+ }<br>
+<br>
+ /// \brief Construct a PBQP Matrix with the given dimensions and initial<br>
+ /// value.<br>
+ Matrix(unsigned Rows, unsigned Cols, PBQPNum InitVal)<br>
+ : Rows(Rows), Cols(Cols), Data(new PBQPNum[Rows * Cols]) {<br>
+ std::fill(Data, Data + (Rows * Cols), InitVal);<br>
+ }<br>
+<br>
+ /// \brief Copy construct a PBQP matrix.<br>
+ Matrix(const Matrix &M)<br>
+ : Rows(M.Rows), Cols(M.Cols), Data(new PBQPNum[Rows * Cols]) {<br>
+ std::copy(M.Data, M.Data + (Rows * Cols), Data);<br>
+ }<br>
+<br>
+ /// \brief Move construct a PBQP matrix.<br>
+ Matrix(Matrix &&M)<br>
+ : Rows(M.Rows), Cols(M.Cols), Data(M.Data) {<br>
+ M.Rows = M.Cols = 0;<br>
+ M.Data = nullptr;<br>
+ }<br>
+<br>
+ /// \brief Destroy this matrix, return its memory.<br>
+ ~Matrix() { delete[] Data; }<br>
+<br>
+ /// \brief Copy-assignment operator.<br>
+ Matrix& operator=(const Matrix &M) {<br>
+ delete[] Data;<br>
+ Rows = M.Rows; Cols = M.Cols;<br>
+ Data = new PBQPNum[Rows * Cols];<br>
+ std::copy(M.Data, M.Data + (Rows * Cols), Data);<br>
+ return *this;<br>
+ }<br>
+<br>
+ /// \brief Move-assignment operator.<br>
+ Matrix& operator=(Matrix &&M) {<br>
+ delete[] Data;<br>
+ Rows = M.Rows;<br>
+ Cols = M.Cols;<br>
+ Data = M.Data;<br>
+ M.Rows = M.Cols = 0;<br>
+ M.Data = nullptr;<br>
+ return *this;<br>
+ }<br>
+<br>
+ /// \brief Comparison operator.<br>
+ bool operator==(const Matrix &M) const {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ if (Rows != M.Rows || Cols != M.Cols)<br>
+ return false;<br>
+ return std::equal(Data, Data + (Rows * Cols), M.Data);<br>
+ }<br>
+<br>
+ /// \brief Return the number of rows in this matrix.<br>
+ unsigned getRows() const {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ return Rows;<br>
+ }<br>
+<br>
+ /// \brief Return the number of cols in this matrix.<br>
+ unsigned getCols() const {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ return Cols;<br>
+ }<br>
+<br>
+ /// \brief Matrix element access.<br>
+ PBQPNum* operator[](unsigned R) {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ assert(R < Rows && "Row out of bounds.");<br>
+ return Data + (R * Cols);<br>
+ }<br>
+<br>
+ /// \brief Matrix element access.<br>
+ const PBQPNum* operator[](unsigned R) const {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ assert(R < Rows && "Row out of bounds.");<br>
+ return Data + (R * Cols);<br>
+ }<br>
+<br>
+ /// \brief Returns the given row as a vector.<br>
+ Vector getRowAsVector(unsigned R) const {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ Vector V(Cols);<br>
+ for (unsigned C = 0; C < Cols; ++C)<br>
+ V[C] = (*this)[R][C];<br>
+ return V;<br>
+ }<br>
+<br>
+ /// \brief Returns the given column as a vector.<br>
+ Vector getColAsVector(unsigned C) const {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ Vector V(Rows);<br>
+ for (unsigned R = 0; R < Rows; ++R)<br>
+ V[R] = (*this)[R][C];<br>
+ return V;<br>
+ }<br>
+<br>
+ /// \brief Reset the matrix to the given value.<br>
+ Matrix& reset(PBQPNum Val = 0) {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ std::fill(Data, Data + (Rows * Cols), Val);<br>
+ return *this;<br>
+ }<br>
+<br>
+ /// \brief Set a single row of this matrix to the given value.<br>
+ Matrix& setRow(unsigned R, PBQPNum Val) {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ assert(R < Rows && "Row out of bounds.");<br>
+ std::fill(Data + (R * Cols), Data + ((R + 1) * Cols), Val);<br>
+ return *this;<br>
+ }<br>
+<br>
+ /// \brief Set a single column of this matrix to the given value.<br>
+ Matrix& setCol(unsigned C, PBQPNum Val) {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ assert(C < Cols && "Column out of bounds.");<br>
+ for (unsigned R = 0; R < Rows; ++R)<br>
+ (*this)[R][C] = Val;<br>
+ return *this;<br>
+ }<br>
+<br>
+ /// \brief Matrix transpose.<br>
+ Matrix transpose() const {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ Matrix M(Cols, Rows);<br>
+ for (unsigned r = 0; r < Rows; ++r)<br>
+ for (unsigned c = 0; c < Cols; ++c)<br>
+ M[c][r] = (*this)[r][c];<br>
+ return M;<br>
+ }<br>
+<br>
+ /// \brief Returns the diagonal of the matrix as a vector.<br>
+ ///<br>
+ /// Matrix must be square.<br>
+ Vector diagonalize() const {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ assert(Rows == Cols && "Attempt to diagonalize non-square matrix.");<br>
+ Vector V(Rows);<br>
+ for (unsigned r = 0; r < Rows; ++r)<br>
+ V[r] = (*this)[r][r];<br>
+ return V;<br>
+ }<br>
<br>
- /// \brief Construct a PBQP Matrix with the given dimensions.<br>
- Matrix(unsigned rows, unsigned cols) :<br>
- rows(rows), cols(cols), data(new PBQPNum[rows * cols]) {<br>
- }<br>
-<br>
- /// \brief Construct a PBQP Matrix with the given dimensions and initial<br>
- /// value.<br>
- Matrix(unsigned rows, unsigned cols, PBQPNum initVal) :<br>
- rows(rows), cols(cols), data(new PBQPNum[rows * cols]) {<br>
- std::fill(data, data + (rows * cols), initVal);<br>
- }<br>
-<br>
- /// \brief Copy construct a PBQP matrix.<br>
- Matrix(const Matrix &m) :<br>
- rows(m.rows), cols(m.cols), data(new PBQPNum[rows * cols]) {<br>
- std::copy(m.data, m.data + (rows * cols), data);<br>
- }<br>
-<br>
- /// \brief Destroy this matrix, return its memory.<br>
- ~Matrix() { delete[] data; }<br>
-<br>
- /// \brief Assignment operator.<br>
- Matrix& operator=(const Matrix &m) {<br>
- delete[] data;<br>
- rows = m.rows; cols = m.cols;<br>
- data = new PBQPNum[rows * cols];<br>
- std::copy(m.data, m.data + (rows * cols), data);<br>
- return *this;<br>
- }<br>
-<br>
- /// \brief Return the number of rows in this matrix.<br>
- unsigned getRows() const { return rows; }<br>
-<br>
- /// \brief Return the number of cols in this matrix.<br>
- unsigned getCols() const { return cols; }<br>
-<br>
- /// \brief Matrix element access.<br>
- PBQPNum* operator[](unsigned r) {<br>
- assert(r < rows && "Row out of bounds.");<br>
- return data + (r * cols);<br>
- }<br>
-<br>
- /// \brief Matrix element access.<br>
- const PBQPNum* operator[](unsigned r) const {<br>
- assert(r < rows && "Row out of bounds.");<br>
- return data + (r * cols);<br>
- }<br>
-<br>
- /// \brief Returns the given row as a vector.<br>
- Vector getRowAsVector(unsigned r) const {<br>
- Vector v(cols);<br>
- for (unsigned c = 0; c < cols; ++c)<br>
- v[c] = (*this)[r][c];<br>
- return v;<br>
- }<br>
-<br>
- /// \brief Returns the given column as a vector.<br>
- Vector getColAsVector(unsigned c) const {<br>
- Vector v(rows);<br>
- for (unsigned r = 0; r < rows; ++r)<br>
- v[r] = (*this)[r][c];<br>
- return v;<br>
- }<br>
-<br>
- /// \brief Reset the matrix to the given value.<br>
- Matrix& reset(PBQPNum val = 0) {<br>
- std::fill(data, data + (rows * cols), val);<br>
- return *this;<br>
- }<br>
-<br>
- /// \brief Set a single row of this matrix to the given value.<br>
- Matrix& setRow(unsigned r, PBQPNum val) {<br>
- assert(r < rows && "Row out of bounds.");<br>
- std::fill(data + (r * cols), data + ((r + 1) * cols), val);<br>
- return *this;<br>
- }<br>
-<br>
- /// \brief Set a single column of this matrix to the given value.<br>
- Matrix& setCol(unsigned c, PBQPNum val) {<br>
- assert(c < cols && "Column out of bounds.");<br>
- for (unsigned r = 0; r < rows; ++r)<br>
- (*this)[r][c] = val;<br>
- return *this;<br>
- }<br>
-<br>
- /// \brief Matrix transpose.<br>
- Matrix transpose() const {<br>
- Matrix m(cols, rows);<br>
- for (unsigned r = 0; r < rows; ++r)<br>
- for (unsigned c = 0; c < cols; ++c)<br>
- m[c][r] = (*this)[r][c];<br>
- return m;<br>
- }<br>
-<br>
- /// \brief Returns the diagonal of the matrix as a vector.<br>
- ///<br>
- /// Matrix must be square.<br>
- Vector diagonalize() const {<br>
- assert(rows == cols && "Attempt to diagonalize non-square matrix.");<br>
-<br>
- Vector v(rows);<br>
- for (unsigned r = 0; r < rows; ++r)<br>
- v[r] = (*this)[r][r];<br>
- return v;<br>
- }<br>
-<br>
- /// \brief Add the given matrix to this one.<br>
- Matrix& operator+=(const Matrix &m) {<br>
- assert(rows == m.rows && cols == m.cols &&<br>
- "Matrix dimensions mismatch.");<br>
- std::transform(data, data + (rows * cols), m.data, data,<br>
- std::plus<PBQPNum>());<br>
- return *this;<br>
- }<br>
-<br>
- /// \brief Returns the minimum of the given row<br>
- PBQPNum getRowMin(unsigned r) const {<br>
- assert(r < rows && "Row out of bounds");<br>
- return *std::min_element(data + (r * cols), data + ((r + 1) * cols));<br>
- }<br>
-<br>
- /// \brief Returns the minimum of the given column<br>
- PBQPNum getColMin(unsigned c) const {<br>
- PBQPNum minElem = (*this)[0][c];<br>
- for (unsigned r = 1; r < rows; ++r)<br>
- if ((*this)[r][c] < minElem) minElem = (*this)[r][c];<br>
- return minElem;<br>
- }<br>
-<br>
- /// \brief Subtracts the given scalar from the elements of the given row.<br>
- Matrix& subFromRow(unsigned r, PBQPNum val) {<br>
- assert(r < rows && "Row out of bounds");<br>
- std::transform(data + (r * cols), data + ((r + 1) * cols),<br>
- data + (r * cols),<br>
- std::bind2nd(std::minus<PBQPNum>(), val));<br>
- return *this;<br>
- }<br>
-<br>
- /// \brief Subtracts the given scalar from the elements of the given column.<br>
- Matrix& subFromCol(unsigned c, PBQPNum val) {<br>
- for (unsigned r = 0; r < rows; ++r)<br>
- (*this)[r][c] -= val;<br>
- return *this;<br>
- }<br>
-<br>
- /// \brief Returns true if this is a zero matrix.<br>
- bool isZero() const {<br>
- return find_if(data, data + (rows * cols),<br>
- std::bind2nd(std::not_equal_to<PBQPNum>(), 0)) ==<br>
- data + (rows * cols);<br>
- }<br>
-<br>
- private:<br>
- unsigned rows, cols;<br>
- PBQPNum *data;<br>
+ /// \brief Add the given matrix to this one.<br>
+ Matrix& operator+=(const Matrix &M) {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ assert(Rows == M.Rows && Cols == M.Cols &&<br>
+ "Matrix dimensions mismatch.");<br>
+ std::transform(Data, Data + (Rows * Cols), M.Data, Data,<br>
+ std::plus<PBQPNum>());<br>
+ return *this;<br>
+ }<br>
+<br>
+ Matrix operator+(const Matrix &M) {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ Matrix Tmp(*this);<br>
+ Tmp += M;<br>
+ return Tmp;<br>
+ }<br>
+<br>
+ /// \brief Returns the minimum of the given row<br>
+ PBQPNum getRowMin(unsigned R) const {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ assert(R < Rows && "Row out of bounds");<br>
+ return *std::min_element(Data + (R * Cols), Data + ((R + 1) * Cols));<br>
+ }<br>
+<br>
+ /// \brief Returns the minimum of the given column<br>
+ PBQPNum getColMin(unsigned C) const {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ PBQPNum MinElem = (*this)[0][C];<br>
+ for (unsigned R = 1; R < Rows; ++R)<br>
+ if ((*this)[R][C] < MinElem)<br>
+ MinElem = (*this)[R][C];<br>
+ return MinElem;<br>
+ }<br>
+<br>
+ /// \brief Subtracts the given scalar from the elements of the given row.<br>
+ Matrix& subFromRow(unsigned R, PBQPNum Val) {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ assert(R < Rows && "Row out of bounds");<br>
+ std::transform(Data + (R * Cols), Data + ((R + 1) * Cols),<br>
+ Data + (R * Cols),<br>
+ std::bind2nd(std::minus<PBQPNum>(), Val));<br>
+ return *this;<br>
+ }<br>
+<br>
+ /// \brief Subtracts the given scalar from the elements of the given column.<br>
+ Matrix& subFromCol(unsigned C, PBQPNum Val) {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ for (unsigned R = 0; R < Rows; ++R)<br>
+ (*this)[R][C] -= Val;<br>
+ return *this;<br>
+ }<br>
+<br>
+ /// \brief Returns true if this is a zero matrix.<br>
+ bool isZero() const {<br>
+ assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix");<br>
+ return find_if(Data, Data + (Rows * Cols),<br>
+ std::bind2nd(std::not_equal_to<PBQPNum>(), 0)) ==<br>
+ Data + (Rows * Cols);<br>
+ }<br>
+<br>
+private:<br>
+ unsigned Rows, Cols;<br>
+ PBQPNum *Data;<br>
+};<br>
+<br>
+class MatrixComparator {<br>
+public:<br>
+ bool operator()(const Matrix &A, const Matrix &B) {<br>
+ if (A.Rows < B.Rows)<br>
+ return true;<br>
+ if (B.Rows < A.Rows)<br>
+ return false;<br>
+ if (A.Cols < B.Cols)<br>
+ return true;<br>
+ if (B.Cols < A.Cols)<br>
+ return false;<br>
+ char *AData = reinterpret_cast<char*>(A.Data);<br>
+ char *BData = reinterpret_cast<char*>(B.Data);<br>
+ return std::lexicographical_compare(<br>
+ AData, AData + (A.Rows * A.Cols * sizeof(PBQPNum)),<br>
+ BData, BData + (A.Rows * A.Cols * sizeof(PBQPNum)));<br>
+ }<br>
};<br>
<br>
/// \brief Output a textual representation of the given matrix on the given<br>
/// output stream.<br>
template <typename OStream><br>
-OStream& operator<<(OStream &os, const Matrix &m) {<br>
-<br>
- assert((m.getRows() != 0) && "Zero-row matrix badness.");<br>
+OStream& operator<<(OStream &OS, const Matrix &M) {<br>
+ assert((M.getRows() != 0) && "Zero-row matrix badness.");<br>
+ for (unsigned i = 0; i < M.getRows(); ++i)<br>
+ OS << M.getRowAsVector(i);<br>
+ return OS;<br>
+}<br>
<br>
- for (unsigned i = 0; i < m.getRows(); ++i) {<br>
- os << m.getRowAsVector(i);<br>
- }<br>
+template <typename Metadata><br>
+class MDVector : public Vector {<br>
+public:<br>
+ MDVector(const Vector &v) : Vector(v), md(*this) { }<br>
+ MDVector(Vector &&v) : Vector(std::move(v)), md(*this) { }<br>
+ const Metadata& getMetadata() const { return md; }<br>
+private:<br>
+ Metadata md;<br>
+};<br>
<br>
- return os;<br>
-}<br>
+template <typename Metadata><br>
+class MDMatrix : public Matrix {<br>
+public:<br>
+ MDMatrix(const Matrix &m) : Matrix(m), md(*this) { }<br>
+ MDMatrix(Matrix &&m) : Matrix(std::move(m)), md(*this) { }<br>
+ const Metadata& getMetadata() const { return md; }<br>
+private:<br>
+ Metadata md;<br>
+};<br>
<br>
}<br>
<br>
<br>
Added: llvm/trunk/include/llvm/CodeGen/PBQP/ReductionRules.h<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/ReductionRules.h?rev=202551&view=auto" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/ReductionRules.h?rev=202551&view=auto</a><br>
==============================================================================<br>
--- llvm/trunk/include/llvm/CodeGen/PBQP/ReductionRules.h (added)<br>
+++ llvm/trunk/include/llvm/CodeGen/PBQP/ReductionRules.h Fri Feb 28 16:25:24 2014<br>
@@ -0,0 +1,194 @@<br>
+//===----------- ReductionRules.h - Reduction Rules -------------*- C++ -*-===//<br>
+//<br>
+// The LLVM Compiler Infrastructure<br>
+//<br>
+// This file is distributed under the University of Illinois Open Source<br>
+// License. See LICENSE.TXT for details.<br>
+//<br>
+//===----------------------------------------------------------------------===//<br>
+//<br>
+// Reduction Rules.<br>
+//<br>
+//===----------------------------------------------------------------------===//<br>
+<br>
+#ifndef LLVM_REDUCTIONRULES_H<br>
+#define LLVM_REDUCTIONRULES_H<br>
+<br>
+#include "Graph.h"<br>
+#include "Math.h"<br>
+#include "Solution.h"<br>
+<br>
+namespace PBQP {<br>
+<br>
+ /// \brief Reduce a node of degree one.<br>
+ ///<br>
+ /// Propagate costs from the given node, which must be of degree one, to its<br>
+ /// neighbor. Notify the problem domain.<br>
+ template <typename GraphT><br>
+ void applyR1(GraphT &G, typename GraphT::NodeId NId) {<br>
+ typedef typename GraphT::NodeId NodeId;<br>
+ typedef typename GraphT::EdgeId EdgeId;<br>
+ typedef typename GraphT::Vector Vector;<br>
+ typedef typename GraphT::Matrix Matrix;<br>
+ typedef typename GraphT::RawVector RawVector;<br>
+<br>
+ assert(G.getNodeDegree(NId) == 1 &&<br>
+ "R1 applied to node with degree != 1.");<br>
+<br>
+ EdgeId EId = *G.adjEdgeIds(NId).begin();<br>
+ NodeId MId = G.getEdgeOtherNodeId(EId, NId);<br>
+<br>
+ const Matrix &ECosts = G.getEdgeCosts(EId);<br>
+ const Vector &XCosts = G.getNodeCosts(NId);<br>
+ RawVector YCosts = G.getNodeCosts(MId);<br>
+<br>
+ // Duplicate a little to avoid transposing matrices.<br>
+ if (NId == G.getEdgeNode1Id(EId)) {<br>
+ for (unsigned j = 0; j < YCosts.getLength(); ++j) {<br>
+ PBQPNum Min = ECosts[0][j] + XCosts[0];<br>
+ for (unsigned i = 1; i < XCosts.getLength(); ++i) {<br>
+ PBQPNum C = ECosts[i][j] + XCosts[i];<br>
+ if (C < Min)<br>
+ Min = C;<br>
+ }<br>
+ YCosts[j] += Min;<br>
+ }<br>
+ } else {<br>
+ for (unsigned i = 0; i < YCosts.getLength(); ++i) {<br>
+ PBQPNum Min = ECosts[i][0] + XCosts[0];<br>
+ for (unsigned j = 1; j < XCosts.getLength(); ++j) {<br>
+ PBQPNum C = ECosts[i][j] + XCosts[j];<br>
+ if (C < Min)<br>
+ Min = C;<br>
+ }<br>
+ YCosts[i] += Min;<br>
+ }<br>
+ }<br>
+ G.setNodeCosts(MId, YCosts);<br>
+ G.disconnectEdge(EId, MId);<br>
+ }<br>
+<br>
+ template <typename GraphT><br>
+ void applyR2(GraphT &G, typename GraphT::NodeId NId) {<br>
+ typedef typename GraphT::NodeId NodeId;<br>
+ typedef typename GraphT::EdgeId EdgeId;<br>
+ typedef typename GraphT::Vector Vector;<br>
+ typedef typename GraphT::Matrix Matrix;<br>
+ typedef typename GraphT::RawMatrix RawMatrix;<br>
+<br>
+ assert(G.getNodeDegree(NId) == 2 &&<br>
+ "R2 applied to node with degree != 2.");<br>
+<br>
+ const Vector &XCosts = G.getNodeCosts(NId);<br>
+<br>
+ typename GraphT::AdjEdgeItr AEItr = G.adjEdgeIds(NId).begin();<br>
+ EdgeId YXEId = *AEItr,<br>
+ ZXEId = *(++AEItr);<br>
+<br>
+ NodeId YNId = G.getEdgeOtherNodeId(YXEId, NId),<br>
+ ZNId = G.getEdgeOtherNodeId(ZXEId, NId);<br>
+<br>
+ bool FlipEdge1 = (G.getEdgeNode1Id(YXEId) == NId),<br>
+ FlipEdge2 = (G.getEdgeNode1Id(ZXEId) == NId);<br>
+<br>
+ const Matrix *YXECosts = FlipEdge1 ?<br>
+ new Matrix(G.getEdgeCosts(YXEId).transpose()) :<br></blockquote><div><br></div><div>I'd consider having a unique_ptr<Matrix> here to handle the owning case, something like:<br><br>std::unique_ptr<Matrix> owner;<br>
const Matrix *YXECosts = FlipEdge1 ? (owner = MakeUnique<Matrix>(...)) : &G.get... ;<br></div><div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
+ &G.getEdgeCosts(YXEId);<br>
+<br>
+ const Matrix *ZXECosts = FlipEdge2 ?<br>
+ new Matrix(G.getEdgeCosts(ZXEId).transpose()) :<br>
+ &G.getEdgeCosts(ZXEId);<br>
+<br>
+ unsigned XLen = XCosts.getLength(),<br>
+ YLen = YXECosts->getRows(),<br>
+ ZLen = ZXECosts->getRows();<br>
+<br>
+ RawMatrix Delta(YLen, ZLen);<br>
+<br>
+ for (unsigned i = 0; i < YLen; ++i) {<br>
+ for (unsigned j = 0; j < ZLen; ++j) {<br>
+ PBQPNum Min = (*YXECosts)[i][0] + (*ZXECosts)[j][0] + XCosts[0];<br>
+ for (unsigned k = 1; k < XLen; ++k) {<br>
+ PBQPNum C = (*YXECosts)[i][k] + (*ZXECosts)[j][k] + XCosts[k];<br>
+ if (C < Min) {<br>
+ Min = C;<br>
+ }<br>
+ }<br>
+ Delta[i][j] = Min;<br>
+ }<br>
+ }<br>
+<br>
+ if (FlipEdge1)<br>
+ delete YXECosts;<br></blockquote><div><br></div><div>You could introduce an extra lexical scope if this is where you want those matrices to be destroyed (once they used scoped ownership).</div><div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
+<br>
+ if (FlipEdge2)<br>
+ delete ZXECosts;<br>
+<br>
+ EdgeId YZEId = G.findEdge(YNId, ZNId);<br>
+ bool AddedEdge = false;<br>
+<br>
+ if (YZEId == G.invalidEdgeId()) {<br>
+ YZEId = G.addEdge(YNId, ZNId, Delta);<br>
+ AddedEdge = true;<br>
+ } else {<br>
+ const Matrix &YZECosts = G.getEdgeCosts(YZEId);<br>
+ if (YNId == G.getEdgeNode1Id(YZEId)) {<br>
+ G.setEdgeCosts(YZEId, Delta + YZECosts);<br>
+ } else {<br>
+ G.setEdgeCosts(YZEId, Delta.transpose() + YZECosts);<br>
+ }<br>
+ }<br>
+<br>
+ G.disconnectEdge(YXEId, YNId);<br>
+ G.disconnectEdge(ZXEId, ZNId);<br>
+<br>
+ // TODO: Try to normalize newly added/modified edge.<br>
+ }<br>
+<br>
+<br>
+ // \brief Find a solution to a fully reduced graph by backpropagation.<br>
+ //<br>
+ // Given a graph and a reduction order, pop each node from the reduction<br>
+ // order and greedily compute a minimum solution based on the node costs, and<br>
+ // the dependent costs due to previously solved nodes.<br>
+ //<br>
+ // Note - This does not return the graph to its original (pre-reduction)<br>
+ // state: the existing solvers destructively alter the node and edge<br>
+ // costs. Given that, the backpropagate function doesn't attempt to<br>
+ // replace the edges either, but leaves the graph in its reduced<br>
+ // state.<br>
+ template <typename GraphT, typename StackT><br>
+ Solution backpropagate(GraphT& G, StackT stack) {<br>
+ typedef GraphBase::NodeId NodeId;<br>
+ typedef GraphBase::EdgeId EdgeId;<br>
+ typedef typename GraphT::Matrix Matrix;<br>
+ typedef typename GraphT::RawVector RawVector;<br>
+<br>
+ Solution s;<br>
+<br>
+ while (!stack.empty()) {<br>
+ NodeId NId = stack.back();<br>
+ stack.pop_back();<br>
+<br>
+ RawVector v = G.getNodeCosts(NId);<br>
+<br>
+ for (auto EId : G.adjEdgeIds(NId)) {<br>
+ const Matrix& edgeCosts = G.getEdgeCosts(EId);<br>
+ if (NId == G.getEdgeNode1Id(EId)) {<br>
+ NodeId mId = G.getEdgeNode2Id(EId);<br>
+ v += edgeCosts.getColAsVector(s.getSelection(mId));<br>
+ } else {<br>
+ NodeId mId = G.getEdgeNode1Id(EId);<br>
+ v += edgeCosts.getRowAsVector(s.getSelection(mId));<br>
+ }<br>
+ }<br>
+<br>
+ s.setSelection(NId, v.minIndex());<br>
+ }<br>
+<br>
+ return s;<br>
+ }<br>
+<br>
+}<br>
+<br>
+#endif // LLVM_REDUCTIONRULES_H<br>
<br>
Added: llvm/trunk/include/llvm/CodeGen/PBQP/RegAllocSolver.h<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/RegAllocSolver.h?rev=202551&view=auto" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/RegAllocSolver.h?rev=202551&view=auto</a><br>
==============================================================================<br>
--- llvm/trunk/include/llvm/CodeGen/PBQP/RegAllocSolver.h (added)<br>
+++ llvm/trunk/include/llvm/CodeGen/PBQP/RegAllocSolver.h Fri Feb 28 16:25:24 2014<br>
@@ -0,0 +1,359 @@<br>
+//===-- RegAllocSolver.h - Heuristic PBQP Solver for reg alloc --*- C++ -*-===//<br>
+//<br>
+// The LLVM Compiler Infrastructure<br>
+//<br>
+// This file is distributed under the University of Illinois Open Source<br>
+// License. See LICENSE.TXT for details.<br>
+//<br>
+//===----------------------------------------------------------------------===//<br>
+//<br>
+// Heuristic PBQP solver for register allocation problems. This solver uses a<br>
+// graph reduction approach. Nodes of degree 0, 1 and 2 are eliminated with<br>
+// optimality-preserving rules (see ReductionRules.h). When no low-degree (<3)<br>
+// nodes are present, a heuristic derived from Brigg's graph coloring approach<br>
+// is used.<br>
+//<br>
+//===----------------------------------------------------------------------===//<br>
+<br>
+#ifndef LLVM_CODEGEN_PBQP_REGALLOCSOLVER_H<br>
+#define LLVM_CODEGEN_PBQP_REGALLOCSOLVER_H<br>
+<br>
+#include "CostAllocator.h"<br>
+#include "Graph.h"<br>
+#include "ReductionRules.h"<br>
+#include "Solution.h"<br>
+#include "llvm/Support/ErrorHandling.h"<br>
+#include <limits><br>
+#include <vector><br>
+<br>
+namespace PBQP {<br>
+<br>
+ namespace RegAlloc {<br>
+<br>
+ /// \brief Metadata to speed allocatability test.<br>
+ ///<br>
+ /// Keeps track of the number of infinities in each row and column.<br>
+ class MatrixMetadata {<br>
+ private:<br>
+ MatrixMetadata(const MatrixMetadata&);<br>
+ void operator=(const MatrixMetadata&);<br>
+ public:<br>
+ MatrixMetadata(const PBQP::Matrix& m)<br>
+ : worstRow(0), worstCol(0),<br>
+ unsafeRows(new bool[m.getRows() - 1]()),<br></blockquote><div><br></div><div>*twitch* really? a bool array? Do you need them to be individually referenced bools, or is a bitfieldOK? (in any case, again - std::unique_ptr<bool[]>, std::bitfield, etc, etc... )</div>
<div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
+ unsafeCols(new bool[m.getCols() - 1]()) {<br>
+<br>
+ unsigned* colCounts = new unsigned[m.getCols() - 1]();<br>
+<br>
+ for (unsigned i = 1; i < m.getRows(); ++i) {<br>
+ unsigned rowCount = 0;<br>
+ for (unsigned j = 1; j < m.getCols(); ++j) {<br>
+ if (m[i][j] == std::numeric_limits<PBQP::PBQPNum>::infinity()) {<br>
+ ++rowCount;<br>
+ ++colCounts[j - 1];<br>
+ unsafeRows[i - 1] = true;<br>
+ unsafeCols[j - 1] = true;<br>
+ }<br>
+ }<br>
+ worstRow = std::max(worstRow, rowCount);<br>
+ }<br>
+ unsigned worstColCountForCurRow =<br>
+ *std::max_element(colCounts, colCounts + m.getCols() - 1);<br>
+ worstCol = std::max(worstCol, worstColCountForCurRow);<br>
+ delete[] colCounts;<br>
+ }<br>
+<br>
+ ~MatrixMetadata() {<br>
+ delete[] unsafeRows;<br>
+ delete[] unsafeCols;<br>
+ }<br>
+<br>
+ unsigned getWorstRow() const { return worstRow; }<br>
+ unsigned getWorstCol() const { return worstCol; }<br>
+ const bool* getUnsafeRows() const { return unsafeRows; }<br>
+ const bool* getUnsafeCols() const { return unsafeCols; }<br>
+<br>
+ private:<br>
+ unsigned worstRow, worstCol;<br>
+ bool* unsafeRows;<br>
+ bool* unsafeCols;<br>
+ };<br>
+<br>
+ class NodeMetadata {<br>
+ public:<br>
+ typedef enum { Unprocessed,<br>
+ OptimallyReducible,<br>
+ ConservativelyAllocatable,<br>
+ NotProvablyAllocatable } ReductionState;<br>
+<br>
+ NodeMetadata() : rs(Unprocessed), deniedOpts(0), optUnsafeEdges(0) {}<br>
+ ~NodeMetadata() { delete[] optUnsafeEdges; }<br>
+<br>
+ void setup(const Vector& costs) {<br>
+ numOpts = costs.getLength() - 1;<br>
+ optUnsafeEdges = new unsigned[numOpts]();<br>
+ }<br>
+<br>
+ ReductionState getReductionState() const { return rs; }<br>
+ void setReductionState(ReductionState rs) { this->rs = rs; }<br>
+<br>
+ void handleAddEdge(const MatrixMetadata& md, bool transpose) {<br>
+ deniedOpts += transpose ? md.getWorstCol() : md.getWorstRow();<br>
+ const bool* unsafeOpts =<br>
+ transpose ? md.getUnsafeCols() : md.getUnsafeRows();<br>
+ for (unsigned i = 0; i < numOpts; ++i)<br>
+ optUnsafeEdges[i] += unsafeOpts[i];<br>
+ }<br>
+<br>
+ void handleRemoveEdge(const MatrixMetadata& md, bool transpose) {<br>
+ deniedOpts -= transpose ? md.getWorstCol() : md.getWorstRow();<br>
+ const bool* unsafeOpts =<br>
+ transpose ? md.getUnsafeCols() : md.getUnsafeRows();<br>
+ for (unsigned i = 0; i < numOpts; ++i)<br>
+ optUnsafeEdges[i] -= unsafeOpts[i];<br>
+ }<br>
+<br>
+ bool isConservativelyAllocatable() const {<br>
+ return (deniedOpts < numOpts) ||<br>
+ (std::find(optUnsafeEdges, optUnsafeEdges + numOpts, 0) !=<br>
+ optUnsafeEdges + numOpts);<br>
+ }<br>
+<br>
+ private:<br>
+ ReductionState rs;<br>
+ unsigned numOpts;<br>
+ unsigned deniedOpts;<br>
+ unsigned* optUnsafeEdges;<br>
+ };<br>
+<br>
+ class RegAllocSolverImpl {<br>
+ private:<br>
+ typedef PBQP::MDMatrix<MatrixMetadata> RAMatrix;<br>
+ public:<br>
+ typedef PBQP::Vector RawVector;<br>
+ typedef PBQP::Matrix RawMatrix;<br>
+ typedef PBQP::Vector Vector;<br>
+ typedef RAMatrix Matrix;<br>
+ typedef PBQP::PoolCostAllocator<<br>
+ Vector, PBQP::VectorComparator,<br>
+ Matrix, PBQP::MatrixComparator> CostAllocator;<br>
+<br>
+ typedef PBQP::GraphBase::NodeId NodeId;<br>
+ typedef PBQP::GraphBase::EdgeId EdgeId;<br>
+<br>
+ typedef RegAlloc::NodeMetadata NodeMetadata;<br>
+<br>
+ struct EdgeMetadata { };<br>
+<br>
+ typedef PBQP::Graph<RegAllocSolverImpl> Graph;<br>
+<br>
+ RegAllocSolverImpl(Graph &G) : G(G) {}<br>
+<br>
+ Solution solve() {<br>
+ G.setSolver(*this);<br>
+ Solution S;<br>
+ setup();<br>
+ S = backpropagate(G, reduce());<br>
+ G.unsetSolver();<br>
+ return S;<br>
+ }<br>
+<br>
+ void handleAddNode(NodeId NId) {<br>
+ G.getNodeMetadata(NId).setup(G.getNodeCosts(NId));<br>
+ }<br>
+ void handleRemoveNode(NodeId NId) {}<br>
+ void handleSetNodeCosts(NodeId NId, const Vector& newCosts) {}<br>
+<br>
+ void handleAddEdge(EdgeId EId) {<br>
+ handleReconnectEdge(EId, G.getEdgeNode1Id(EId));<br>
+ handleReconnectEdge(EId, G.getEdgeNode2Id(EId));<br>
+ }<br>
+<br>
+ void handleRemoveEdge(EdgeId EId) {<br>
+ handleDisconnectEdge(EId, G.getEdgeNode1Id(EId));<br>
+ handleDisconnectEdge(EId, G.getEdgeNode2Id(EId));<br>
+ }<br>
+<br>
+ void handleDisconnectEdge(EdgeId EId, NodeId NId) {<br>
+ NodeMetadata& nMd = G.getNodeMetadata(NId);<br>
+ const MatrixMetadata& mMd = G.getEdgeCosts(EId).getMetadata();<br>
+ nMd.handleRemoveEdge(mMd, NId == G.getEdgeNode2Id(EId));<br>
+ if (G.getNodeDegree(NId) == 3) {<br>
+ // This node is becoming optimally reducible.<br>
+ moveToOptimallyReducibleNodes(NId);<br>
+ } else if (nMd.getReductionState() ==<br>
+ NodeMetadata::NotProvablyAllocatable &&<br>
+ nMd.isConservativelyAllocatable()) {<br>
+ // This node just became conservatively allocatable.<br>
+ moveToConservativelyAllocatableNodes(NId);<br>
+ }<br>
+ }<br>
+<br>
+ void handleReconnectEdge(EdgeId EId, NodeId NId) {<br>
+ NodeMetadata& nMd = G.getNodeMetadata(NId);<br>
+ const MatrixMetadata& mMd = G.getEdgeCosts(EId).getMetadata();<br>
+ nMd.handleAddEdge(mMd, NId == G.getEdgeNode2Id(EId));<br>
+ }<br>
+<br>
+ void handleSetEdgeCosts(EdgeId EId, const Matrix& NewCosts) {<br>
+ handleRemoveEdge(EId);<br>
+<br>
+ NodeId n1Id = G.getEdgeNode1Id(EId);<br>
+ NodeId n2Id = G.getEdgeNode2Id(EId);<br>
+ NodeMetadata& n1Md = G.getNodeMetadata(n1Id);<br>
+ NodeMetadata& n2Md = G.getNodeMetadata(n2Id);<br>
+ const MatrixMetadata& mMd = NewCosts.getMetadata();<br>
+ n1Md.handleAddEdge(mMd, n1Id != G.getEdgeNode1Id(EId));<br>
+ n2Md.handleAddEdge(mMd, n2Id != G.getEdgeNode1Id(EId));<br>
+ }<br>
+<br>
+ private:<br>
+<br>
+ void removeFromCurrentSet(NodeId NId) {<br>
+ switch (G.getNodeMetadata(NId).getReductionState()) {<br>
+ case NodeMetadata::Unprocessed: break;<br>
+ case NodeMetadata::OptimallyReducible:<br>
+ assert(OptimallyReducibleNodes.find(NId) !=<br>
+ OptimallyReducibleNodes.end() &&<br>
+ "Node not in optimally reducible set.");<br>
+ OptimallyReducibleNodes.erase(NId);<br>
+ break;<br>
+ case NodeMetadata::ConservativelyAllocatable:<br>
+ assert(ConservativelyAllocatableNodes.find(NId) !=<br>
+ ConservativelyAllocatableNodes.end() &&<br>
+ "Node not in conservatively allocatable set.");<br>
+ ConservativelyAllocatableNodes.erase(NId);<br>
+ break;<br>
+ case NodeMetadata::NotProvablyAllocatable:<br>
+ assert(NotProvablyAllocatableNodes.find(NId) !=<br>
+ NotProvablyAllocatableNodes.end() &&<br>
+ "Node not in not-provably-allocatable set.");<br>
+ NotProvablyAllocatableNodes.erase(NId);<br>
+ break;<br>
+ }<br>
+ }<br>
+<br>
+ void moveToOptimallyReducibleNodes(NodeId NId) {<br>
+ removeFromCurrentSet(NId);<br>
+ OptimallyReducibleNodes.insert(NId);<br>
+ G.getNodeMetadata(NId).setReductionState(<br>
+ NodeMetadata::OptimallyReducible);<br>
+ }<br>
+<br>
+ void moveToConservativelyAllocatableNodes(NodeId NId) {<br>
+ removeFromCurrentSet(NId);<br>
+ ConservativelyAllocatableNodes.insert(NId);<br>
+ G.getNodeMetadata(NId).setReductionState(<br>
+ NodeMetadata::ConservativelyAllocatable);<br>
+ }<br>
+<br>
+ void moveToNotProvablyAllocatableNodes(NodeId NId) {<br>
+ removeFromCurrentSet(NId);<br>
+ NotProvablyAllocatableNodes.insert(NId);<br>
+ G.getNodeMetadata(NId).setReductionState(<br>
+ NodeMetadata::NotProvablyAllocatable);<br>
+ }<br>
+<br>
+ void setup() {<br>
+ // Set up worklists.<br>
+ for (auto NId : G.nodeIds()) {<br>
+ if (G.getNodeDegree(NId) < 3)<br>
+ moveToOptimallyReducibleNodes(NId);<br>
+ else if (G.getNodeMetadata(NId).isConservativelyAllocatable())<br>
+ moveToConservativelyAllocatableNodes(NId);<br>
+ else<br>
+ moveToNotProvablyAllocatableNodes(NId);<br>
+ }<br>
+ }<br>
+<br>
+ // Compute a reduction order for the graph by iteratively applying PBQP<br>
+ // reduction rules. Locally optimal rules are applied whenever possible (R0,<br>
+ // R1, R2). If no locally-optimal rules apply then any conservatively<br>
+ // allocatable node is reduced. Finally, if no conservatively allocatable<br>
+ // node exists then the node with the lowest spill-cost:degree ratio is<br>
+ // selected.<br>
+ std::vector<GraphBase::NodeId> reduce() {<br>
+ assert(!G.empty() && "Cannot reduce empty graph.");<br>
+<br>
+ typedef GraphBase::NodeId NodeId;<br>
+ std::vector<NodeId> NodeStack;<br>
+<br>
+ // Consume worklists.<br>
+ while (true) {<br>
+ if (!OptimallyReducibleNodes.empty()) {<br>
+ NodeSet::iterator nItr = OptimallyReducibleNodes.begin();<br>
+ NodeId NId = *nItr;<br>
+ OptimallyReducibleNodes.erase(nItr);<br>
+ NodeStack.push_back(NId);<br>
+ switch (G.getNodeDegree(NId)) {<br>
+ case 0:<br>
+ break;<br>
+ case 1:<br>
+ applyR1(G, NId);<br>
+ break;<br>
+ case 2:<br>
+ applyR2(G, NId);<br>
+ break;<br>
+ default: llvm_unreachable("Not an optimally reducible node.");<br>
+ }<br>
+ } else if (!ConservativelyAllocatableNodes.empty()) {<br>
+ // Conservatively allocatable nodes will never spill. For now just<br>
+ // take the first node in the set and push it on the stack. When we<br>
+ // start optimizing more heavily for register preferencing, it may<br>
+ // would be better to push nodes with lower 'expected' or worst-case<br>
+ // register costs first (since early nodes are the most<br>
+ // constrained).<br>
+ NodeSet::iterator nItr = ConservativelyAllocatableNodes.begin();<br>
+ NodeId NId = *nItr;<br>
+ ConservativelyAllocatableNodes.erase(nItr);<br>
+ NodeStack.push_back(NId);<br>
+ G.disconnectAllNeighborsFromNode(NId);<br>
+<br>
+ } else if (!NotProvablyAllocatableNodes.empty()) {<br>
+ NodeSet::iterator nItr =<br>
+ std::min_element(NotProvablyAllocatableNodes.begin(),<br>
+ NotProvablyAllocatableNodes.end(),<br>
+ SpillCostComparator(G));<br>
+ NodeId NId = *nItr;<br>
+ NotProvablyAllocatableNodes.erase(nItr);<br>
+ NodeStack.push_back(NId);<br>
+ G.disconnectAllNeighborsFromNode(NId);<br>
+ } else<br>
+ break;<br>
+ }<br>
+<br>
+ return NodeStack;<br>
+ }<br>
+<br>
+ class SpillCostComparator {<br>
+ public:<br>
+ SpillCostComparator(const Graph& G) : G(G) {}<br>
+ bool operator()(NodeId N1Id, NodeId N2Id) {<br>
+ PBQPNum N1SC = G.getNodeCosts(N1Id)[0] / G.getNodeDegree(N1Id);<br>
+ PBQPNum N2SC = G.getNodeCosts(N2Id)[0] / G.getNodeDegree(N2Id);<br>
+ return N1SC < N2SC;<br>
+ }<br>
+ private:<br>
+ const Graph& G;<br>
+ };<br>
+<br>
+ Graph& G;<br>
+ typedef std::set<NodeId> NodeSet;<br>
+ NodeSet OptimallyReducibleNodes;<br>
+ NodeSet ConservativelyAllocatableNodes;<br>
+ NodeSet NotProvablyAllocatableNodes;<br>
+ };<br>
+<br>
+ typedef Graph<RegAllocSolverImpl> Graph;<br>
+<br>
+ Solution solve(Graph& G) {<br>
+ if (G.empty())<br>
+ return Solution();<br>
+ RegAllocSolverImpl RegAllocSolver(G);<br>
+ return RegAllocSolver.solve();<br>
+ }<br>
+<br>
+ }<br>
+}<br>
+<br>
+#endif // LLVM_CODEGEN_PBQP_REGALLOCSOLVER_H<br>
<br>
Modified: llvm/trunk/include/llvm/CodeGen/PBQP/Solution.h<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/Solution.h?rev=202551&r1=202550&r2=202551&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/PBQP/Solution.h?rev=202551&r1=202550&r2=202551&view=diff</a><br>
==============================================================================<br>
--- llvm/trunk/include/llvm/CodeGen/PBQP/Solution.h (original)<br>
+++ llvm/trunk/include/llvm/CodeGen/PBQP/Solution.h Fri Feb 28 16:25:24 2014<br>
@@ -26,7 +26,7 @@ namespace PBQP {<br>
class Solution {<br>
private:<br>
<br>
- typedef std::map<Graph::NodeId, unsigned> SelectionsMap;<br>
+ typedef std::map<GraphBase::NodeId, unsigned> SelectionsMap;<br>
SelectionsMap selections;<br>
<br>
unsigned r0Reductions, r1Reductions, r2Reductions, rNReductions;<br>
@@ -72,14 +72,14 @@ namespace PBQP {<br>
/// \brief Set the selection for a given node.<br>
/// @param nodeId Node id.<br>
/// @param selection Selection for nodeId.<br>
- void setSelection(Graph::NodeId nodeId, unsigned selection) {<br>
+ void setSelection(GraphBase::NodeId nodeId, unsigned selection) {<br>
selections[nodeId] = selection;<br>
}<br>
<br>
/// \brief Get a node's selection.<br>
/// @param nodeId Node id.<br>
/// @return The selection for nodeId;<br>
- unsigned getSelection(Graph::NodeId nodeId) const {<br>
+ unsigned getSelection(GraphBase::NodeId nodeId) const {<br>
SelectionsMap::const_iterator sItr = selections.find(nodeId);<br>
assert(sItr != selections.end() && "No selection for node.");<br>
return sItr->second;<br>
<br>
Modified: llvm/trunk/include/llvm/CodeGen/RegAllocPBQP.h<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/RegAllocPBQP.h?rev=202551&r1=202550&r2=202551&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/RegAllocPBQP.h?rev=202551&r1=202550&r2=202551&view=diff</a><br>
==============================================================================<br>
--- llvm/trunk/include/llvm/CodeGen/RegAllocPBQP.h (original)<br>
+++ llvm/trunk/include/llvm/CodeGen/RegAllocPBQP.h Fri Feb 28 16:25:24 2014<br>
@@ -17,9 +17,9 @@<br>
#define LLVM_CODEGEN_REGALLOCPBQP_H<br>
<br>
#include "llvm/ADT/DenseMap.h"<br>
+#include "llvm/ADT/SmallVector.h"<br>
#include "llvm/CodeGen/MachineFunctionPass.h"<br>
-#include "llvm/CodeGen/PBQP/Graph.h"<br>
-#include "llvm/CodeGen/PBQP/Solution.h"<br>
+#include "llvm/CodeGen/PBQP/RegAllocSolver.h"<br>
#include <map><br>
#include <set><br>
<br>
@@ -31,28 +31,29 @@ namespace llvm {<br>
class TargetRegisterInfo;<br>
template<class T> class OwningPtr;<br>
<br>
+ typedef PBQP::RegAlloc::Graph PBQPRAGraph;<br>
+<br>
/// This class wraps up a PBQP instance representing a register allocation<br>
/// problem, plus the structures necessary to map back from the PBQP solution<br>
/// to a register allocation solution. (i.e. The PBQP-node <--> vreg map,<br>
/// and the PBQP option <--> storage location map).<br>
-<br>
class PBQPRAProblem {<br>
public:<br>
<br>
typedef SmallVector<unsigned, 16> AllowedSet;<br>
<br>
- PBQP::Graph& getGraph() { return graph; }<br>
+ PBQPRAGraph& getGraph() { return graph; }<br>
<br>
- const PBQP::Graph& getGraph() const { return graph; }<br>
+ const PBQPRAGraph& getGraph() const { return graph; }<br>
<br>
/// Record the mapping between the given virtual register and PBQP node,<br>
/// and the set of allowed pregs for the vreg.<br>
///<br>
/// If you are extending<br>
/// PBQPBuilder you are unlikely to need this: Nodes and options for all<br>
- /// vregs will already have been set up for you by the base class.<br>
+ /// vregs will already have been set up for you by the base class.<br>
template <typename AllowedRegsItr><br>
- void recordVReg(unsigned vreg, PBQP::Graph::NodeId nodeId,<br>
+ void recordVReg(unsigned vreg, PBQPRAGraph::NodeId nodeId,<br>
AllowedRegsItr arBegin, AllowedRegsItr arEnd) {<br>
assert(node2VReg.find(nodeId) == node2VReg.end() && "Re-mapping node.");<br>
assert(vreg2Node.find(vreg) == vreg2Node.end() && "Re-mapping vreg.");<br>
@@ -64,10 +65,10 @@ namespace llvm {<br>
}<br>
<br>
/// Get the virtual register corresponding to the given PBQP node.<br>
- unsigned getVRegForNode(PBQP::Graph::NodeId nodeId) const;<br>
+ unsigned getVRegForNode(PBQPRAGraph::NodeId nodeId) const;<br>
<br>
/// Get the PBQP node corresponding to the given virtual register.<br>
- PBQP::Graph::NodeId getNodeForVReg(unsigned vreg) const;<br>
+ PBQPRAGraph::NodeId getNodeForVReg(unsigned vreg) const;<br>
<br>
/// Returns true if the given PBQP option represents a physical register,<br>
/// false otherwise.<br>
@@ -92,16 +93,16 @@ namespace llvm {<br>
<br>
private:<br>
<br>
- typedef std::map<PBQP::Graph::NodeId, unsigned> Node2VReg;<br>
- typedef DenseMap<unsigned, PBQP::Graph::NodeId> VReg2Node;<br>
+ typedef std::map<PBQPRAGraph::NodeId, unsigned> Node2VReg;<br>
+ typedef DenseMap<unsigned, PBQPRAGraph::NodeId> VReg2Node;<br>
typedef DenseMap<unsigned, AllowedSet> AllowedSetMap;<br>
<br>
- PBQP::Graph graph;<br>
+ PBQPRAGraph graph;<br>
Node2VReg node2VReg;<br>
VReg2Node vreg2Node;<br>
<br>
AllowedSetMap allowedSets;<br>
-<br>
+<br>
};<br>
<br>
/// Builds PBQP instances to represent register allocation problems. Includes<br>
@@ -114,7 +115,7 @@ namespace llvm {<br>
public:<br>
<br>
typedef std::set<unsigned> RegSet;<br>
-<br>
+<br>
/// Default constructor.<br>
PBQPBuilder() {}<br>
<br>
@@ -139,12 +140,12 @@ namespace llvm {<br>
/// Extended builder which adds coalescing constraints to a problem.<br>
class PBQPBuilderWithCoalescing : public PBQPBuilder {<br>
public:<br>
-<br>
+<br>
/// Build a PBQP instance to represent the register allocation problem for<br>
/// the given MachineFunction.<br>
virtual PBQPRAProblem *build(MachineFunction *mf, const LiveIntervals *lis,<br>
const MachineBlockFrequencyInfo *mbfi,<br>
- const RegSet &vregs);<br>
+ const RegSet &vregs);<br>
<br>
private:<br>
<br>
<br>
Modified: llvm/trunk/lib/CodeGen/RegAllocPBQP.cpp<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/RegAllocPBQP.cpp?rev=202551&r1=202550&r2=202551&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/RegAllocPBQP.cpp?rev=202551&r1=202550&r2=202551&view=diff</a><br>
==============================================================================<br>
--- llvm/trunk/lib/CodeGen/RegAllocPBQP.cpp (original)<br>
+++ llvm/trunk/lib/CodeGen/RegAllocPBQP.cpp Fri Feb 28 16:25:24 2014<br>
@@ -45,9 +45,6 @@<br>
#include "llvm/CodeGen/MachineFunctionPass.h"<br>
#include "llvm/CodeGen/MachineLoopInfo.h"<br>
#include "llvm/CodeGen/MachineRegisterInfo.h"<br>
-#include "llvm/CodeGen/PBQP/Graph.h"<br>
-#include "llvm/CodeGen/PBQP/HeuristicSolver.h"<br>
-#include "llvm/CodeGen/PBQP/Heuristics/Briggs.h"<br>
#include "llvm/CodeGen/RegAllocRegistry.h"<br>
#include "llvm/CodeGen/VirtRegMap.h"<br>
#include "llvm/IR/Module.h"<br>
@@ -157,13 +154,13 @@ char RegAllocPBQP::ID = 0;<br>
<br>
} // End anonymous namespace.<br>
<br>
-unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::NodeId node) const {<br>
+unsigned PBQPRAProblem::getVRegForNode(PBQPRAGraph::NodeId node) const {<br>
Node2VReg::const_iterator vregItr = node2VReg.find(node);<br>
assert(vregItr != node2VReg.end() && "No vreg for node.");<br>
return vregItr->second;<br>
}<br>
<br>
-PBQP::Graph::NodeId PBQPRAProblem::getNodeForVReg(unsigned vreg) const {<br>
+PBQPRAGraph::NodeId PBQPRAProblem::getNodeForVReg(unsigned vreg) const {<br>
VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);<br>
assert(nodeItr != vreg2Node.end() && "No node for vreg.");<br>
return nodeItr->second;<br>
@@ -195,7 +192,7 @@ PBQPRAProblem *PBQPBuilder::build(Machin<br>
const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();<br>
<br>
OwningPtr<PBQPRAProblem> p(new PBQPRAProblem());<br>
- PBQP::Graph &g = p->getGraph();<br>
+ PBQPRAGraph &g = p->getGraph();<br>
RegSet pregs;<br>
<br>
// Collect the set of preg intervals, record that they're used in the MF.<br>
@@ -245,17 +242,19 @@ PBQPRAProblem *PBQPBuilder::build(Machin<br>
vrAllowed.push_back(preg);<br>
}<br>
<br>
- // Construct the node.<br>
- PBQP::Graph::NodeId node =<br>
- g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));<br>
-<br>
- // Record the mapping and allowed set in the problem.<br>
- p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());<br>
+ PBQP::Vector nodeCosts(vrAllowed.size() + 1, 0);<br>
<br>
PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?<br>
vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();<br>
<br>
- addSpillCosts(g.getNodeCosts(node), spillCost);<br>
+ addSpillCosts(nodeCosts, spillCost);<br>
+<br>
+ // Construct the node.<br>
+ PBQPRAGraph::NodeId nId = g.addNode(std::move(nodeCosts));<br>
+<br>
+ // Record the mapping and allowed set in the problem.<br>
+ p->recordVReg(vreg, nId, vrAllowed.begin(), vrAllowed.end());<br>
+<br>
}<br>
<br>
for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();<br>
@@ -272,11 +271,11 @@ PBQPRAProblem *PBQPBuilder::build(Machin<br>
<br>
assert(!l2.empty() && "Empty interval in vreg set?");<br>
if (l1.overlaps(l2)) {<br>
- PBQP::Graph::EdgeId edge =<br>
- g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),<br>
- PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));<br>
+ PBQP::Matrix edgeCosts(vr1Allowed.size()+1, vr2Allowed.size()+1, 0);<br>
+ addInterferenceCosts(edgeCosts, vr1Allowed, vr2Allowed, tri);<br>
<br>
- addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);<br>
+ g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),<br>
+ std::move(edgeCosts));<br>
}<br>
}<br>
}<br>
@@ -316,7 +315,7 @@ PBQPRAProblem *PBQPBuilderWithCoalescing<br>
const RegSet &vregs) {<br>
<br>
OwningPtr<PBQPRAProblem> p(PBQPBuilder::build(mf, lis, mbfi, vregs));<br>
- PBQP::Graph &g = p->getGraph();<br>
+ PBQPRAGraph &g = p->getGraph();<br>
<br>
const TargetMachine &tm = mf->getTarget();<br>
CoalescerPair cp(*tm.getRegisterInfo());<br>
@@ -362,28 +361,32 @@ PBQPRAProblem *PBQPBuilderWithCoalescing<br>
}<br>
if (pregOpt < allowed.size()) {<br>
++pregOpt; // +1 to account for spill option.<br>
- PBQP::Graph::NodeId node = p->getNodeForVReg(src);<br>
- addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);<br>
+ PBQPRAGraph::NodeId node = p->getNodeForVReg(src);<br>
+ llvm::dbgs() << "Reading node costs for node " << node << "\n";<br>
+ llvm::dbgs() << "Source node: " << &g.getNodeCosts(node) << "\n";<br>
+ PBQP::Vector newCosts(g.getNodeCosts(node));<br>
+ addPhysRegCoalesce(newCosts, pregOpt, cBenefit);<br>
+ g.setNodeCosts(node, newCosts);<br>
}<br>
} else {<br>
const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);<br>
const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);<br>
- PBQP::Graph::NodeId node1 = p->getNodeForVReg(dst);<br>
- PBQP::Graph::NodeId node2 = p->getNodeForVReg(src);<br>
- PBQP::Graph::EdgeId edge = g.findEdge(node1, node2);<br>
+ PBQPRAGraph::NodeId node1 = p->getNodeForVReg(dst);<br>
+ PBQPRAGraph::NodeId node2 = p->getNodeForVReg(src);<br>
+ PBQPRAGraph::EdgeId edge = g.findEdge(node1, node2);<br>
if (edge == g.invalidEdgeId()) {<br>
- edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,<br>
- allowed2->size() + 1,<br>
- 0));<br>
+ PBQP::Matrix costs(allowed1->size() + 1, allowed2->size() + 1, 0);<br>
+ addVirtRegCoalesce(costs, *allowed1, *allowed2, cBenefit);<br>
+ g.addEdge(node1, node2, costs);<br>
} else {<br>
- if (g.getEdgeNode1(edge) == node2) {<br>
+ if (g.getEdgeNode1Id(edge) == node2) {<br>
std::swap(node1, node2);<br>
std::swap(allowed1, allowed2);<br>
}<br>
+ PBQP::Matrix costs(g.getEdgeCosts(edge));<br>
+ addVirtRegCoalesce(costs, *allowed1, *allowed2, cBenefit);<br>
+ g.setEdgeCosts(edge, costs);<br>
}<br>
-<br>
- addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,<br>
- cBenefit);<br>
}<br>
}<br>
}<br>
@@ -471,14 +474,12 @@ bool RegAllocPBQP::mapPBQPToRegAlloc(con<br>
// Clear the existing allocation.<br>
vrm->clearAllVirt();<br>
<br>
- const PBQP::Graph &g = problem.getGraph();<br>
+ const PBQPRAGraph &g = problem.getGraph();<br>
// Iterate over the nodes mapping the PBQP solution to a register<br>
// assignment.<br>
- for (PBQP::Graph::NodeItr nodeItr = g.nodesBegin(),<br>
- nodeEnd = g.nodesEnd();<br>
- nodeItr != nodeEnd; ++nodeItr) {<br>
- unsigned vreg = problem.getVRegForNode(*nodeItr);<br>
- unsigned alloc = solution.getSelection(*nodeItr);<br>
+ for (auto NId : g.nodeIds()) {<br>
+ unsigned vreg = problem.getVRegForNode(NId);<br>
+ unsigned alloc = solution.getSelection(NId);<br>
<br>
if (problem.isPRegOption(vreg, alloc)) {<br>
unsigned preg = problem.getPRegForOption(vreg, alloc);<br>
@@ -603,8 +604,7 @@ bool RegAllocPBQP::runOnMachineFunction(<br>
#endif<br>
<br>
PBQP::Solution solution =<br>
- PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(<br>
- problem->getGraph());<br>
+ PBQP::RegAlloc::solve(problem->getGraph());<br>
<br>
pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);<br>
<br>
<br>
<br>
_______________________________________________<br>
llvm-commits mailing list<br>
<a href="mailto:llvm-commits@cs.uiuc.edu">llvm-commits@cs.uiuc.edu</a><br>
<a href="http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits" target="_blank">http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits</a><br>
</blockquote></div><br></div></div>