RegAllocPBQP.cpp revision 233fd9cea04468d71ae44031df3f2c8d1c3299a7
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//===----------------------------------------------------------------------===//
31
32#define DEBUG_TYPE "regalloc"
33
34#include "PBQP/HeuristicSolver.h"
35#include "PBQP/SimpleGraph.h"
36#include "PBQP/Heuristics/Briggs.h"
37#include "VirtRegMap.h"
38#include "VirtRegRewriter.h"
39#include "llvm/CodeGen/LiveIntervalAnalysis.h"
40#include "llvm/CodeGen/LiveStackAnalysis.h"
41#include "llvm/CodeGen/MachineFunctionPass.h"
42#include "llvm/CodeGen/MachineLoopInfo.h"
43#include "llvm/CodeGen/MachineRegisterInfo.h"
44#include "llvm/CodeGen/RegAllocRegistry.h"
45#include "llvm/CodeGen/RegisterCoalescer.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/raw_ostream.h"
48#include "llvm/Target/TargetInstrInfo.h"
49#include "llvm/Target/TargetMachine.h"
50#include <limits>
51#include <map>
52#include <memory>
53#include <set>
54#include <vector>
55
56using namespace llvm;
57
58static RegisterRegAlloc
59registerPBQPRepAlloc("pbqp", "PBQP register allocator.",
60                      llvm::createPBQPRegisterAllocator);
61
62namespace {
63
64  ///
65  /// PBQP based allocators solve the register allocation problem by mapping
66  /// register allocation problems to Partitioned Boolean Quadratic
67  /// Programming problems.
68  class VISIBILITY_HIDDEN PBQPRegAlloc : public MachineFunctionPass {
69  public:
70
71    static char ID;
72
73    /// Construct a PBQP register allocator.
74    PBQPRegAlloc() : MachineFunctionPass(&ID) {}
75
76    /// Return the pass name.
77    virtual const char* getPassName() const {
78      return "PBQP Register Allocator";
79    }
80
81    /// PBQP analysis usage.
82    virtual void getAnalysisUsage(AnalysisUsage &au) const {
83      au.addRequired<LiveIntervals>();
84      //au.addRequiredID(SplitCriticalEdgesID);
85      au.addRequired<RegisterCoalescer>();
86      au.addRequired<LiveStacks>();
87      au.addPreserved<LiveStacks>();
88      au.addRequired<MachineLoopInfo>();
89      au.addPreserved<MachineLoopInfo>();
90      au.addRequired<VirtRegMap>();
91      MachineFunctionPass::getAnalysisUsage(au);
92    }
93
94    /// Perform register allocation
95    virtual bool runOnMachineFunction(MachineFunction &MF);
96
97  private:
98    typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
99    typedef std::vector<const LiveInterval*> Node2LIMap;
100    typedef std::vector<unsigned> AllowedSet;
101    typedef std::vector<AllowedSet> AllowedSetMap;
102    typedef std::set<unsigned> RegSet;
103    typedef std::pair<unsigned, unsigned> RegPair;
104    typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
105
106    typedef std::set<LiveInterval*> LiveIntervalSet;
107
108    MachineFunction *mf;
109    const TargetMachine *tm;
110    const TargetRegisterInfo *tri;
111    const TargetInstrInfo *tii;
112    const MachineLoopInfo *loopInfo;
113    MachineRegisterInfo *mri;
114
115    LiveIntervals *lis;
116    LiveStacks *lss;
117    VirtRegMap *vrm;
118
119    LI2NodeMap li2Node;
120    Node2LIMap node2LI;
121    AllowedSetMap allowedSets;
122    LiveIntervalSet vregIntervalsToAlloc,
123                    emptyVRegIntervals;
124
125
126    /// Builds a PBQP cost vector.
127    template <typename RegContainer>
128    PBQP::Vector buildCostVector(unsigned vReg,
129                                 const RegContainer &allowed,
130                                 const CoalesceMap &cealesces,
131                                 PBQP::PBQPNum spillCost) const;
132
133    /// \brief Builds a PBQP interference matrix.
134    ///
135    /// @return Either a pointer to a non-zero PBQP matrix representing the
136    ///         allocation option costs, or a null pointer for a zero matrix.
137    ///
138    /// Expects allowed sets for two interfering LiveIntervals. These allowed
139    /// sets should contain only allocable registers from the LiveInterval's
140    /// register class, with any interfering pre-colored registers removed.
141    template <typename RegContainer>
142    PBQP::Matrix* buildInterferenceMatrix(const RegContainer &allowed1,
143                                          const RegContainer &allowed2) const;
144
145    ///
146    /// Expects allowed sets for two potentially coalescable LiveIntervals,
147    /// and an estimated benefit due to coalescing. The allowed sets should
148    /// contain only allocable registers from the LiveInterval's register
149    /// classes, with any interfering pre-colored registers removed.
150    template <typename RegContainer>
151    PBQP::Matrix* buildCoalescingMatrix(const RegContainer &allowed1,
152                                        const RegContainer &allowed2,
153                                        PBQP::PBQPNum cBenefit) const;
154
155    /// \brief Finds coalescing opportunities and returns them as a map.
156    ///
157    /// Any entries in the map are guaranteed coalescable, even if their
158    /// corresponding live intervals overlap.
159    CoalesceMap findCoalesces();
160
161    /// \brief Finds the initial set of vreg intervals to allocate.
162    void findVRegIntervalsToAlloc();
163
164    /// \brief Constructs a PBQP problem representation of the register
165    /// allocation problem for this function.
166    ///
167    /// @return a PBQP solver object for the register allocation problem.
168    PBQP::SimpleGraph constructPBQPProblem();
169
170    /// \brief Adds a stack interval if the given live interval has been
171    /// spilled. Used to support stack slot coloring.
172    void addStackInterval(const LiveInterval *spilled,MachineRegisterInfo* mri);
173
174    /// \brief Given a solved PBQP problem maps this solution back to a register
175    /// assignment.
176    bool mapPBQPToRegAlloc(const PBQP::Solution &solution);
177
178    /// \brief Postprocessing before final spilling. Sets basic block "live in"
179    /// variables.
180    void finalizeAlloc() const;
181
182  };
183
184  char PBQPRegAlloc::ID = 0;
185}
186
187
188template <typename RegContainer>
189PBQP::Vector PBQPRegAlloc::buildCostVector(unsigned vReg,
190                                           const RegContainer &allowed,
191                                           const CoalesceMap &coalesces,
192                                           PBQP::PBQPNum spillCost) const {
193
194  typedef typename RegContainer::const_iterator AllowedItr;
195
196  // Allocate vector. Additional element (0th) used for spill option
197  PBQP::Vector v(allowed.size() + 1, 0);
198
199  v[0] = spillCost;
200
201  // Iterate over the allowed registers inserting coalesce benefits if there
202  // are any.
203  unsigned ai = 0;
204  for (AllowedItr itr = allowed.begin(), end = allowed.end();
205       itr != end; ++itr, ++ai) {
206
207    unsigned pReg = *itr;
208
209    CoalesceMap::const_iterator cmItr =
210      coalesces.find(RegPair(vReg, pReg));
211
212    // No coalesce - on to the next preg.
213    if (cmItr == coalesces.end())
214      continue;
215
216    // We have a coalesce - insert the benefit.
217    v[ai + 1] = -cmItr->second;
218  }
219
220  return v;
221}
222
223template <typename RegContainer>
224PBQP::Matrix* PBQPRegAlloc::buildInterferenceMatrix(
225      const RegContainer &allowed1, const RegContainer &allowed2) const {
226
227  typedef typename RegContainer::const_iterator RegContainerIterator;
228
229  // Construct a PBQP matrix representing the cost of allocation options. The
230  // rows and columns correspond to the allocation options for the two live
231  // intervals.  Elements will be infinite where corresponding registers alias,
232  // since we cannot allocate aliasing registers to interfering live intervals.
233  // All other elements (non-aliasing combinations) will have zero cost. Note
234  // that the spill option (element 0,0) has zero cost, since we can allocate
235  // both intervals to memory safely (the cost for each individual allocation
236  // to memory is accounted for by the cost vectors for each live interval).
237  PBQP::Matrix *m =
238    new PBQP::Matrix(allowed1.size() + 1, allowed2.size() + 1, 0);
239
240  // Assume this is a zero matrix until proven otherwise.  Zero matrices occur
241  // between interfering live ranges with non-overlapping register sets (e.g.
242  // non-overlapping reg classes, or disjoint sets of allowed regs within the
243  // same class). The term "overlapping" is used advisedly: sets which do not
244  // intersect, but contain registers which alias, will have non-zero matrices.
245  // We optimize zero matrices away to improve solver speed.
246  bool isZeroMatrix = true;
247
248
249  // Row index. Starts at 1, since the 0th row is for the spill option, which
250  // is always zero.
251  unsigned ri = 1;
252
253  // Iterate over allowed sets, insert infinities where required.
254  for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
255       a1Itr != a1End; ++a1Itr) {
256
257    // Column index, starts at 1 as for row index.
258    unsigned ci = 1;
259    unsigned reg1 = *a1Itr;
260
261    for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
262         a2Itr != a2End; ++a2Itr) {
263
264      unsigned reg2 = *a2Itr;
265
266      // If the row/column regs are identical or alias insert an infinity.
267      if ((reg1 == reg2) || tri->areAliases(reg1, reg2)) {
268        (*m)[ri][ci] = std::numeric_limits<PBQP::PBQPNum>::infinity();
269        isZeroMatrix = false;
270      }
271
272      ++ci;
273    }
274
275    ++ri;
276  }
277
278  // If this turns out to be a zero matrix...
279  if (isZeroMatrix) {
280    // free it and return null.
281    delete m;
282    return 0;
283  }
284
285  // ...otherwise return the cost matrix.
286  return m;
287}
288
289template <typename RegContainer>
290PBQP::Matrix* PBQPRegAlloc::buildCoalescingMatrix(
291      const RegContainer &allowed1, const RegContainer &allowed2,
292      PBQP::PBQPNum cBenefit) const {
293
294  typedef typename RegContainer::const_iterator RegContainerIterator;
295
296  // Construct a PBQP Matrix representing the benefits of coalescing. As with
297  // interference matrices the rows and columns represent allowed registers
298  // for the LiveIntervals which are (potentially) to be coalesced. The amount
299  // -cBenefit will be placed in any element representing the same register
300  // for both intervals.
301  PBQP::Matrix *m =
302    new PBQP::Matrix(allowed1.size() + 1, allowed2.size() + 1, 0);
303
304  // Reset costs to zero.
305  m->reset(0);
306
307  // Assume the matrix is zero till proven otherwise. Zero matrices will be
308  // optimized away as in the interference case.
309  bool isZeroMatrix = true;
310
311  // Row index. Starts at 1, since the 0th row is for the spill option, which
312  // is always zero.
313  unsigned ri = 1;
314
315  // Iterate over the allowed sets, insert coalescing benefits where
316  // appropriate.
317  for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
318       a1Itr != a1End; ++a1Itr) {
319
320    // Column index, starts at 1 as for row index.
321    unsigned ci = 1;
322    unsigned reg1 = *a1Itr;
323
324    for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
325         a2Itr != a2End; ++a2Itr) {
326
327      // If the row and column represent the same register insert a beneficial
328      // cost to preference this allocation - it would allow us to eliminate a
329      // move instruction.
330      if (reg1 == *a2Itr) {
331        (*m)[ri][ci] = -cBenefit;
332        isZeroMatrix = false;
333      }
334
335      ++ci;
336    }
337
338    ++ri;
339  }
340
341  // If this turns out to be a zero matrix...
342  if (isZeroMatrix) {
343    // ...free it and return null.
344    delete m;
345    return 0;
346  }
347
348  return m;
349}
350
351PBQPRegAlloc::CoalesceMap PBQPRegAlloc::findCoalesces() {
352
353  typedef MachineFunction::const_iterator MFIterator;
354  typedef MachineBasicBlock::const_iterator MBBIterator;
355  typedef LiveInterval::const_vni_iterator VNIIterator;
356
357  CoalesceMap coalescesFound;
358
359  // To find coalesces we need to iterate over the function looking for
360  // copy instructions.
361  for (MFIterator bbItr = mf->begin(), bbEnd = mf->end();
362       bbItr != bbEnd; ++bbItr) {
363
364    const MachineBasicBlock *mbb = &*bbItr;
365
366    for (MBBIterator iItr = mbb->begin(), iEnd = mbb->end();
367         iItr != iEnd; ++iItr) {
368
369      const MachineInstr *instr = &*iItr;
370      unsigned srcReg, dstReg, srcSubReg, dstSubReg;
371
372      // If this isn't a copy then continue to the next instruction.
373      if (!tii->isMoveInstr(*instr, srcReg, dstReg, srcSubReg, dstSubReg))
374        continue;
375
376      // If the registers are already the same our job is nice and easy.
377      if (dstReg == srcReg)
378        continue;
379
380      bool srcRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(srcReg),
381           dstRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(dstReg);
382
383      // If both registers are physical then we can't coalesce.
384      if (srcRegIsPhysical && dstRegIsPhysical)
385        continue;
386
387      // If it's a copy that includes a virtual register but the source and
388      // destination classes differ then we can't coalesce, so continue with
389      // the next instruction.
390      const TargetRegisterClass *srcRegClass = srcRegIsPhysical ?
391          tri->getPhysicalRegisterRegClass(srcReg) : mri->getRegClass(srcReg);
392
393      const TargetRegisterClass *dstRegClass = dstRegIsPhysical ?
394          tri->getPhysicalRegisterRegClass(dstReg) : mri->getRegClass(dstReg);
395
396      if (srcRegClass != dstRegClass)
397        continue;
398
399      // We also need any physical regs to be allocable, coalescing with
400      // a non-allocable register is invalid.
401      if (srcRegIsPhysical) {
402        if (std::find(srcRegClass->allocation_order_begin(*mf),
403                      srcRegClass->allocation_order_end(*mf), srcReg) ==
404            srcRegClass->allocation_order_end(*mf))
405          continue;
406      }
407
408      if (dstRegIsPhysical) {
409        if (std::find(dstRegClass->allocation_order_begin(*mf),
410                      dstRegClass->allocation_order_end(*mf), dstReg) ==
411            dstRegClass->allocation_order_end(*mf))
412          continue;
413      }
414
415      // If we've made it here we have a copy with compatible register classes.
416      // We can probably coalesce, but we need to consider overlap.
417      const LiveInterval *srcLI = &lis->getInterval(srcReg),
418                         *dstLI = &lis->getInterval(dstReg);
419
420      if (srcLI->overlaps(*dstLI)) {
421        // Even in the case of an overlap we might still be able to coalesce,
422        // but we need to make sure that no definition of either range occurs
423        // while the other range is live.
424
425        // Otherwise start by assuming we're ok.
426        bool badDef = false;
427
428        // Test all defs of the source range.
429        for (VNIIterator
430               vniItr = srcLI->vni_begin(), vniEnd = srcLI->vni_end();
431               vniItr != vniEnd; ++vniItr) {
432
433          // If we find a def that kills the coalescing opportunity then
434          // record it and break from the loop.
435          if (dstLI->liveAt((*vniItr)->def)) {
436            badDef = true;
437            break;
438          }
439        }
440
441        // If we have a bad def give up, continue to the next instruction.
442        if (badDef)
443          continue;
444
445        // Otherwise test definitions of the destination range.
446        for (VNIIterator
447               vniItr = dstLI->vni_begin(), vniEnd = dstLI->vni_end();
448               vniItr != vniEnd; ++vniItr) {
449
450          // We want to make sure we skip the copy instruction itself.
451          if ((*vniItr)->getCopy() == instr)
452            continue;
453
454          if (srcLI->liveAt((*vniItr)->def)) {
455            badDef = true;
456            break;
457          }
458        }
459
460        // As before a bad def we give up and continue to the next instr.
461        if (badDef)
462          continue;
463      }
464
465      // If we make it to here then either the ranges didn't overlap, or they
466      // did, but none of their definitions would prevent us from coalescing.
467      // We're good to go with the coalesce.
468
469      float cBenefit = powf(10.0f, loopInfo->getLoopDepth(mbb)) / 5.0;
470
471      coalescesFound[RegPair(srcReg, dstReg)] = cBenefit;
472      coalescesFound[RegPair(dstReg, srcReg)] = cBenefit;
473    }
474
475  }
476
477  return coalescesFound;
478}
479
480void PBQPRegAlloc::findVRegIntervalsToAlloc() {
481
482  // Iterate over all live ranges.
483  for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
484       itr != end; ++itr) {
485
486    // Ignore physical ones.
487    if (TargetRegisterInfo::isPhysicalRegister(itr->first))
488      continue;
489
490    LiveInterval *li = itr->second;
491
492    // If this live interval is non-empty we will use pbqp to allocate it.
493    // Empty intervals we allocate in a simple post-processing stage in
494    // finalizeAlloc.
495    if (!li->empty()) {
496      vregIntervalsToAlloc.insert(li);
497    }
498    else {
499      emptyVRegIntervals.insert(li);
500    }
501  }
502}
503
504PBQP::SimpleGraph PBQPRegAlloc::constructPBQPProblem() {
505
506  typedef std::vector<const LiveInterval*> LIVector;
507  typedef std::vector<unsigned> RegVector;
508  typedef std::vector<PBQP::SimpleGraph::NodeIterator> NodeVector;
509
510  // This will store the physical intervals for easy reference.
511  LIVector physIntervals;
512
513  // Start by clearing the old node <-> live interval mappings & allowed sets
514  li2Node.clear();
515  node2LI.clear();
516  allowedSets.clear();
517
518  // Populate physIntervals, update preg use:
519  for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
520       itr != end; ++itr) {
521
522    if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
523      physIntervals.push_back(itr->second);
524      mri->setPhysRegUsed(itr->second->reg);
525    }
526  }
527
528  // Iterate over vreg intervals, construct live interval <-> node number
529  //  mappings.
530  for (LiveIntervalSet::const_iterator
531       itr = vregIntervalsToAlloc.begin(), end = vregIntervalsToAlloc.end();
532       itr != end; ++itr) {
533    const LiveInterval *li = *itr;
534
535    li2Node[li] = node2LI.size();
536    node2LI.push_back(li);
537  }
538
539  // Get the set of potential coalesces.
540  CoalesceMap coalesces;//(findCoalesces());
541
542  // Construct a PBQP solver for this problem
543  PBQP::SimpleGraph problem;
544  NodeVector problemNodes(vregIntervalsToAlloc.size());
545
546  // Resize allowedSets container appropriately.
547  allowedSets.resize(vregIntervalsToAlloc.size());
548
549  // Iterate over virtual register intervals to compute allowed sets...
550  for (unsigned node = 0; node < node2LI.size(); ++node) {
551
552    // Grab pointers to the interval and its register class.
553    const LiveInterval *li = node2LI[node];
554    const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
555
556    // Start by assuming all allocable registers in the class are allowed...
557    RegVector liAllowed(liRC->allocation_order_begin(*mf),
558                        liRC->allocation_order_end(*mf));
559
560    // Eliminate the physical registers which overlap with this range, along
561    // with all their aliases.
562    for (LIVector::iterator pItr = physIntervals.begin(),
563       pEnd = physIntervals.end(); pItr != pEnd; ++pItr) {
564
565      if (!li->overlaps(**pItr))
566        continue;
567
568      unsigned pReg = (*pItr)->reg;
569
570      // If we get here then the live intervals overlap, but we're still ok
571      // if they're coalescable.
572      if (coalesces.find(RegPair(li->reg, pReg)) != coalesces.end())
573        continue;
574
575      // If we get here then we have a genuine exclusion.
576
577      // Remove the overlapping reg...
578      RegVector::iterator eraseItr =
579        std::find(liAllowed.begin(), liAllowed.end(), pReg);
580
581      if (eraseItr != liAllowed.end())
582        liAllowed.erase(eraseItr);
583
584      const unsigned *aliasItr = tri->getAliasSet(pReg);
585
586      if (aliasItr != 0) {
587        // ...and its aliases.
588        for (; *aliasItr != 0; ++aliasItr) {
589          RegVector::iterator eraseItr =
590            std::find(liAllowed.begin(), liAllowed.end(), *aliasItr);
591
592          if (eraseItr != liAllowed.end()) {
593            liAllowed.erase(eraseItr);
594          }
595        }
596      }
597    }
598
599    // Copy the allowed set into a member vector for use when constructing cost
600    // vectors & matrices, and mapping PBQP solutions back to assignments.
601    allowedSets[node] = AllowedSet(liAllowed.begin(), liAllowed.end());
602
603    // Set the spill cost to the interval weight, or epsilon if the
604    // interval weight is zero
605    PBQP::PBQPNum spillCost = (li->weight != 0.0) ?
606        li->weight : std::numeric_limits<PBQP::PBQPNum>::min();
607
608    // Build a cost vector for this interval.
609    problemNodes[node] =
610      problem.addNode(
611        buildCostVector(li->reg, allowedSets[node], coalesces, spillCost));
612
613  }
614
615
616  // Now add the cost matrices...
617  for (unsigned node1 = 0; node1 < node2LI.size(); ++node1) {
618    const LiveInterval *li = node2LI[node1];
619
620    // Test for live range overlaps and insert interference matrices.
621    for (unsigned node2 = node1 + 1; node2 < node2LI.size(); ++node2) {
622      const LiveInterval *li2 = node2LI[node2];
623
624      CoalesceMap::const_iterator cmItr =
625        coalesces.find(RegPair(li->reg, li2->reg));
626
627      PBQP::Matrix *m = 0;
628
629      if (cmItr != coalesces.end()) {
630        m = buildCoalescingMatrix(allowedSets[node1], allowedSets[node2],
631                                  cmItr->second);
632      }
633      else if (li->overlaps(*li2)) {
634        m = buildInterferenceMatrix(allowedSets[node1], allowedSets[node2]);
635      }
636
637      if (m != 0) {
638        problem.addEdge(problemNodes[node1],
639                        problemNodes[node2],
640                        *m);
641
642        delete m;
643      }
644    }
645  }
646
647  problem.assignNodeIDs();
648
649  assert(problem.getNumNodes() == allowedSets.size());
650  for (unsigned i = 0; i < allowedSets.size(); ++i) {
651    assert(problem.getNodeItr(i) == problemNodes[i]);
652  }
653/*
654  std::cerr << "Allocating for " << problem.getNumNodes() << " nodes, "
655            << problem.getNumEdges() << " edges.\n";
656
657  problem.printDot(std::cerr);
658*/
659  // We're done, PBQP problem constructed - return it.
660  return problem;
661}
662
663void PBQPRegAlloc::addStackInterval(const LiveInterval *spilled,
664                                    MachineRegisterInfo* mri) {
665  int stackSlot = vrm->getStackSlot(spilled->reg);
666
667  if (stackSlot == VirtRegMap::NO_STACK_SLOT)
668    return;
669
670  const TargetRegisterClass *RC = mri->getRegClass(spilled->reg);
671  LiveInterval &stackInterval = lss->getOrCreateInterval(stackSlot, RC);
672
673  VNInfo *vni;
674  if (stackInterval.getNumValNums() != 0)
675    vni = stackInterval.getValNumInfo(0);
676  else
677    vni = stackInterval.getNextValue(0, 0, false, lss->getVNInfoAllocator());
678
679  LiveInterval &rhsInterval = lis->getInterval(spilled->reg);
680  stackInterval.MergeRangesInAsValue(rhsInterval, vni);
681}
682
683bool PBQPRegAlloc::mapPBQPToRegAlloc(const PBQP::Solution &solution) {
684
685  static unsigned round = 0;
686  (void) round;
687
688  // Set to true if we have any spills
689  bool anotherRoundNeeded = false;
690
691  // Clear the existing allocation.
692  vrm->clearAllVirt();
693
694  // Iterate over the nodes mapping the PBQP solution to a register assignment.
695  for (unsigned node = 0; node < node2LI.size(); ++node) {
696    unsigned virtReg = node2LI[node]->reg,
697             allocSelection = solution.getSelection(node);
698
699
700    // If the PBQP solution is non-zero it's a physical register...
701    if (allocSelection != 0) {
702      // Get the physical reg, subtracting 1 to account for the spill option.
703      unsigned physReg = allowedSets[node][allocSelection - 1];
704
705      DEBUG(errs() << "VREG " << virtReg << " -> "
706                   << tri->getName(physReg) << "\n");
707
708      assert(physReg != 0);
709
710      // Add to the virt reg map and update the used phys regs.
711      vrm->assignVirt2Phys(virtReg, physReg);
712    }
713    // ...Otherwise it's a spill.
714    else {
715
716      // Make sure we ignore this virtual reg on the next round
717      // of allocation
718      vregIntervalsToAlloc.erase(&lis->getInterval(virtReg));
719
720      // Insert spill ranges for this live range
721      const LiveInterval *spillInterval = node2LI[node];
722      double oldSpillWeight = spillInterval->weight;
723      SmallVector<LiveInterval*, 8> spillIs;
724      std::vector<LiveInterval*> newSpills =
725        lis->addIntervalsForSpills(*spillInterval, spillIs, loopInfo, *vrm);
726      addStackInterval(spillInterval, mri);
727
728      DEBUG(errs() << "VREG " << virtReg << " -> SPILLED (Cost: "
729                   << oldSpillWeight << ", New vregs: ");
730
731      // Copy any newly inserted live intervals into the list of regs to
732      // allocate.
733      for (std::vector<LiveInterval*>::const_iterator
734           itr = newSpills.begin(), end = newSpills.end();
735           itr != end; ++itr) {
736
737        assert(!(*itr)->empty() && "Empty spill range.");
738
739        DEBUG(errs() << (*itr)->reg << " ");
740
741        vregIntervalsToAlloc.insert(*itr);
742      }
743
744      DEBUG(errs() << ")\n");
745
746      // We need another round if spill intervals were added.
747      anotherRoundNeeded |= !newSpills.empty();
748    }
749  }
750
751  return !anotherRoundNeeded;
752}
753
754void PBQPRegAlloc::finalizeAlloc() const {
755  typedef LiveIntervals::iterator LIIterator;
756  typedef LiveInterval::Ranges::const_iterator LRIterator;
757
758  // First allocate registers for the empty intervals.
759  for (LiveIntervalSet::const_iterator
760	 itr = emptyVRegIntervals.begin(), end = emptyVRegIntervals.end();
761         itr != end; ++itr) {
762    LiveInterval *li = *itr;
763
764    unsigned physReg = vrm->getRegAllocPref(li->reg);
765
766    if (physReg == 0) {
767      const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
768      physReg = *liRC->allocation_order_begin(*mf);
769    }
770
771    vrm->assignVirt2Phys(li->reg, physReg);
772  }
773
774  // Finally iterate over the basic blocks to compute and set the live-in sets.
775  SmallVector<MachineBasicBlock*, 8> liveInMBBs;
776  MachineBasicBlock *entryMBB = &*mf->begin();
777
778  for (LIIterator liItr = lis->begin(), liEnd = lis->end();
779       liItr != liEnd; ++liItr) {
780
781    const LiveInterval *li = liItr->second;
782    unsigned reg = 0;
783
784    // Get the physical register for this interval
785    if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
786      reg = li->reg;
787    }
788    else if (vrm->isAssignedReg(li->reg)) {
789      reg = vrm->getPhys(li->reg);
790    }
791    else {
792      // Ranges which are assigned a stack slot only are ignored.
793      continue;
794    }
795
796    if (reg == 0) {
797      // Filter out zero regs - they're for intervals that were spilled.
798      continue;
799    }
800
801    // Iterate over the ranges of the current interval...
802    for (LRIterator lrItr = li->begin(), lrEnd = li->end();
803         lrItr != lrEnd; ++lrItr) {
804
805      // Find the set of basic blocks which this range is live into...
806      if (lis->findLiveInMBBs(lrItr->start, lrItr->end,  liveInMBBs)) {
807        // And add the physreg for this interval to their live-in sets.
808        for (unsigned i = 0; i < liveInMBBs.size(); ++i) {
809          if (liveInMBBs[i] != entryMBB) {
810            if (!liveInMBBs[i]->isLiveIn(reg)) {
811              liveInMBBs[i]->addLiveIn(reg);
812            }
813          }
814        }
815        liveInMBBs.clear();
816      }
817    }
818  }
819
820}
821
822bool PBQPRegAlloc::runOnMachineFunction(MachineFunction &MF) {
823
824  mf = &MF;
825  tm = &mf->getTarget();
826  tri = tm->getRegisterInfo();
827  tii = tm->getInstrInfo();
828  mri = &mf->getRegInfo();
829
830  lis = &getAnalysis<LiveIntervals>();
831  lss = &getAnalysis<LiveStacks>();
832  loopInfo = &getAnalysis<MachineLoopInfo>();
833
834  vrm = &getAnalysis<VirtRegMap>();
835
836  DEBUG(errs() << "PBQP2 Register Allocating for " << mf->getFunction()->getName() << "\n");
837
838  // Allocator main loop:
839  //
840  // * Map current regalloc problem to a PBQP problem
841  // * Solve the PBQP problem
842  // * Map the solution back to a register allocation
843  // * Spill if necessary
844  //
845  // This process is continued till no more spills are generated.
846
847  // Find the vreg intervals in need of allocation.
848  findVRegIntervalsToAlloc();
849
850  // If there aren't any then we're done here.
851  if (vregIntervalsToAlloc.empty() && emptyVRegIntervals.empty())
852    return true;
853
854  // If there are non-empty intervals allocate them using pbqp.
855  if (!vregIntervalsToAlloc.empty()) {
856
857    bool pbqpAllocComplete = false;
858    unsigned round = 0;
859
860    while (!pbqpAllocComplete) {
861      DEBUG(errs() << "  PBQP Regalloc round " << round << ":\n");
862
863      PBQP::SimpleGraph problem = constructPBQPProblem();
864      PBQP::HeuristicSolver<PBQP::Heuristics::Briggs> solver;
865      problem.assignNodeIDs();
866      PBQP::Solution solution = solver.solve(problem);
867
868      pbqpAllocComplete = mapPBQPToRegAlloc(solution);
869
870      ++round;
871    }
872  }
873
874  // Finalise allocation, allocate empty ranges.
875  finalizeAlloc();
876
877  vregIntervalsToAlloc.clear();
878  emptyVRegIntervals.clear();
879  li2Node.clear();
880  node2LI.clear();
881  allowedSets.clear();
882
883  DEBUG(errs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
884
885  // Run rewriter
886  std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
887
888  rewriter->runOnMachineFunction(*mf, *vrm, lis);
889
890  return true;
891}
892
893FunctionPass* llvm::createPBQPRegisterAllocator() {
894  return new PBQPRegAlloc();
895}
896
897
898#undef DEBUG_TYPE
899