LLVM  4.0.0
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 (int C(UsedColors.find_first()); C != -1;
144  C = UsedColors.find_next(C)) {
145  if (MRI->getRegClass(SortedIntervals[C]->reg) != RC)
146  continue;
147  for (LiveInterval *OtherLI : Assignments[C])
148  if (!OtherLI->empty() && OtherLI->overlaps(*LI))
149  goto continue_outer;
150  Color = C;
151  break;
152  continue_outer:;
153  }
154 
155  unsigned New = SortedIntervals[Color]->reg;
156  SlotMapping[i] = New;
157  Changed |= Old != New;
158  UsedColors.set(Color);
159  Assignments[Color].push_back(LI);
160  DEBUG(dbgs() << "Assigning vreg"
161  << TargetRegisterInfo::virtReg2Index(LI->reg) << " to vreg"
162  << TargetRegisterInfo::virtReg2Index(New) << "\n");
163  }
164  if (!Changed)
165  return false;
166 
167  // Rewrite register operands.
168  for (size_t i = 0, e = SortedIntervals.size(); i < e; ++i) {
169  unsigned Old = SortedIntervals[i]->reg;
170  unsigned New = SlotMapping[i];
171  if (Old != New)
172  MRI->replaceRegWith(Old, New);
173  }
174  return true;
175 }
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
const unsigned reg
Definition: LiveInterval.h:656
static unsigned virtReg2Index(unsigned Reg)
Convert a virtual register number to a 0-based index.
size_t i
static unsigned index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
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:625
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:377
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end...
bool empty() const
Definition: LiveInterval.h:357
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
AnalysisUsage & addRequired()
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
bool isLiveIn(unsigned Reg) const
AnalysisUsage & addPreservedID(const void *ID)
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:115
Represent the analysis usage information of a pass.
void dump() const
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:298
Color
A "color", which is either even or odd.
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:276
LiveInterval & getInterval(unsigned Reg)
static float getSpillWeight(bool isDef, bool isUse, const MachineBlockFrequencyInfo *MBFI, const MachineInstr &Instr)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
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.
This class is derived from MachineFunctionInfo and contains private WebAssembly-specific information ...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
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...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
This file declares WebAssembly-specific per-machine-function information.
FunctionPass * createWebAssemblyRegColoring()
iterator_range< reg_nodbg_iterator > reg_nodbg_operands(unsigned Reg) const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
#define DEBUG(X)
Definition: Debug.h:100
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool use_empty(unsigned RegNo) const
use_empty - Return true if there are no instructions using the specified register.