]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/CodeGen/RegAllocPBQP.cpp
remove extra semicolon
[opencl/llvm.git] / lib / CodeGen / RegAllocPBQP.cpp
1 //===------ RegAllocPBQP.cpp ---- PBQP Register Allocator -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a Partitioned Boolean Quadratic Programming (PBQP) based
11 // register allocator for LLVM. This allocator works by constructing a PBQP
12 // problem representing the register allocation problem under consideration,
13 // solving this using a PBQP solver, and mapping the solution back to a
14 // register assignment. If any variables are selected for spilling then spill
15 // code is inserted and the process repeated.
16 //
17 // The PBQP solver (pbqp.c) provided for this allocator uses a heuristic tuned
18 // for register allocation. For more information on PBQP for register
19 // allocation, see the following papers:
20 //
21 //   (1) Hames, L. and Scholz, B. 2006. Nearly optimal register allocation with
22 //   PBQP. In Proceedings of the 7th Joint Modular Languages Conference
23 //   (JMLC'06). LNCS, vol. 4228. Springer, New York, NY, USA. 346-361.
24 //
25 //   (2) Scholz, B., Eckstein, E. 2002. Register allocation for irregular
26 //   architectures. In Proceedings of the Joint Conference on Languages,
27 //   Compilers and Tools for Embedded Systems (LCTES'02), ACM Press, New York,
28 //   NY, USA, 139-148.
29 //
30 //===----------------------------------------------------------------------===//
32 #include "llvm/CodeGen/RegAllocPBQP.h"
33 #include "RegisterCoalescer.h"
34 #include "Spiller.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/CodeGen/CalcSpillWeights.h"
37 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
38 #include "llvm/CodeGen/LiveRangeEdit.h"
39 #include "llvm/CodeGen/LiveStackAnalysis.h"
40 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
41 #include "llvm/CodeGen/MachineDominators.h"
42 #include "llvm/CodeGen/MachineFunctionPass.h"
43 #include "llvm/CodeGen/MachineLoopInfo.h"
44 #include "llvm/CodeGen/MachineRegisterInfo.h"
45 #include "llvm/CodeGen/RegAllocRegistry.h"
46 #include "llvm/CodeGen/VirtRegMap.h"
47 #include "llvm/IR/Module.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/FileSystem.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Target/TargetInstrInfo.h"
52 #include "llvm/Target/TargetSubtargetInfo.h"
53 #include <limits>
54 #include <memory>
55 #include <queue>
56 #include <set>
57 #include <sstream>
58 #include <vector>
60 using namespace llvm;
62 #define DEBUG_TYPE "regalloc"
64 static RegisterRegAlloc
65 RegisterPBQPRepAlloc("pbqp", "PBQP register allocator",
66                        createDefaultPBQPRegisterAllocator);
68 static cl::opt<bool>
69 PBQPCoalescing("pbqp-coalescing",
70                 cl::desc("Attempt coalescing during PBQP register allocation."),
71                 cl::init(false), cl::Hidden);
73 #ifndef NDEBUG
74 static cl::opt<bool>
75 PBQPDumpGraphs("pbqp-dump-graphs",
76                cl::desc("Dump graphs for each function/round in the compilation unit."),
77                cl::init(false), cl::Hidden);
78 #endif
80 namespace {
82 ///
83 /// PBQP based allocators solve the register allocation problem by mapping
84 /// register allocation problems to Partitioned Boolean Quadratic
85 /// Programming problems.
86 class RegAllocPBQP : public MachineFunctionPass {
87 public:
89   static char ID;
91   /// Construct a PBQP register allocator.
92   RegAllocPBQP(char *cPassID = nullptr)
93       : MachineFunctionPass(ID), customPassID(cPassID) {
94     initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
95     initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
96     initializeLiveStacksPass(*PassRegistry::getPassRegistry());
97     initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
98   }
100   /// Return the pass name.
101   const char* getPassName() const override {
102     return "PBQP Register Allocator";
103   }
105   /// PBQP analysis usage.
106   void getAnalysisUsage(AnalysisUsage &au) const override;
108   /// Perform register allocation
109   bool runOnMachineFunction(MachineFunction &MF) override;
111 private:
113   typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
114   typedef std::vector<const LiveInterval*> Node2LIMap;
115   typedef std::vector<unsigned> AllowedSet;
116   typedef std::vector<AllowedSet> AllowedSetMap;
117   typedef std::pair<unsigned, unsigned> RegPair;
118   typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
119   typedef std::set<unsigned> RegSet;
121   char *customPassID;
123   RegSet VRegsToAlloc, EmptyIntervalVRegs;
125   /// \brief Finds the initial set of vreg intervals to allocate.
126   void findVRegIntervalsToAlloc(const MachineFunction &MF, LiveIntervals &LIS);
128   /// \brief Constructs an initial graph.
129   void initializeGraph(PBQPRAGraph &G);
131   /// \brief Given a solved PBQP problem maps this solution back to a register
132   /// assignment.
133   bool mapPBQPToRegAlloc(const PBQPRAGraph &G,
134                          const PBQP::Solution &Solution,
135                          VirtRegMap &VRM,
136                          Spiller &VRegSpiller);
138   /// \brief Postprocessing before final spilling. Sets basic block "live in"
139   /// variables.
140   void finalizeAlloc(MachineFunction &MF, LiveIntervals &LIS,
141                      VirtRegMap &VRM) const;
143 };
145 char RegAllocPBQP::ID = 0;
147 /// @brief Set spill costs for each node in the PBQP reg-alloc graph.
148 class SpillCosts : public PBQPRAConstraint {
149 public:
150   void apply(PBQPRAGraph &G) override {
151     LiveIntervals &LIS = G.getMetadata().LIS;
153     // A minimum spill costs, so that register constraints can can be set
154     // without normalization in the [0.0:MinSpillCost( interval.
155     const PBQP::PBQPNum MinSpillCost = 10.0;
157     for (auto NId : G.nodeIds()) {
158       PBQP::PBQPNum SpillCost =
159         LIS.getInterval(G.getNodeMetadata(NId).getVReg()).weight;
160       if (SpillCost == 0.0)
161         SpillCost = std::numeric_limits<PBQP::PBQPNum>::min();
162       else
163         SpillCost += MinSpillCost;
164       PBQPRAGraph::RawVector NodeCosts(G.getNodeCosts(NId));
165       NodeCosts[PBQP::RegAlloc::getSpillOptionIdx()] = SpillCost;
166       G.setNodeCosts(NId, std::move(NodeCosts));
167     }
168   }
169 };
171 /// @brief Add interference edges between overlapping vregs.
172 class Interference : public PBQPRAConstraint {
173 private:
175 private:
177   typedef const PBQP::RegAlloc::AllowedRegVector* AllowedRegVecPtr;
178   typedef std::pair<AllowedRegVecPtr, AllowedRegVecPtr> IMatrixKey;
179   typedef DenseMap<IMatrixKey, PBQPRAGraph::MatrixPtr> IMatrixCache;
181   // Holds (Interval, CurrentSegmentID, and NodeId). The first two are required
182   // for the fast interference graph construction algorithm. The last is there
183   // to save us from looking up node ids via the VRegToNode map in the graph
184   // metadata.
185   typedef std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId>
186     IntervalInfo;
188   static SlotIndex getStartPoint(const IntervalInfo &I) {
189     return std::get<0>(I)->segments[std::get<1>(I)].start;
190   }
192   static SlotIndex getEndPoint(const IntervalInfo &I) {
193     return std::get<0>(I)->segments[std::get<1>(I)].end;
194   }
196   static PBQP::GraphBase::NodeId getNodeId(const IntervalInfo &I) {
197     return std::get<2>(I);
198   }
200   static bool lowestStartPoint(const IntervalInfo &I1,
201                                const IntervalInfo &I2) {
202     // Condition reversed because priority queue has the *highest* element at
203     // the front, rather than the lowest.
204     return getStartPoint(I1) > getStartPoint(I2);
205   }
207   static bool lowestEndPoint(const IntervalInfo &I1,
208                              const IntervalInfo &I2) {
209     SlotIndex E1 = getEndPoint(I1);
210     SlotIndex E2 = getEndPoint(I2);
212     if (E1 < E2)
213       return true;
215     if (E1 > E2)
216       return false;
218     // If two intervals end at the same point, we need a way to break the tie or
219     // the set will assume they're actually equal and refuse to insert a
220     // "duplicate". Just compare the vregs - fast and guaranteed unique.
221     return std::get<0>(I1)->reg < std::get<0>(I2)->reg;
222   }
224   static bool isAtLastSegment(const IntervalInfo &I) {
225     return std::get<1>(I) == std::get<0>(I)->size() - 1;
226   }
228   static IntervalInfo nextSegment(const IntervalInfo &I) {
229     return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I));
230   }
232 public:
234   void apply(PBQPRAGraph &G) override {
235     // The following is loosely based on the linear scan algorithm introduced in
236     // "Linear Scan Register Allocation" by Poletto and Sarkar. This version
237     // isn't linear, because the size of the active set isn't bound by the
238     // number of registers, but rather the size of the largest clique in the
239     // graph. Still, we expect this to be better than N^2.
240     LiveIntervals &LIS = G.getMetadata().LIS;
242     // Interferenc matrices are incredibly regular - they're only a function of
243     // the allowed sets, so we cache them to avoid the overhead of constructing
244     // and uniquing them.
245     IMatrixCache C;
247     typedef std::set<IntervalInfo, decltype(&lowestEndPoint)> IntervalSet;
248     typedef std::priority_queue<IntervalInfo, std::vector<IntervalInfo>,
249                                 decltype(&lowestStartPoint)> IntervalQueue;
250     IntervalSet Active(lowestEndPoint);
251     IntervalQueue Inactive(lowestStartPoint);
253     // Start by building the inactive set.
254     for (auto NId : G.nodeIds()) {
255       unsigned VReg = G.getNodeMetadata(NId).getVReg();
256       LiveInterval &LI = LIS.getInterval(VReg);
257       assert(!LI.empty() && "PBQP graph contains node for empty interval");
258       Inactive.push(std::make_tuple(&LI, 0, NId));
259     }
261     while (!Inactive.empty()) {
262       // Tentatively grab the "next" interval - this choice may be overriden
263       // below.
264       IntervalInfo Cur = Inactive.top();
266       // Retire any active intervals that end before Cur starts.
267       IntervalSet::iterator RetireItr = Active.begin();
268       while (RetireItr != Active.end() &&
269              (getEndPoint(*RetireItr) <= getStartPoint(Cur))) {
270         // If this interval has subsequent segments, add the next one to the
271         // inactive list.
272         if (!isAtLastSegment(*RetireItr))
273           Inactive.push(nextSegment(*RetireItr));
275         ++RetireItr;
276       }
277       Active.erase(Active.begin(), RetireItr);
279       // One of the newly retired segments may actually start before the
280       // Cur segment, so re-grab the front of the inactive list.
281       Cur = Inactive.top();
282       Inactive.pop();
284       // At this point we know that Cur overlaps all active intervals. Add the
285       // interference edges.
286       PBQP::GraphBase::NodeId NId = getNodeId(Cur);
287       for (const auto &A : Active) {
288         PBQP::GraphBase::NodeId MId = getNodeId(A);
290         // Check that we haven't already added this edge
291         // FIXME: findEdge is expensive in the worst case (O(max_clique(G))).
292         //        It might be better to replace this with a local bit-matrix.
293         if (G.findEdge(NId, MId) != PBQPRAGraph::invalidEdgeId())
294           continue;
296         // This is a new edge - add it to the graph.
297         createInterferenceEdge(G, NId, MId, C);
298       }
300       // Finally, add Cur to the Active set.
301       Active.insert(Cur);
302     }
303   }
305 private:
307   void createInterferenceEdge(PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
308                               PBQPRAGraph::NodeId MId, IMatrixCache &C) {
310     const TargetRegisterInfo &TRI =
311       *G.getMetadata().MF.getTarget().getSubtargetImpl()->getRegisterInfo();
313     const auto &NRegs = G.getNodeMetadata(NId).getAllowedRegs();
314     const auto &MRegs = G.getNodeMetadata(MId).getAllowedRegs();
316     // Try looking the edge costs up in the IMatrixCache first.
317     IMatrixKey K(&NRegs, &MRegs);
318     IMatrixCache::iterator I = C.find(K);
319     if (I != C.end()) {
320       G.addEdgeBypassingCostAllocator(NId, MId, I->second);
321       return;
322     }
324     PBQPRAGraph::RawMatrix M(NRegs.size() + 1, MRegs.size() + 1, 0);
325     for (unsigned I = 0; I != NRegs.size(); ++I) {
326       unsigned PRegN = NRegs[I];
327       for (unsigned J = 0; J != MRegs.size(); ++J) {
328         unsigned PRegM = MRegs[J];
329         if (TRI.regsOverlap(PRegN, PRegM))
330           M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
331       }
332     }
334     PBQPRAGraph::EdgeId EId = G.addEdge(NId, MId, std::move(M));
335     C[K] = G.getEdgeCostsPtr(EId);
336   }
337 };
340 class Coalescing : public PBQPRAConstraint {
341 public:
342   void apply(PBQPRAGraph &G) override {
343     MachineFunction &MF = G.getMetadata().MF;
344     MachineBlockFrequencyInfo &MBFI = G.getMetadata().MBFI;
345     CoalescerPair CP(*MF.getTarget().getSubtargetImpl()->getRegisterInfo());
347     // Scan the machine function and add a coalescing cost whenever CoalescerPair
348     // gives the Ok.
349     for (const auto &MBB : MF) {
350       for (const auto &MI : MBB) {
352         // Skip not-coalescable or already coalesced copies.
353         if (!CP.setRegisters(&MI) || CP.getSrcReg() == CP.getDstReg())
354           continue;
356         unsigned DstReg = CP.getDstReg();
357         unsigned SrcReg = CP.getSrcReg();
359         const float Scale = 1.0f / MBFI.getEntryFreq();
360         PBQP::PBQPNum CBenefit = MBFI.getBlockFreq(&MBB).getFrequency() * Scale;
362         if (CP.isPhys()) {
363           if (!MF.getRegInfo().isAllocatable(DstReg))
364             continue;
366           PBQPRAGraph::NodeId NId = G.getMetadata().getNodeIdForVReg(SrcReg);
368           const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed =
369             G.getNodeMetadata(NId).getAllowedRegs();
371           unsigned PRegOpt = 0;
372           while (PRegOpt < Allowed.size() && Allowed[PRegOpt] != DstReg)
373             ++PRegOpt;
375           if (PRegOpt < Allowed.size()) {
376             PBQPRAGraph::RawVector NewCosts(G.getNodeCosts(NId));
377             NewCosts[PRegOpt + 1] -= CBenefit;
378             G.setNodeCosts(NId, std::move(NewCosts));
379           }
380         } else {
381           PBQPRAGraph::NodeId N1Id = G.getMetadata().getNodeIdForVReg(DstReg);
382           PBQPRAGraph::NodeId N2Id = G.getMetadata().getNodeIdForVReg(SrcReg);
383           const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed1 =
384             &G.getNodeMetadata(N1Id).getAllowedRegs();
385           const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed2 =
386             &G.getNodeMetadata(N2Id).getAllowedRegs();
388           PBQPRAGraph::EdgeId EId = G.findEdge(N1Id, N2Id);
389           if (EId == G.invalidEdgeId()) {
390             PBQPRAGraph::RawMatrix Costs(Allowed1->size() + 1,
391                                          Allowed2->size() + 1, 0);
392             addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
393             G.addEdge(N1Id, N2Id, std::move(Costs));
394           } else {
395             if (G.getEdgeNode1Id(EId) == N2Id) {
396               std::swap(N1Id, N2Id);
397               std::swap(Allowed1, Allowed2);
398             }
399             PBQPRAGraph::RawMatrix Costs(G.getEdgeCosts(EId));
400             addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
401             G.setEdgeCosts(EId, std::move(Costs));
402           }
403         }
404       }
405     }
406   }
408 private:
410   void addVirtRegCoalesce(
411                     PBQPRAGraph::RawMatrix &CostMat,
412                     const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed1,
413                     const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed2,
414                     PBQP::PBQPNum Benefit) {
415     assert(CostMat.getRows() == Allowed1.size() + 1 && "Size mismatch.");
416     assert(CostMat.getCols() == Allowed2.size() + 1 && "Size mismatch.");
417     for (unsigned I = 0; I != Allowed1.size(); ++I) {
418       unsigned PReg1 = Allowed1[I];
419       for (unsigned J = 0; J != Allowed2.size(); ++J) {
420         unsigned PReg2 = Allowed2[J];
421         if (PReg1 == PReg2)
422           CostMat[I + 1][J + 1] -= Benefit;
423       }
424     }
425   }
427 };
429 } // End anonymous namespace.
431 // Out-of-line destructor/anchor for PBQPRAConstraint.
432 PBQPRAConstraint::~PBQPRAConstraint() {}
433 void PBQPRAConstraint::anchor() {}
434 void PBQPRAConstraintList::anchor() {}
436 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
437   au.setPreservesCFG();
438   au.addRequired<AliasAnalysis>();
439   au.addPreserved<AliasAnalysis>();
440   au.addRequired<SlotIndexes>();
441   au.addPreserved<SlotIndexes>();
442   au.addRequired<LiveIntervals>();
443   au.addPreserved<LiveIntervals>();
444   //au.addRequiredID(SplitCriticalEdgesID);
445   if (customPassID)
446     au.addRequiredID(*customPassID);
447   au.addRequired<LiveStacks>();
448   au.addPreserved<LiveStacks>();
449   au.addRequired<MachineBlockFrequencyInfo>();
450   au.addPreserved<MachineBlockFrequencyInfo>();
451   au.addRequired<MachineLoopInfo>();
452   au.addPreserved<MachineLoopInfo>();
453   au.addRequired<MachineDominatorTree>();
454   au.addPreserved<MachineDominatorTree>();
455   au.addRequired<VirtRegMap>();
456   au.addPreserved<VirtRegMap>();
457   MachineFunctionPass::getAnalysisUsage(au);
460 void RegAllocPBQP::findVRegIntervalsToAlloc(const MachineFunction &MF,
461                                             LiveIntervals &LIS) {
462   const MachineRegisterInfo &MRI = MF.getRegInfo();
464   // Iterate over all live ranges.
465   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
466     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
467     if (MRI.reg_nodbg_empty(Reg))
468       continue;
469     LiveInterval &LI = LIS.getInterval(Reg);
471     // If this live interval is non-empty we will use pbqp to allocate it.
472     // Empty intervals we allocate in a simple post-processing stage in
473     // finalizeAlloc.
474     if (!LI.empty()) {
475       VRegsToAlloc.insert(LI.reg);
476     } else {
477       EmptyIntervalVRegs.insert(LI.reg);
478     }
479   }
482 static bool isACalleeSavedRegister(unsigned reg, const TargetRegisterInfo &TRI,
483                                    const MachineFunction &MF) {
484   const MCPhysReg *CSR = TRI.getCalleeSavedRegs(&MF);
485   for (unsigned i = 0; CSR[i] != 0; ++i)
486     if (TRI.regsOverlap(reg, CSR[i]))
487       return true;
488   return false;
491 void RegAllocPBQP::initializeGraph(PBQPRAGraph &G) {
492   MachineFunction &MF = G.getMetadata().MF;
494   LiveIntervals &LIS = G.getMetadata().LIS;
495   const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
496   const TargetRegisterInfo &TRI =
497     *G.getMetadata().MF.getTarget().getSubtargetImpl()->getRegisterInfo();
499   for (auto VReg : VRegsToAlloc) {
500     const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
501     LiveInterval &VRegLI = LIS.getInterval(VReg);
503     // Record any overlaps with regmask operands.
504     BitVector RegMaskOverlaps;
505     LIS.checkRegMaskInterference(VRegLI, RegMaskOverlaps);
507     // Compute an initial allowed set for the current vreg.
508     std::vector<unsigned> VRegAllowed;
509     ArrayRef<MCPhysReg> RawPRegOrder = TRC->getRawAllocationOrder(MF);
510     for (unsigned I = 0; I != RawPRegOrder.size(); ++I) {
511       unsigned PReg = RawPRegOrder[I];
512       if (MRI.isReserved(PReg))
513         continue;
515       // vregLI crosses a regmask operand that clobbers preg.
516       if (!RegMaskOverlaps.empty() && !RegMaskOverlaps.test(PReg))
517         continue;
519       // vregLI overlaps fixed regunit interference.
520       bool Interference = false;
521       for (MCRegUnitIterator Units(PReg, &TRI); Units.isValid(); ++Units) {
522         if (VRegLI.overlaps(LIS.getRegUnit(*Units))) {
523           Interference = true;
524           break;
525         }
526       }
527       if (Interference)
528         continue;
530       // preg is usable for this virtual register.
531       VRegAllowed.push_back(PReg);
532     }
534     PBQPRAGraph::RawVector NodeCosts(VRegAllowed.size() + 1, 0);
536     // Tweak cost of callee saved registers, as using then force spilling and
537     // restoring them. This would only happen in the prologue / epilogue though.
538     for (unsigned i = 0; i != VRegAllowed.size(); ++i)
539       if (isACalleeSavedRegister(VRegAllowed[i], TRI, MF))
540         NodeCosts[1 + i] += 1.0;
542     PBQPRAGraph::NodeId NId = G.addNode(std::move(NodeCosts));
543     G.getNodeMetadata(NId).setVReg(VReg);
544     G.getNodeMetadata(NId).setAllowedRegs(
545       G.getMetadata().getAllowedRegs(std::move(VRegAllowed)));
546     G.getMetadata().setNodeIdForVReg(VReg, NId);
547   }
550 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAGraph &G,
551                                      const PBQP::Solution &Solution,
552                                      VirtRegMap &VRM,
553                                      Spiller &VRegSpiller) {
554   MachineFunction &MF = G.getMetadata().MF;
555   LiveIntervals &LIS = G.getMetadata().LIS;
556   const TargetRegisterInfo &TRI =
557     *MF.getTarget().getSubtargetImpl()->getRegisterInfo();
558   (void)TRI;
560   // Set to true if we have any spills
561   bool AnotherRoundNeeded = false;
563   // Clear the existing allocation.
564   VRM.clearAllVirt();
566   // Iterate over the nodes mapping the PBQP solution to a register
567   // assignment.
568   for (auto NId : G.nodeIds()) {
569     unsigned VReg = G.getNodeMetadata(NId).getVReg();
570     unsigned AllocOption = Solution.getSelection(NId);
572     if (AllocOption != PBQP::RegAlloc::getSpillOptionIdx()) {
573       unsigned PReg = G.getNodeMetadata(NId).getAllowedRegs()[AllocOption - 1];
574       DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> "
575             << TRI.getName(PReg) << "\n");
576       assert(PReg != 0 && "Invalid preg selected.");
577       VRM.assignVirt2Phys(VReg, PReg);
578     } else {
579       VRegsToAlloc.erase(VReg);
580       SmallVector<unsigned, 8> NewSpills;
581       LiveRangeEdit LRE(&LIS.getInterval(VReg), NewSpills, MF, LIS, &VRM);
582       VRegSpiller.spill(LRE);
584       DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> SPILLED (Cost: "
585                    << LRE.getParent().weight << ", New vregs: ");
587       // Copy any newly inserted live intervals into the list of regs to
588       // allocate.
589       for (LiveRangeEdit::iterator I = LRE.begin(), E = LRE.end();
590            I != E; ++I) {
591         LiveInterval &LI = LIS.getInterval(*I);
592         assert(!LI.empty() && "Empty spill range.");
593         DEBUG(dbgs() << PrintReg(LI.reg, &TRI) << " ");
594         VRegsToAlloc.insert(LI.reg);
595       }
597       DEBUG(dbgs() << ")\n");
599       // We need another round if spill intervals were added.
600       AnotherRoundNeeded |= !LRE.empty();
601     }
602   }
604   return !AnotherRoundNeeded;
607 void RegAllocPBQP::finalizeAlloc(MachineFunction &MF,
608                                  LiveIntervals &LIS,
609                                  VirtRegMap &VRM) const {
610   MachineRegisterInfo &MRI = MF.getRegInfo();
612   // First allocate registers for the empty intervals.
613   for (RegSet::const_iterator
614          I = EmptyIntervalVRegs.begin(), E = EmptyIntervalVRegs.end();
615          I != E; ++I) {
616     LiveInterval &LI = LIS.getInterval(*I);
618     unsigned PReg = MRI.getSimpleHint(LI.reg);
620     if (PReg == 0) {
621       const TargetRegisterClass &RC = *MRI.getRegClass(LI.reg);
622       PReg = RC.getRawAllocationOrder(MF).front();
623     }
625     VRM.assignVirt2Phys(LI.reg, PReg);
626   }
629 static inline float normalizePBQPSpillWeight(float UseDefFreq, unsigned Size,
630                                          unsigned NumInstr) {
631   // All intervals have a spill weight that is mostly proportional to the number
632   // of uses, with uses in loops having a bigger weight.
633   return NumInstr * normalizeSpillWeight(UseDefFreq, Size, 1);
636 bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
637   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
638   MachineBlockFrequencyInfo &MBFI =
639     getAnalysis<MachineBlockFrequencyInfo>();
641   calculateSpillWeightsAndHints(LIS, MF, getAnalysis<MachineLoopInfo>(), MBFI,
642                                 normalizePBQPSpillWeight);
644   VirtRegMap &VRM = getAnalysis<VirtRegMap>();
646   std::unique_ptr<Spiller> VRegSpiller(createInlineSpiller(*this, MF, VRM));
648   MF.getRegInfo().freezeReservedRegs(MF);
650   DEBUG(dbgs() << "PBQP Register Allocating for " << MF.getName() << "\n");
652   // Allocator main loop:
653   //
654   // * Map current regalloc problem to a PBQP problem
655   // * Solve the PBQP problem
656   // * Map the solution back to a register allocation
657   // * Spill if necessary
658   //
659   // This process is continued till no more spills are generated.
661   // Find the vreg intervals in need of allocation.
662   findVRegIntervalsToAlloc(MF, LIS);
664 #ifndef NDEBUG
665   const Function &F = *MF.getFunction();
666   std::string FullyQualifiedName =
667     F.getParent()->getModuleIdentifier() + "." + F.getName().str();
668 #endif
670   // If there are non-empty intervals allocate them using pbqp.
671   if (!VRegsToAlloc.empty()) {
673     const TargetSubtargetInfo &Subtarget = *MF.getTarget().getSubtargetImpl();
674     std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
675       llvm::make_unique<PBQPRAConstraintList>();
676     ConstraintsRoot->addConstraint(llvm::make_unique<SpillCosts>());
677     ConstraintsRoot->addConstraint(llvm::make_unique<Interference>());
678     if (PBQPCoalescing)
679       ConstraintsRoot->addConstraint(llvm::make_unique<Coalescing>());
680     ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints());
682     bool PBQPAllocComplete = false;
683     unsigned Round = 0;
685     while (!PBQPAllocComplete) {
686       DEBUG(dbgs() << "  PBQP Regalloc round " << Round << ":\n");
688       PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI));
689       initializeGraph(G);
690       ConstraintsRoot->apply(G);
692 #ifndef NDEBUG
693       if (PBQPDumpGraphs) {
694         std::ostringstream RS;
695         RS << Round;
696         std::string GraphFileName = FullyQualifiedName + "." + RS.str() +
697                                     ".pbqpgraph";
698         std::error_code EC;
699         raw_fd_ostream OS(GraphFileName, EC, sys::fs::F_Text);
700         DEBUG(dbgs() << "Dumping graph for round " << Round << " to \""
701               << GraphFileName << "\"\n");
702         G.dumpToStream(OS);
703       }
704 #endif
706       PBQP::Solution Solution = PBQP::RegAlloc::solve(G);
707       PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
708       ++Round;
709     }
710   }
712   // Finalise allocation, allocate empty ranges.
713   finalizeAlloc(MF, LIS, VRM);
714   VRegsToAlloc.clear();
715   EmptyIntervalVRegs.clear();
717   DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << VRM << "\n");
719   return true;
722 FunctionPass *llvm::createPBQPRegisterAllocator(char *customPassID) {
723   return new RegAllocPBQP(customPassID);
726 FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
727   return createPBQPRegisterAllocator();
730 #undef DEBUG_TYPE