LLVM  7.0.0svn
WebAssemblyRegColoring.cpp
Go to the documentation of this file.
1 //===-- WebAssemblyRegColoring.cpp - Register coloring --------------------===//
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 /// \file
11 /// \brief This file implements a virtual register coloring pass.
12 ///
13 /// WebAssembly doesn't have a fixed number of registers, but it is still
14 /// desirable to minimize the total number of registers used in each function.
15 ///
16 /// This code is modeled after lib/CodeGen/StackSlotColoring.cpp.
17 ///
18 //===----------------------------------------------------------------------===//
19 
20 #include "WebAssembly.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/Support/Debug.h"
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "wasm-reg-coloring"
31 
32 namespace {
33 class WebAssemblyRegColoring final : public MachineFunctionPass {
34 public:
35  static char ID; // Pass identification, replacement for typeid
36  WebAssemblyRegColoring() : MachineFunctionPass(ID) {}
37 
38  StringRef getPassName() const override {
39  return "WebAssembly Register Coloring";
40  }
41 
42  void getAnalysisUsage(AnalysisUsage &AU) const override {
43  AU.setPreservesCFG();
49  }
50 
51  bool runOnMachineFunction(MachineFunction &MF) override;
52 
53 private:
54 };
55 } // end anonymous namespace
56 
59  return new WebAssemblyRegColoring();
60 }
61 
62 // Compute the total spill weight for VReg.
64  const MachineBlockFrequencyInfo *MBFI,
65  unsigned VReg) {
66  float weight = 0.0f;
67  for (MachineOperand &MO : MRI->reg_nodbg_operands(VReg))
68  weight += LiveIntervals::getSpillWeight(MO.isDef(), MO.isUse(), MBFI,
69  *MO.getParent());
70  return weight;
71 }
72 
73 bool WebAssemblyRegColoring::runOnMachineFunction(MachineFunction &MF) {
74  DEBUG({
75  dbgs() << "********** Register Coloring **********\n"
76  << "********** Function: " << MF.getName() << '\n';
77  });
78 
79  // If there are calls to setjmp or sigsetjmp, don't perform coloring. Virtual
80  // registers could be modified before the longjmp is executed, resulting in
81  // the wrong value being used afterwards. (See <rdar://problem/8007500>.)
82  // TODO: Does WebAssembly need to care about setjmp for register coloring?
83  if (MF.exposesReturnsTwice())
84  return false;
85 
87  LiveIntervals *Liveness = &getAnalysis<LiveIntervals>();
88  const MachineBlockFrequencyInfo *MBFI =
89  &getAnalysis<MachineBlockFrequencyInfo>();
91 
92  // Gather all register intervals into a list and sort them.
93  unsigned NumVRegs = MRI->getNumVirtRegs();
94  SmallVector<LiveInterval *, 0> SortedIntervals;
95  SortedIntervals.reserve(NumVRegs);
96 
97  DEBUG(dbgs() << "Interesting register intervals:\n");
98  for (unsigned i = 0; i < NumVRegs; ++i) {
99  unsigned VReg = TargetRegisterInfo::index2VirtReg(i);
100  if (MFI.isVRegStackified(VReg))
101  continue;
102  // Skip unused registers, which can use $drop.
103  if (MRI->use_empty(VReg))
104  continue;
105 
106  LiveInterval *LI = &Liveness->getInterval(VReg);
107  assert(LI->weight == 0.0f);
108  LI->weight = computeWeight(MRI, MBFI, VReg);
109  DEBUG(LI->dump());
110  SortedIntervals.push_back(LI);
111  }
112  DEBUG(dbgs() << '\n');
113 
114  // Sort them to put arguments first (since we don't want to rename live-in
115  // registers), by weight next, and then by position.
116  // TODO: Investigate more intelligent sorting heuristics. For starters, we
117  // should try to coalesce adjacent live intervals before non-adjacent ones.
118  std::sort(SortedIntervals.begin(), SortedIntervals.end(),
119  [MRI](LiveInterval *LHS, LiveInterval *RHS) {
120  if (MRI->isLiveIn(LHS->reg) != MRI->isLiveIn(RHS->reg))
121  return MRI->isLiveIn(LHS->reg);
122  if (LHS->weight != RHS->weight)
123  return LHS->weight > RHS->weight;
124  if (LHS->empty() || RHS->empty())
125  return !LHS->empty() && RHS->empty();
126  return *LHS < *RHS;
127  });
128 
129  DEBUG(dbgs() << "Coloring register intervals:\n");
130  SmallVector<unsigned, 16> SlotMapping(SortedIntervals.size(), -1u);
132  SortedIntervals.size());
133  BitVector UsedColors(SortedIntervals.size());
134  bool Changed = false;
135  for (size_t i = 0, e = SortedIntervals.size(); i < e; ++i) {
136  LiveInterval *LI = SortedIntervals[i];
137  unsigned Old = LI->reg;
138  size_t Color = i;
139  const TargetRegisterClass *RC = MRI->getRegClass(Old);
140 
141  // Check if it's possible to reuse any of the used colors.
142  if (!MRI->isLiveIn(Old))
143  for (unsigned C : UsedColors.set_bits()) {
144  if (MRI->getRegClass(SortedIntervals[C]->reg) != RC)
145  continue;
146  for (LiveInterval *OtherLI : Assignments[C])
147  if (!OtherLI->empty() && OtherLI->overlaps(*LI))
148  goto continue_outer;
149  Color = C;
150  break;
151  continue_outer:;
152  }
153 
154  unsigned New = SortedIntervals[Color]->reg;
155  SlotMapping[i] = New;
156  Changed |= Old != New;
157  UsedColors.set(Color);
158  Assignments[Color].push_back(LI);
159  DEBUG(dbgs() << "Assigning vreg"
160  << TargetRegisterInfo::virtReg2Index(LI->reg) << " to vreg"
161  << TargetRegisterInfo::virtReg2Index(New) << "\n");
162  }
163  if (!Changed)
164  return false;
165 
166  // Rewrite register operands.
167  for (size_t i = 0, e = SortedIntervals.size(); i < e; ++i) {
168  unsigned Old = SortedIntervals[i]->reg;
169  unsigned New = SlotMapping[i];
170  if (Old != New)
171  MRI->replaceRegWith(Old, New);
172  }
173  return true;
174 }
uint64_t CallInst * C
bool empty() const
Definition: LiveInterval.h:370
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
const unsigned reg
Definition: LiveInterval.h:667
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
static unsigned virtReg2Index(unsigned Reg)
Convert a virtual register number to a 0-based index.
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
static unsigned index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:136
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:638
iterator_range< reg_nodbg_iterator > reg_nodbg_operands(unsigned Reg) const
static float computeWeight(const MachineRegisterInfo *MRI, const MachineBlockFrequencyInfo *MBFI, unsigned VReg)
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
void reserve(size_type N)
Definition: SmallVector.h:378
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end...
AnalysisUsage & addRequired()
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
AnalysisUsage & addPreservedID(const void *ID)
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
unsigned const MachineRegisterInfo * MRI
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:116
Represent the analysis usage information of a pass.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
Color
A "color", which is either even or odd.
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:862
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:285
LiveInterval & getInterval(unsigned Reg)
static float getSpillWeight(bool isDef, bool isUse, const MachineBlockFrequencyInfo *MBFI, const MachineInstr &Instr)
Calculate the spill weight to assign to a single instruction.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
bool use_empty(unsigned RegNo) const
use_empty - Return true if there are no instructions using the specified register.
This struct contains the mappings from the slot numbers to unnamed metadata nodes, global values and types.
Definition: SlotMapping.h:33
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
bool isLiveIn(unsigned Reg) const
This class is derived from MachineFunctionInfo and contains private WebAssembly-specific information ...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:120
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool exposesReturnsTwice() const
exposesReturnsTwice - Returns true if the function calls setjmp or any other similar functions with a...
This file declares WebAssembly-specific per-machine-function information.
FunctionPass * createWebAssemblyRegColoring()
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
#define DEBUG(X)
Definition: Debug.h:118
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
Definition: Parallel.h:199