blob: a06909f72e44b55a578dca5f10308b91a996bb2d [file] [log] [blame]
Owen Anderson0bda0e82007-10-31 03:37:57 +00001//===- StrongPhiElimination.cpp - Eliminate PHI nodes by inserting copies -===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Owen Anderson0bda0e82007-10-31 03:37:57 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass eliminates machine instruction PHI nodes by inserting copy
11// instructions, using an intelligent copy-folding technique based on
12// dominator information. This is technique is derived from:
13//
14// Budimlic, et al. Fast copy coalescing and live-range identification.
15// In Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language
16// Design and Implementation (Berlin, Germany, June 17 - 19, 2002).
17// PLDI '02. ACM, New York, NY, 25-32.
18// DOI= http://doi.acm.org/10.1145/512529.512534
19//
20//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "strongphielim"
23#include "llvm/CodeGen/Passes.h"
Owen Andersoneb37ecc2008-03-10 07:22:36 +000024#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Owen Anderson0bda0e82007-10-31 03:37:57 +000025#include "llvm/CodeGen/MachineDominators.h"
26#include "llvm/CodeGen/MachineFunctionPass.h"
27#include "llvm/CodeGen/MachineInstr.h"
Owen Anderson755ebab2008-03-17 06:08:26 +000028#include "llvm/CodeGen/MachineLoopInfo.h"
Owen Anderson0d893b42008-01-08 05:16:15 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Owen Anderson3947e4d2008-05-30 18:38:26 +000030#include "llvm/CodeGen/RegisterCoalescer.h"
Owen Anderson0bda0e82007-10-31 03:37:57 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetMachine.h"
Owen Andersonefbcebc2007-12-23 15:37:26 +000033#include "llvm/ADT/DepthFirstIterator.h"
Owen Anderson0bda0e82007-10-31 03:37:57 +000034#include "llvm/ADT/Statistic.h"
35#include "llvm/Support/Compiler.h"
36using namespace llvm;
37
Owen Anderson0bda0e82007-10-31 03:37:57 +000038namespace {
39 struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
40 static char ID; // Pass identification, replacement for typeid
41 StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
42
Owen Andersonec1213f2008-01-09 22:40:54 +000043 // Waiting stores, for each MBB, the set of copies that need to
44 // be inserted into that MBB
Owen Andersonafc6de02007-12-10 08:07:09 +000045 DenseMap<MachineBasicBlock*,
Owen Andersonefbcebc2007-12-23 15:37:26 +000046 std::map<unsigned, unsigned> > Waiting;
47
Owen Andersonec1213f2008-01-09 22:40:54 +000048 // Stacks holds the renaming stack for each register
Owen Andersonefbcebc2007-12-23 15:37:26 +000049 std::map<unsigned, std::vector<unsigned> > Stacks;
Owen Andersonec1213f2008-01-09 22:40:54 +000050
51 // Registers in UsedByAnother are PHI nodes that are themselves
52 // used as operands to another another PHI node
Owen Andersonefbcebc2007-12-23 15:37:26 +000053 std::set<unsigned> UsedByAnother;
Owen Andersonec1213f2008-01-09 22:40:54 +000054
Owen Andersona9efb262008-06-05 17:22:53 +000055 // RenameSets are the is a map from a PHI-defined register
Owen Andersonc12417e2008-07-24 17:12:16 +000056 // to the input registers to be coalesced along with the
57 // predecessor block for those input registers.
58 std::map<unsigned, std::map<unsigned, MachineBasicBlock*> > RenameSets;
Owen Andersondfd07ea2008-03-12 04:22:57 +000059
60 // PhiValueNumber holds the ID numbers of the VNs for each phi that we're
61 // eliminating, indexed by the register defined by that phi.
62 std::map<unsigned, unsigned> PhiValueNumber;
Owen Andersonafc6de02007-12-10 08:07:09 +000063
Owen Andersonec1213f2008-01-09 22:40:54 +000064 // Store the DFS-in number of each block
65 DenseMap<MachineBasicBlock*, unsigned> preorder;
66
67 // Store the DFS-out number of each block
68 DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
69
Owen Andersona4ad2e72007-11-06 04:49:43 +000070 bool runOnMachineFunction(MachineFunction &Fn);
71
Owen Anderson0bda0e82007-10-31 03:37:57 +000072 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.addRequired<MachineDominatorTree>();
Owen Andersoneb37ecc2008-03-10 07:22:36 +000074 AU.addRequired<LiveIntervals>();
75
76 // TODO: Actually make this true.
77 AU.addPreserved<LiveIntervals>();
Owen Anderson3947e4d2008-05-30 18:38:26 +000078 AU.addPreserved<RegisterCoalescer>();
Owen Anderson0bda0e82007-10-31 03:37:57 +000079 MachineFunctionPass::getAnalysisUsage(AU);
80 }
81
82 virtual void releaseMemory() {
83 preorder.clear();
84 maxpreorder.clear();
Owen Andersona4ad2e72007-11-06 04:49:43 +000085
Owen Andersonefbcebc2007-12-23 15:37:26 +000086 Waiting.clear();
Owen Andersonec1213f2008-01-09 22:40:54 +000087 Stacks.clear();
88 UsedByAnother.clear();
89 RenameSets.clear();
Owen Anderson0bda0e82007-10-31 03:37:57 +000090 }
91
92 private:
Owen Andersonec1213f2008-01-09 22:40:54 +000093
94 /// DomForestNode - Represents a node in the "dominator forest". This is
95 /// a forest in which the nodes represent registers and the edges
96 /// represent a dominance relation in the block defining those registers.
Owen Anderson83430bc2007-11-04 22:33:26 +000097 struct DomForestNode {
98 private:
Owen Andersonec1213f2008-01-09 22:40:54 +000099 // Store references to our children
Owen Anderson83430bc2007-11-04 22:33:26 +0000100 std::vector<DomForestNode*> children;
Owen Andersonec1213f2008-01-09 22:40:54 +0000101 // The register we represent
Owen Andersonee49b532007-11-06 05:22:43 +0000102 unsigned reg;
Owen Anderson83430bc2007-11-04 22:33:26 +0000103
Owen Andersonec1213f2008-01-09 22:40:54 +0000104 // Add another node as our child
Owen Anderson83430bc2007-11-04 22:33:26 +0000105 void addChild(DomForestNode* DFN) { children.push_back(DFN); }
106
107 public:
108 typedef std::vector<DomForestNode*>::iterator iterator;
109
Owen Andersonec1213f2008-01-09 22:40:54 +0000110 // Create a DomForestNode by providing the register it represents, and
111 // the node to be its parent. The virtual root node has register 0
112 // and a null parent.
Owen Andersonee49b532007-11-06 05:22:43 +0000113 DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
Owen Anderson83430bc2007-11-04 22:33:26 +0000114 if (parent)
115 parent->addChild(this);
116 }
117
Owen Andersona4ad2e72007-11-06 04:49:43 +0000118 ~DomForestNode() {
119 for (iterator I = begin(), E = end(); I != E; ++I)
120 delete *I;
121 }
Owen Anderson83430bc2007-11-04 22:33:26 +0000122
Owen Andersonec1213f2008-01-09 22:40:54 +0000123 /// getReg - Return the regiser that this node represents
Owen Andersonee49b532007-11-06 05:22:43 +0000124 inline unsigned getReg() { return reg; }
Owen Andersona4ad2e72007-11-06 04:49:43 +0000125
Owen Andersonec1213f2008-01-09 22:40:54 +0000126 // Provide iterator access to our children
Owen Andersona4ad2e72007-11-06 04:49:43 +0000127 inline DomForestNode::iterator begin() { return children.begin(); }
128 inline DomForestNode::iterator end() { return children.end(); }
Owen Anderson83430bc2007-11-04 22:33:26 +0000129 };
130
Owen Anderson0bda0e82007-10-31 03:37:57 +0000131 void computeDFS(MachineFunction& MF);
Owen Anderson60a877d2007-11-07 05:17:15 +0000132 void processBlock(MachineBasicBlock* MBB);
Owen Anderson83430bc2007-11-04 22:33:26 +0000133
Owen Andersonc12417e2008-07-24 17:12:16 +0000134 std::vector<DomForestNode*> computeDomForest(
135 std::map<unsigned, MachineBasicBlock*>& instrs,
Owen Andersonddd060f2008-01-10 01:36:43 +0000136 MachineRegisterInfo& MRI);
Owen Andersond525f662007-12-11 20:12:11 +0000137 void processPHIUnion(MachineInstr* Inst,
Owen Andersonc12417e2008-07-24 17:12:16 +0000138 std::map<unsigned, MachineBasicBlock*>& PHIUnion,
Owen Anderson62d67dd2007-12-13 05:53:03 +0000139 std::vector<StrongPHIElimination::DomForestNode*>& DF,
140 std::vector<std::pair<unsigned, unsigned> >& locals);
Owen Andersonf1519e82007-12-24 22:12:23 +0000141 void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
Owen Anderson724acf12008-08-07 18:28:07 +0000142 void InsertCopies(MachineDomTreeNode* MBB,
Owen Andersone46611e2008-03-24 04:11:27 +0000143 SmallPtrSet<MachineBasicBlock*, 16>& v);
Owen Anderson27d66812008-08-13 17:25:42 +0000144 void mergeLiveIntervals(unsigned primary, unsigned secondary);
Owen Anderson0bda0e82007-10-31 03:37:57 +0000145 };
Owen Anderson0bda0e82007-10-31 03:37:57 +0000146}
147
Dan Gohman844731a2008-05-13 00:00:25 +0000148char StrongPHIElimination::ID = 0;
149static RegisterPass<StrongPHIElimination>
150X("strong-phi-node-elimination",
151 "Eliminate PHI nodes for register allocation, intelligently");
152
Dan Gohman6ddba2b2008-05-13 02:05:11 +0000153const PassInfo *const llvm::StrongPHIEliminationID = &X;
Owen Anderson0bda0e82007-10-31 03:37:57 +0000154
155/// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
156/// of the given MachineFunction. These numbers are then used in other parts
157/// of the PHI elimination process.
158void StrongPHIElimination::computeDFS(MachineFunction& MF) {
159 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
160 SmallPtrSet<MachineDomTreeNode*, 8> visited;
161
162 unsigned time = 0;
163
164 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
165
166 MachineDomTreeNode* node = DT.getRootNode();
167
168 std::vector<MachineDomTreeNode*> worklist;
169 worklist.push_back(node);
170
171 while (!worklist.empty()) {
172 MachineDomTreeNode* currNode = worklist.back();
173
174 if (!frontier.count(currNode)) {
175 frontier.insert(currNode);
176 ++time;
177 preorder.insert(std::make_pair(currNode->getBlock(), time));
178 }
179
180 bool inserted = false;
Owen Andersonbc91bd32008-03-31 01:39:20 +0000181 for (MachineDomTreeNode::iterator I = currNode->begin(), E = currNode->end();
Owen Anderson0bda0e82007-10-31 03:37:57 +0000182 I != E; ++I)
183 if (!frontier.count(*I) && !visited.count(*I)) {
184 worklist.push_back(*I);
185 inserted = true;
186 break;
187 }
188
189 if (!inserted) {
190 frontier.erase(currNode);
191 visited.insert(currNode);
192 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
193
194 worklist.pop_back();
195 }
196 }
Duncan Sands1bd32712007-10-31 08:49:24 +0000197}
Owen Anderson83430bc2007-11-04 22:33:26 +0000198
Dan Gohman844731a2008-05-13 00:00:25 +0000199namespace {
200
Owen Anderson8b96b9f2007-11-06 05:26:02 +0000201/// PreorderSorter - a helper class that is used to sort registers
202/// according to the preorder number of their defining blocks
Owen Anderson83430bc2007-11-04 22:33:26 +0000203class PreorderSorter {
204private:
205 DenseMap<MachineBasicBlock*, unsigned>& preorder;
Owen Andersonddd060f2008-01-10 01:36:43 +0000206 MachineRegisterInfo& MRI;
Owen Anderson83430bc2007-11-04 22:33:26 +0000207
208public:
Owen Andersonee49b532007-11-06 05:22:43 +0000209 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
Owen Andersonddd060f2008-01-10 01:36:43 +0000210 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
Owen Anderson83430bc2007-11-04 22:33:26 +0000211
Owen Andersonee49b532007-11-06 05:22:43 +0000212 bool operator()(unsigned A, unsigned B) {
Owen Anderson83430bc2007-11-04 22:33:26 +0000213 if (A == B)
214 return false;
215
Owen Andersonddd060f2008-01-10 01:36:43 +0000216 MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
217 MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
Owen Andersonee49b532007-11-06 05:22:43 +0000218
219 if (preorder[ABlock] < preorder[BBlock])
Owen Anderson83430bc2007-11-04 22:33:26 +0000220 return true;
Owen Andersonee49b532007-11-06 05:22:43 +0000221 else if (preorder[ABlock] > preorder[BBlock])
Owen Anderson83430bc2007-11-04 22:33:26 +0000222 return false;
223
Owen Andersonee49b532007-11-06 05:22:43 +0000224 return false;
Owen Anderson83430bc2007-11-04 22:33:26 +0000225 }
226};
227
Dan Gohman844731a2008-05-13 00:00:25 +0000228}
229
Owen Anderson8b96b9f2007-11-06 05:26:02 +0000230/// computeDomForest - compute the subforest of the DomTree corresponding
231/// to the defining blocks of the registers in question
Owen Anderson83430bc2007-11-04 22:33:26 +0000232std::vector<StrongPHIElimination::DomForestNode*>
Owen Andersonc12417e2008-07-24 17:12:16 +0000233StrongPHIElimination::computeDomForest(
234 std::map<unsigned, MachineBasicBlock*>& regs,
Owen Andersonddd060f2008-01-10 01:36:43 +0000235 MachineRegisterInfo& MRI) {
Owen Andersonec1213f2008-01-09 22:40:54 +0000236 // Begin by creating a virtual root node, since the actual results
237 // may well be a forest. Assume this node has maximum DFS-out number.
Owen Anderson83430bc2007-11-04 22:33:26 +0000238 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
239 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
240
Owen Andersonec1213f2008-01-09 22:40:54 +0000241 // Populate a worklist with the registers
Owen Andersonee49b532007-11-06 05:22:43 +0000242 std::vector<unsigned> worklist;
243 worklist.reserve(regs.size());
Owen Andersonc12417e2008-07-24 17:12:16 +0000244 for (std::map<unsigned, MachineBasicBlock*>::iterator I = regs.begin(),
245 E = regs.end(); I != E; ++I)
Owen Anderson00316712008-03-12 03:13:29 +0000246 worklist.push_back(I->first);
Owen Andersonee49b532007-11-06 05:22:43 +0000247
Owen Andersonec1213f2008-01-09 22:40:54 +0000248 // Sort the registers by the DFS-in number of their defining block
Owen Andersonddd060f2008-01-10 01:36:43 +0000249 PreorderSorter PS(preorder, MRI);
Owen Anderson83430bc2007-11-04 22:33:26 +0000250 std::sort(worklist.begin(), worklist.end(), PS);
251
Owen Andersonec1213f2008-01-09 22:40:54 +0000252 // Create a "current parent" stack, and put the virtual root on top of it
Owen Anderson83430bc2007-11-04 22:33:26 +0000253 DomForestNode* CurrentParent = VirtualRoot;
254 std::vector<DomForestNode*> stack;
255 stack.push_back(VirtualRoot);
256
Owen Andersonec1213f2008-01-09 22:40:54 +0000257 // Iterate over all the registers in the previously computed order
Owen Andersonee49b532007-11-06 05:22:43 +0000258 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
259 I != E; ++I) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000260 unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
Owen Andersoncb7d9492008-01-09 06:19:05 +0000261 MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
Owen Andersonddd060f2008-01-10 01:36:43 +0000262 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
Owen Andersoncb7d9492008-01-09 06:19:05 +0000263 0;
Owen Andersonee49b532007-11-06 05:22:43 +0000264
Owen Andersonec1213f2008-01-09 22:40:54 +0000265 // If the DFS-in number of the register is greater than the DFS-out number
266 // of the current parent, repeatedly pop the parent stack until it isn't.
Owen Andersonee49b532007-11-06 05:22:43 +0000267 while (pre > maxpreorder[parentBlock]) {
Owen Anderson83430bc2007-11-04 22:33:26 +0000268 stack.pop_back();
269 CurrentParent = stack.back();
Owen Andersonee49b532007-11-06 05:22:43 +0000270
Owen Anderson864e3a32008-01-09 10:41:39 +0000271 parentBlock = CurrentParent->getReg() ?
Owen Andersonddd060f2008-01-10 01:36:43 +0000272 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
Owen Anderson864e3a32008-01-09 10:41:39 +0000273 0;
Owen Anderson83430bc2007-11-04 22:33:26 +0000274 }
275
Owen Andersonec1213f2008-01-09 22:40:54 +0000276 // Now that we've found the appropriate parent, create a DomForestNode for
277 // this register and attach it to the forest
Owen Anderson83430bc2007-11-04 22:33:26 +0000278 DomForestNode* child = new DomForestNode(*I, CurrentParent);
Owen Andersonec1213f2008-01-09 22:40:54 +0000279
280 // Push this new node on the "current parent" stack
Owen Anderson83430bc2007-11-04 22:33:26 +0000281 stack.push_back(child);
282 CurrentParent = child;
283 }
284
Owen Andersonec1213f2008-01-09 22:40:54 +0000285 // Return a vector containing the children of the virtual root node
Owen Anderson83430bc2007-11-04 22:33:26 +0000286 std::vector<DomForestNode*> ret;
287 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
288 return ret;
289}
Owen Andersona4ad2e72007-11-06 04:49:43 +0000290
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000291/// isLiveIn - helper method that determines, from a regno, if a register
Owen Anderson60a877d2007-11-07 05:17:15 +0000292/// is live into a block
Owen Andersonddd060f2008-01-10 01:36:43 +0000293static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000294 LiveIntervals& LI) {
295 LiveInterval& I = LI.getOrCreateInterval(r);
296 unsigned idx = LI.getMBBStartIdx(MBB);
297 return I.liveBeforeAndAt(idx);
Owen Anderson60a877d2007-11-07 05:17:15 +0000298}
299
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000300/// isLiveOut - help method that determines, from a regno, if a register is
Owen Anderson60a877d2007-11-07 05:17:15 +0000301/// live out of a block.
Owen Andersonddd060f2008-01-10 01:36:43 +0000302static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000303 LiveIntervals& LI) {
304 for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
Owen Anderson724acf12008-08-07 18:28:07 +0000305 E = MBB->succ_end(); PI != E; ++PI)
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000306 if (isLiveIn(r, *PI, LI))
307 return true;
Owen Anderson60a877d2007-11-07 05:17:15 +0000308
309 return false;
310}
311
Owen Anderson87a702b2007-12-16 05:44:27 +0000312/// interferes - checks for local interferences by scanning a block. The only
313/// trick parameter is 'mode' which tells it the relationship of the two
314/// registers. 0 - defined in the same block, 1 - first properly dominates
315/// second, 2 - second properly dominates first
Owen Andersonb199cbe2008-01-10 00:33:11 +0000316static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000317 LiveIntervals& LV, unsigned mode) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000318 MachineInstr* def = 0;
319 MachineInstr* kill = 0;
320
Owen Andersonddd060f2008-01-10 01:36:43 +0000321 // The code is still in SSA form at this point, so there is only one
322 // definition per VReg. Thus we can safely use MRI->getVRegDef().
323 const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
Owen Andersonb199cbe2008-01-10 00:33:11 +0000324
Owen Anderson87a702b2007-12-16 05:44:27 +0000325 bool interference = false;
326
327 // Wallk the block, checking for interferences
328 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
329 MBI != MBE; ++MBI) {
330 MachineInstr* curr = MBI;
331
332 // Same defining block...
333 if (mode == 0) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000334 if (curr == MRI->getVRegDef(a)) {
335 // If we find our first definition, save it
Owen Anderson87a702b2007-12-16 05:44:27 +0000336 if (!def) {
337 def = curr;
Owen Andersonddd060f2008-01-10 01:36:43 +0000338 // If there's already an unkilled definition, then
Owen Anderson87a702b2007-12-16 05:44:27 +0000339 // this is an interference
340 } else if (!kill) {
341 interference = true;
342 break;
Owen Andersonddd060f2008-01-10 01:36:43 +0000343 // If there's a definition followed by a KillInst, then
Owen Anderson87a702b2007-12-16 05:44:27 +0000344 // they can't interfere
345 } else {
346 interference = false;
347 break;
348 }
349 // Symmetric with the above
Owen Andersonddd060f2008-01-10 01:36:43 +0000350 } else if (curr == MRI->getVRegDef(b)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000351 if (!def) {
352 def = curr;
353 } else if (!kill) {
354 interference = true;
355 break;
356 } else {
357 interference = false;
358 break;
359 }
Owen Andersonddd060f2008-01-10 01:36:43 +0000360 // Store KillInsts if they match up with the definition
Evan Cheng6130f662008-03-05 00:59:57 +0000361 } else if (curr->killsRegister(a)) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000362 if (def == MRI->getVRegDef(a)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000363 kill = curr;
Evan Cheng6130f662008-03-05 00:59:57 +0000364 } else if (curr->killsRegister(b)) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000365 if (def == MRI->getVRegDef(b)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000366 kill = curr;
367 }
368 }
369 }
370 // First properly dominates second...
371 } else if (mode == 1) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000372 if (curr == MRI->getVRegDef(b)) {
373 // Definition of second without kill of first is an interference
Owen Anderson87a702b2007-12-16 05:44:27 +0000374 if (!kill) {
375 interference = true;
376 break;
Owen Andersonddd060f2008-01-10 01:36:43 +0000377 // Definition after a kill is a non-interference
Owen Anderson87a702b2007-12-16 05:44:27 +0000378 } else {
379 interference = false;
380 break;
381 }
382 // Save KillInsts of First
Evan Cheng6130f662008-03-05 00:59:57 +0000383 } else if (curr->killsRegister(a)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000384 kill = curr;
385 }
386 // Symmetric with the above
387 } else if (mode == 2) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000388 if (curr == MRI->getVRegDef(a)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000389 if (!kill) {
390 interference = true;
391 break;
392 } else {
393 interference = false;
394 break;
395 }
Evan Cheng6130f662008-03-05 00:59:57 +0000396 } else if (curr->killsRegister(b)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000397 kill = curr;
398 }
399 }
400 }
401
402 return interference;
403}
404
Owen Andersondc4d6552008-01-10 00:47:01 +0000405/// processBlock - Determine how to break up PHIs in the current block. Each
406/// PHI is broken up by some combination of renaming its operands and inserting
407/// copies. This method is responsible for determining which operands receive
408/// which treatment.
Owen Anderson60a877d2007-11-07 05:17:15 +0000409void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000410 LiveIntervals& LI = getAnalysis<LiveIntervals>();
Owen Andersonddd060f2008-01-10 01:36:43 +0000411 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
Owen Anderson60a877d2007-11-07 05:17:15 +0000412
413 // Holds names that have been added to a set in any PHI within this block
414 // before the current one.
415 std::set<unsigned> ProcessedNames;
416
Owen Andersondc4d6552008-01-10 00:47:01 +0000417 // Iterate over all the PHI nodes in this block
Owen Anderson60a877d2007-11-07 05:17:15 +0000418 MachineBasicBlock::iterator P = MBB->begin();
Owen Anderson78216bc2008-04-01 18:05:08 +0000419 while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
Owen Andersonafc6de02007-12-10 08:07:09 +0000420 unsigned DestReg = P->getOperand(0).getReg();
421
Owen Anderson9860b712008-08-06 20:29:20 +0000422
Owen Andersond382f8a2008-03-26 03:03:23 +0000423 // Don't both doing PHI elimination for dead PHI's.
424 if (P->registerDefIsDead(DestReg)) {
425 ++P;
426 continue;
427 }
428
Owen Andersondfd07ea2008-03-12 04:22:57 +0000429 LiveInterval& PI = LI.getOrCreateInterval(DestReg);
Owen Andersonc7c00362008-03-29 01:58:47 +0000430 unsigned pIdx = LI.getDefIndex(LI.getInstructionIndex(P));
Owen Andersondfd07ea2008-03-12 04:22:57 +0000431 VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
432 PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
433
Owen Andersondc4d6552008-01-10 00:47:01 +0000434 // PHIUnion is the set of incoming registers to the PHI node that
435 // are going to be renames rather than having copies inserted. This set
436 // is refinded over the course of this function. UnionedBlocks is the set
437 // of corresponding MBBs.
Owen Andersonc12417e2008-07-24 17:12:16 +0000438 std::map<unsigned, MachineBasicBlock*> PHIUnion;
Owen Andersone46611e2008-03-24 04:11:27 +0000439 SmallPtrSet<MachineBasicBlock*, 8> UnionedBlocks;
Owen Anderson60a877d2007-11-07 05:17:15 +0000440
Owen Andersondc4d6552008-01-10 00:47:01 +0000441 // Iterate over the operands of the PHI node
Owen Anderson60a877d2007-11-07 05:17:15 +0000442 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
443 unsigned SrcReg = P->getOperand(i-1).getReg();
Owen Anderson9860b712008-08-06 20:29:20 +0000444
445 // Don't need to try to coalesce a register with itself.
446 if (SrcReg == DestReg) {
447 ProcessedNames.insert(SrcReg);
448 continue;
449 }
Owen Anderson60a877d2007-11-07 05:17:15 +0000450
Owen Andersondc4d6552008-01-10 00:47:01 +0000451 // Check for trivial interferences via liveness information, allowing us
452 // to avoid extra work later. Any registers that interfere cannot both
453 // be in the renaming set, so choose one and add copies for it instead.
454 // The conditions are:
455 // 1) if the operand is live into the PHI node's block OR
456 // 2) if the PHI node is live out of the operand's defining block OR
457 // 3) if the operand is itself a PHI node and the original PHI is
458 // live into the operand's defining block OR
459 // 4) if the operand is already being renamed for another PHI node
460 // in this block OR
461 // 5) if any two operands are defined in the same block, insert copies
462 // for one of them
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000463 if (isLiveIn(SrcReg, P->getParent(), LI) ||
Owen Andersonddd060f2008-01-10 01:36:43 +0000464 isLiveOut(P->getOperand(0).getReg(),
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000465 MRI.getVRegDef(SrcReg)->getParent(), LI) ||
Owen Andersonddd060f2008-01-10 01:36:43 +0000466 ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
467 isLiveIn(P->getOperand(0).getReg(),
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000468 MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
Owen Andersonafc6de02007-12-10 08:07:09 +0000469 ProcessedNames.count(SrcReg) ||
Owen Andersonddd060f2008-01-10 01:36:43 +0000470 UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
Owen Andersonafc6de02007-12-10 08:07:09 +0000471
Owen Andersondc4d6552008-01-10 00:47:01 +0000472 // Add a copy for the selected register
Chris Lattner8aa797a2007-12-30 23:10:15 +0000473 MachineBasicBlock* From = P->getOperand(i).getMBB();
Owen Andersonefbcebc2007-12-23 15:37:26 +0000474 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
475 UsedByAnother.insert(SrcReg);
Owen Anderson60a877d2007-11-07 05:17:15 +0000476 } else {
Owen Andersondc4d6552008-01-10 00:47:01 +0000477 // Otherwise, add it to the renaming set
Owen Andersonc12417e2008-07-24 17:12:16 +0000478 PHIUnion.insert(std::make_pair(SrcReg,P->getOperand(i).getMBB()));
Owen Andersonddd060f2008-01-10 01:36:43 +0000479 UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
Owen Anderson60a877d2007-11-07 05:17:15 +0000480 }
Owen Anderson60a877d2007-11-07 05:17:15 +0000481 }
482
Owen Andersondc4d6552008-01-10 00:47:01 +0000483 // Compute the dominator forest for the renaming set. This is a forest
484 // where the nodes are the registers and the edges represent dominance
485 // relations between the defining blocks of the registers
Owen Anderson42f9e962007-11-13 20:13:24 +0000486 std::vector<StrongPHIElimination::DomForestNode*> DF =
Owen Andersonddd060f2008-01-10 01:36:43 +0000487 computeDomForest(PHIUnion, MRI);
Owen Anderson42f9e962007-11-13 20:13:24 +0000488
Owen Andersondc4d6552008-01-10 00:47:01 +0000489 // Walk DomForest to resolve interferences at an inter-block level. This
490 // will remove registers from the renaming set (and insert copies for them)
491 // if interferences are found.
Owen Anderson62d67dd2007-12-13 05:53:03 +0000492 std::vector<std::pair<unsigned, unsigned> > localInterferences;
493 processPHIUnion(P, PHIUnion, DF, localInterferences);
494
Owen Anderson52b17332008-04-02 03:00:13 +0000495 // If one of the inputs is defined in the same block as the current PHI
496 // then we need to check for a local interference between that input and
497 // the PHI.
Owen Andersonc12417e2008-07-24 17:12:16 +0000498 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
Owen Anderson52b17332008-04-02 03:00:13 +0000499 E = PHIUnion.end(); I != E; ++I)
500 if (MRI.getVRegDef(I->first)->getParent() == P->getParent())
501 localInterferences.push_back(std::make_pair(I->first,
502 P->getOperand(0).getReg()));
503
Owen Andersondc4d6552008-01-10 00:47:01 +0000504 // The dominator forest walk may have returned some register pairs whose
Owen Anderson52b17332008-04-02 03:00:13 +0000505 // interference cannot be determined from dominator analysis. We now
Owen Andersondc4d6552008-01-10 00:47:01 +0000506 // examine these pairs for local interferences.
Owen Anderson87a702b2007-12-16 05:44:27 +0000507 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
508 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
509 std::pair<unsigned, unsigned> p = *I;
510
Owen Anderson87a702b2007-12-16 05:44:27 +0000511 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
512
513 // Determine the block we need to scan and the relationship between
514 // the two registers
515 MachineBasicBlock* scan = 0;
516 unsigned mode = 0;
Owen Andersonddd060f2008-01-10 01:36:43 +0000517 if (MRI.getVRegDef(p.first)->getParent() ==
518 MRI.getVRegDef(p.second)->getParent()) {
519 scan = MRI.getVRegDef(p.first)->getParent();
Owen Anderson87a702b2007-12-16 05:44:27 +0000520 mode = 0; // Same block
Owen Andersonddd060f2008-01-10 01:36:43 +0000521 } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
522 MRI.getVRegDef(p.second)->getParent())) {
523 scan = MRI.getVRegDef(p.second)->getParent();
Owen Anderson87a702b2007-12-16 05:44:27 +0000524 mode = 1; // First dominates second
525 } else {
Owen Andersonddd060f2008-01-10 01:36:43 +0000526 scan = MRI.getVRegDef(p.first)->getParent();
Owen Anderson87a702b2007-12-16 05:44:27 +0000527 mode = 2; // Second dominates first
528 }
529
530 // If there's an interference, we need to insert copies
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000531 if (interferes(p.first, p.second, scan, LI, mode)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000532 // Insert copies for First
533 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
534 if (P->getOperand(i-1).getReg() == p.first) {
535 unsigned SrcReg = p.first;
536 MachineBasicBlock* From = P->getOperand(i).getMBB();
537
Owen Andersonefbcebc2007-12-23 15:37:26 +0000538 Waiting[From].insert(std::make_pair(SrcReg,
539 P->getOperand(0).getReg()));
540 UsedByAnother.insert(SrcReg);
541
Owen Anderson87a702b2007-12-16 05:44:27 +0000542 PHIUnion.erase(SrcReg);
543 }
544 }
545 }
546 }
Owen Anderson42f9e962007-11-13 20:13:24 +0000547
Owen Anderson52b17332008-04-02 03:00:13 +0000548 // Add the renaming set for this PHI node to our overall renaming information
Owen Anderson0c5714b2008-01-08 21:54:52 +0000549 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
Owen Andersoncae8d8d2007-12-22 04:59:10 +0000550
Owen Andersondc4d6552008-01-10 00:47:01 +0000551 // Remember which registers are already renamed, so that we don't try to
552 // rename them for another PHI node in this block
Owen Andersonc12417e2008-07-24 17:12:16 +0000553 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
Owen Anderson00316712008-03-12 03:13:29 +0000554 E = PHIUnion.end(); I != E; ++I)
555 ProcessedNames.insert(I->first);
Owen Andersondc4d6552008-01-10 00:47:01 +0000556
Owen Anderson60a877d2007-11-07 05:17:15 +0000557 ++P;
558 }
Owen Andersonee49b532007-11-06 05:22:43 +0000559}
560
Gabor Greif2cf36e02008-03-06 10:51:21 +0000561/// processPHIUnion - Take a set of candidate registers to be coalesced when
Owen Anderson965b4672007-12-16 04:07:23 +0000562/// decomposing the PHI instruction. Use the DominanceForest to remove the ones
563/// that are known to interfere, and flag others that need to be checked for
564/// local interferences.
Owen Andersond525f662007-12-11 20:12:11 +0000565void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
Owen Andersonc12417e2008-07-24 17:12:16 +0000566 std::map<unsigned, MachineBasicBlock*>& PHIUnion,
Owen Anderson62d67dd2007-12-13 05:53:03 +0000567 std::vector<StrongPHIElimination::DomForestNode*>& DF,
568 std::vector<std::pair<unsigned, unsigned> >& locals) {
Owen Andersond525f662007-12-11 20:12:11 +0000569
570 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
571 SmallPtrSet<DomForestNode*, 4> visited;
572
Owen Andersonddd060f2008-01-10 01:36:43 +0000573 // Code is still in SSA form, so we can use MRI::getVRegDef()
574 MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
575
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000576 LiveIntervals& LI = getAnalysis<LiveIntervals>();
Owen Andersond525f662007-12-11 20:12:11 +0000577 unsigned DestReg = Inst->getOperand(0).getReg();
578
Owen Anderson965b4672007-12-16 04:07:23 +0000579 // DF walk on the DomForest
Owen Andersond525f662007-12-11 20:12:11 +0000580 while (!worklist.empty()) {
581 DomForestNode* DFNode = worklist.back();
582
Owen Andersond525f662007-12-11 20:12:11 +0000583 visited.insert(DFNode);
584
585 bool inserted = false;
Owen Andersond525f662007-12-11 20:12:11 +0000586 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
587 CI != CE; ++CI) {
588 DomForestNode* child = *CI;
Owen Anderson3b489522008-01-21 22:01:01 +0000589
590 // If the current node is live-out of the defining block of one of its
Owen Andersona6b19262008-01-21 22:03:00 +0000591 // children, insert a copy for it. NOTE: The paper actually calls for
592 // a more elaborate heuristic for determining whether to insert copies
593 // for the child or the parent. In the interest of simplicity, we're
594 // just always choosing the parent.
Owen Andersonddd060f2008-01-10 01:36:43 +0000595 if (isLiveOut(DFNode->getReg(),
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000596 MRI.getVRegDef(child->getReg())->getParent(), LI)) {
Owen Andersond525f662007-12-11 20:12:11 +0000597 // Insert copies for parent
598 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
599 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
Owen Andersoned2ffa22007-12-12 01:25:08 +0000600 unsigned SrcReg = DFNode->getReg();
Owen Andersond525f662007-12-11 20:12:11 +0000601 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
602
Owen Andersonefbcebc2007-12-23 15:37:26 +0000603 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
604 UsedByAnother.insert(SrcReg);
605
Owen Andersoned2ffa22007-12-12 01:25:08 +0000606 PHIUnion.erase(SrcReg);
Owen Andersond525f662007-12-11 20:12:11 +0000607 }
608 }
Owen Anderson3b489522008-01-21 22:01:01 +0000609
610 // If a node is live-in to the defining block of one of its children, but
611 // not live-out, then we need to scan that block for local interferences.
Owen Andersonddd060f2008-01-10 01:36:43 +0000612 } else if (isLiveIn(DFNode->getReg(),
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000613 MRI.getVRegDef(child->getReg())->getParent(), LI) ||
Owen Andersonddd060f2008-01-10 01:36:43 +0000614 MRI.getVRegDef(DFNode->getReg())->getParent() ==
615 MRI.getVRegDef(child->getReg())->getParent()) {
Owen Anderson62d67dd2007-12-13 05:53:03 +0000616 // Add (p, c) to possible local interferences
617 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
Owen Andersond525f662007-12-11 20:12:11 +0000618 }
Owen Anderson965b4672007-12-16 04:07:23 +0000619
Owen Anderson4ba08ec2007-12-13 05:43:37 +0000620 if (!visited.count(child)) {
621 worklist.push_back(child);
622 inserted = true;
Owen Andersond525f662007-12-11 20:12:11 +0000623 }
624 }
625
626 if (!inserted) worklist.pop_back();
627 }
628}
629
Owen Andersonefbcebc2007-12-23 15:37:26 +0000630/// ScheduleCopies - Insert copies into predecessor blocks, scheduling
631/// them properly so as to avoid the 'lost copy' and the 'virtual swap'
632/// problems.
633///
634/// Based on "Practical Improvements to the Construction and Destruction
635/// of Static Single Assignment Form" by Briggs, et al.
Owen Andersonf1519e82007-12-24 22:12:23 +0000636void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
637 std::set<unsigned>& pushed) {
Owen Anderson38b42502008-06-04 17:55:58 +0000638 // FIXME: This function needs to update LiveIntervals
Owen Andersonefbcebc2007-12-23 15:37:26 +0000639 std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
640
641 std::map<unsigned, unsigned> worklist;
642 std::map<unsigned, unsigned> map;
643
644 // Setup worklist of initial copies
645 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
646 E = copy_set.end(); I != E; ) {
647 map.insert(std::make_pair(I->first, I->first));
648 map.insert(std::make_pair(I->second, I->second));
649
Owen Andersonc7c00362008-03-29 01:58:47 +0000650 if (!UsedByAnother.count(I->second)) {
Owen Andersonefbcebc2007-12-23 15:37:26 +0000651 worklist.insert(*I);
652
653 // Avoid iterator invalidation
654 unsigned first = I->first;
655 ++I;
656 copy_set.erase(first);
657 } else {
658 ++I;
659 }
660 }
661
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000662 LiveIntervals& LI = getAnalysis<LiveIntervals>();
Owen Anderson0d893b42008-01-08 05:16:15 +0000663 MachineFunction* MF = MBB->getParent();
Owen Andersonddd060f2008-01-10 01:36:43 +0000664 MachineRegisterInfo& MRI = MF->getRegInfo();
Owen Anderson0d893b42008-01-08 05:16:15 +0000665 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Owen Andersonefbcebc2007-12-23 15:37:26 +0000666
Owen Anderson38b42502008-06-04 17:55:58 +0000667 SmallVector<std::pair<unsigned, MachineInstr*>, 4> InsertedPHIDests;
668
Owen Andersonefbcebc2007-12-23 15:37:26 +0000669 // Iterate over the worklist, inserting copies
670 while (!worklist.empty() || !copy_set.empty()) {
671 while (!worklist.empty()) {
672 std::pair<unsigned, unsigned> curr = *worklist.begin();
673 worklist.erase(curr.first);
674
Owen Anderson0d893b42008-01-08 05:16:15 +0000675 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
676
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000677 if (isLiveOut(curr.second, MBB, LI)) {
Owen Anderson0d893b42008-01-08 05:16:15 +0000678 // Create a temporary
679 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
680
681 // Insert copy from curr.second to a temporary at
682 // the Phi defining curr.second
Owen Andersonddd060f2008-01-10 01:36:43 +0000683 MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
684 TII->copyRegToReg(*PI->getParent(), PI, t,
Owen Anderson0d893b42008-01-08 05:16:15 +0000685 curr.second, RC, RC);
686
Owen Andersonefbcebc2007-12-23 15:37:26 +0000687 // Push temporary on Stacks
Owen Anderson0d893b42008-01-08 05:16:15 +0000688 Stacks[curr.second].push_back(t);
689
690 // Insert curr.second in pushed
691 pushed.insert(curr.second);
Owen Anderson724acf12008-08-07 18:28:07 +0000692
693 // Create a live interval for this temporary
694 InsertedPHIDests.push_back(std::make_pair(t, --PI));
Owen Andersonefbcebc2007-12-23 15:37:26 +0000695 }
696
697 // Insert copy from map[curr.first] to curr.second
Owen Anderson9c2efa82008-01-10 00:01:41 +0000698 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
Owen Anderson0d893b42008-01-08 05:16:15 +0000699 map[curr.first], RC, RC);
Owen Andersonefbcebc2007-12-23 15:37:26 +0000700 map[curr.first] = curr.second;
701
Owen Anderson38b42502008-06-04 17:55:58 +0000702 // Push this copy onto InsertedPHICopies so we can
703 // update LiveIntervals with it.
704 MachineBasicBlock::iterator MI = MBB->getFirstTerminator();
705 InsertedPHIDests.push_back(std::make_pair(curr.second, --MI));
706
Owen Andersonefbcebc2007-12-23 15:37:26 +0000707 // If curr.first is a destination in copy_set...
708 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
709 E = copy_set.end(); I != E; )
710 if (curr.first == I->second) {
711 std::pair<unsigned, unsigned> temp = *I;
712
713 // Avoid iterator invalidation
714 ++I;
715 copy_set.erase(temp.first);
716 worklist.insert(temp);
717
718 break;
719 } else {
720 ++I;
721 }
722 }
723
724 if (!copy_set.empty()) {
725 std::pair<unsigned, unsigned> curr = *copy_set.begin();
726 copy_set.erase(curr.first);
Owen Andersonefbcebc2007-12-23 15:37:26 +0000727 worklist.insert(curr);
Owen Anderson27d66812008-08-13 17:25:42 +0000728
729 LiveInterval& I = LI.getInterval(curr.second);
730 MachineBasicBlock::iterator term = MBB->getFirstTerminator();
731 unsigned endIdx = 0;
732 if (term != MBB->end())
733 endIdx = LI.getInstructionIndex(term);
734 else
735 endIdx = LI.getMBBEndIdx(MBB);
736
737 if (I.liveAt(endIdx)) {
738 const TargetRegisterClass *RC =
739 MF->getRegInfo().getRegClass(curr.first);
740
741 // Insert a copy from dest to a new temporary t at the end of b
742 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
743 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
744 curr.second, RC, RC);
745 map[curr.second] = t;
746
747 MachineBasicBlock::iterator TI = MBB->getFirstTerminator();
748 InsertedPHIDests.push_back(std::make_pair(t, --TI));
749 }
Owen Andersonefbcebc2007-12-23 15:37:26 +0000750 }
751 }
Owen Anderson38b42502008-06-04 17:55:58 +0000752
753 // Renumber the instructions so that we can perform the index computations
754 // needed to create new live intervals.
755 LI.computeNumbering();
756
757 // For copies that we inserted at the ends of predecessors, we construct
758 // live intervals. This is pretty easy, since we know that the destination
759 // register cannot have be in live at that point previously. We just have
760 // to make sure that, for registers that serve as inputs to more than one
761 // PHI, we don't create multiple overlapping live intervals.
762 std::set<unsigned> RegHandled;
763 for (SmallVector<std::pair<unsigned, MachineInstr*>, 4>::iterator I =
Owen Anderson27d66812008-08-13 17:25:42 +0000764 InsertedPHIDests.begin(), E = InsertedPHIDests.end(); I != E; ++I) {
765 unsigned bar = 0;
Owen Anderson724acf12008-08-07 18:28:07 +0000766 if (RegHandled.insert(I->first).second &&
767 !LI.getOrCreateInterval(I->first).liveAt(
768 LI.getMBBEndIdx(I->second->getParent())))
Owen Andersona9efb262008-06-05 17:22:53 +0000769 LI.addLiveRangeToEndOfBlock(I->first, I->second);
Owen Anderson27d66812008-08-13 17:25:42 +0000770 }
Owen Andersonefbcebc2007-12-23 15:37:26 +0000771}
772
Owen Andersonf1519e82007-12-24 22:12:23 +0000773/// InsertCopies - insert copies into MBB and all of its successors
Owen Anderson724acf12008-08-07 18:28:07 +0000774void StrongPHIElimination::InsertCopies(MachineDomTreeNode* MDTN,
Owen Andersone46611e2008-03-24 04:11:27 +0000775 SmallPtrSet<MachineBasicBlock*, 16>& visited) {
Owen Anderson724acf12008-08-07 18:28:07 +0000776 MachineBasicBlock* MBB = MDTN->getBlock();
Owen Anderson719fef62008-01-09 10:32:30 +0000777 visited.insert(MBB);
778
Owen Andersonf1519e82007-12-24 22:12:23 +0000779 std::set<unsigned> pushed;
780
Owen Anderson724acf12008-08-07 18:28:07 +0000781 LiveIntervals& LI = getAnalysis<LiveIntervals>();
Owen Andersonf1519e82007-12-24 22:12:23 +0000782 // Rewrite register uses from Stacks
783 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
Owen Anderson724acf12008-08-07 18:28:07 +0000784 I != E; ++I) {
785 if (I->getOpcode() == TargetInstrInfo::PHI)
786 continue;
787
Owen Andersonf1519e82007-12-24 22:12:23 +0000788 for (unsigned i = 0; i < I->getNumOperands(); ++i)
789 if (I->getOperand(i).isRegister() &&
790 Stacks[I->getOperand(i).getReg()].size()) {
Owen Anderson724acf12008-08-07 18:28:07 +0000791 // Remove the live range for the old vreg.
792 LiveInterval& OldInt = LI.getInterval(I->getOperand(i).getReg());
793 LiveInterval::iterator OldLR = OldInt.FindLiveRangeContaining(
794 LiveIntervals::getUseIndex(LI.getInstructionIndex(I)));
795 if (OldLR != OldInt.end())
796 OldInt.removeRange(*OldLR, true);
797
798 // Change the register
Owen Andersonf1519e82007-12-24 22:12:23 +0000799 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
Owen Anderson724acf12008-08-07 18:28:07 +0000800
801 // Add a live range for the new vreg
802 LiveInterval& Int = LI.getInterval(I->getOperand(i).getReg());
803 VNInfo* FirstVN = *Int.vni_begin();
804 FirstVN->hasPHIKill = false;
805 if (I->getOperand(i).isKill())
806 FirstVN->kills.push_back(
807 LiveIntervals::getUseIndex(LI.getInstructionIndex(I)));
808
809 LiveRange LR (LI.getMBBStartIdx(I->getParent()),
810 LiveIntervals::getUseIndex(LI.getInstructionIndex(I)),
811 FirstVN);
812
813 Int.addRange(LR);
Owen Andersonf1519e82007-12-24 22:12:23 +0000814 }
Owen Anderson724acf12008-08-07 18:28:07 +0000815 }
Owen Andersonf1519e82007-12-24 22:12:23 +0000816
817 // Schedule the copies for this block
818 ScheduleCopies(MBB, pushed);
819
Owen Anderson724acf12008-08-07 18:28:07 +0000820 // Recur down the dominator tree.
821 for (MachineDomTreeNode::iterator I = MDTN->begin(),
822 E = MDTN->end(); I != E; ++I)
823 if (!visited.count((*I)->getBlock()))
Owen Anderson719fef62008-01-09 10:32:30 +0000824 InsertCopies(*I, visited);
Owen Andersonf1519e82007-12-24 22:12:23 +0000825
826 // As we exit this block, pop the names we pushed while processing it
827 for (std::set<unsigned>::iterator I = pushed.begin(),
828 E = pushed.end(); I != E; ++I)
829 Stacks[*I].pop_back();
830}
831
Owen Anderson00316712008-03-12 03:13:29 +0000832void StrongPHIElimination::mergeLiveIntervals(unsigned primary,
Owen Anderson27d66812008-08-13 17:25:42 +0000833 unsigned secondary) {
Owen Anderson755ebab2008-03-17 06:08:26 +0000834
835 LiveIntervals& LI = getAnalysis<LiveIntervals>();
836 LiveInterval& LHS = LI.getOrCreateInterval(primary);
837 LiveInterval& RHS = LI.getOrCreateInterval(secondary);
838
Owen Andersona9efb262008-06-05 17:22:53 +0000839 LI.computeNumbering();
Owen Anderson27d66812008-08-13 17:25:42 +0000840
841 SmallVector<VNInfo*, 4> VNSet (RHS.vni_begin(), RHS.vni_end());
Owen Andersonb9fb8d12008-07-30 00:21:16 +0000842 DenseMap<VNInfo*, VNInfo*> VNMap;
Owen Anderson27d66812008-08-13 17:25:42 +0000843 for (SmallVector<VNInfo*, 4>::iterator VI = VNSet.begin(),
844 VE = VNSet.end(); VI != VE; ++VI) {
845 VNInfo* NewVN = LHS.getNextValue((*VI)->def,
846 (*VI)->copy,
847 LI.getVNInfoAllocator());
848 LHS.MergeValueInAsValue(RHS, *VI, NewVN);
849 RHS.removeValNo(*VI);
Owen Andersonb9fb8d12008-07-30 00:21:16 +0000850 }
Owen Anderson55c64352008-07-25 21:08:41 +0000851
Owen Anderson83ea1f82008-07-29 21:17:08 +0000852 if (RHS.begin() == RHS.end())
Owen Anderson55c64352008-07-25 21:08:41 +0000853 LI.removeInterval(RHS.reg);
Owen Anderson00316712008-03-12 03:13:29 +0000854}
855
Owen Andersona4ad2e72007-11-06 04:49:43 +0000856bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
Owen Andersonc7c00362008-03-29 01:58:47 +0000857 LiveIntervals& LI = getAnalysis<LiveIntervals>();
858
Owen Andersonefbcebc2007-12-23 15:37:26 +0000859 // Compute DFS numbers of each block
Owen Andersona4ad2e72007-11-06 04:49:43 +0000860 computeDFS(Fn);
861
Owen Andersonefbcebc2007-12-23 15:37:26 +0000862 // Determine which phi node operands need copies
Owen Anderson60a877d2007-11-07 05:17:15 +0000863 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
864 if (!I->empty() &&
865 I->begin()->getOpcode() == TargetInstrInfo::PHI)
866 processBlock(I);
Owen Andersona4ad2e72007-11-06 04:49:43 +0000867
Owen Anderson883771f2008-08-06 22:08:58 +0000868 // Break interferences where two different phis want to coalesce
869 // in the same register.
870 std::set<unsigned> seen;
871 typedef std::map<unsigned, std::map<unsigned, MachineBasicBlock*> >
872 RenameSetType;
873 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
874 I != E; ++I) {
875 for (std::map<unsigned, MachineBasicBlock*>::iterator
876 OI = I->second.begin(), OE = I->second.end(); OI != OE; ) {
877 if (!seen.count(OI->first)) {
878 seen.insert(OI->first);
879 ++OI;
880 } else {
881 Waiting[OI->second].insert(std::make_pair(OI->first, I->first));
882 unsigned reg = OI->first;
883 ++OI;
884 I->second.erase(reg);
885 }
886 }
887 }
888
Owen Andersonefbcebc2007-12-23 15:37:26 +0000889 // Insert copies
Owen Andersona9efb262008-06-05 17:22:53 +0000890 // FIXME: This process should probably preserve LiveIntervals
Owen Andersone46611e2008-03-24 04:11:27 +0000891 SmallPtrSet<MachineBasicBlock*, 16> visited;
Owen Anderson724acf12008-08-07 18:28:07 +0000892 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
893 InsertCopies(MDT.getRootNode(), visited);
Owen Andersonefbcebc2007-12-23 15:37:26 +0000894
Owen Anderson0c5714b2008-01-08 21:54:52 +0000895 // Perform renaming
Owen Anderson0c5714b2008-01-08 21:54:52 +0000896 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
897 I != E; ++I)
Owen Anderson883771f2008-08-06 22:08:58 +0000898 while (I->second.size()) {
899 std::map<unsigned, MachineBasicBlock*>::iterator SI = I->second.begin();
900
901 if (SI->first != I->first) {
Owen Anderson27d66812008-08-13 17:25:42 +0000902 mergeLiveIntervals(I->first, SI->first);
Owen Anderson883771f2008-08-06 22:08:58 +0000903 Fn.getRegInfo().replaceRegWith(SI->first, I->first);
904
905 if (RenameSets.count(SI->first)) {
906 I->second.insert(RenameSets[SI->first].begin(),
907 RenameSets[SI->first].end());
908 RenameSets.erase(SI->first);
909 }
Owen Anderson883771f2008-08-06 22:08:58 +0000910 }
911
912 I->second.erase(SI->first);
Owen Anderson00316712008-03-12 03:13:29 +0000913 }
Owen Anderson0c5714b2008-01-08 21:54:52 +0000914
915 // FIXME: Insert last-minute copies
916
917 // Remove PHIs
Owen Anderson97ca75e2008-01-22 23:58:54 +0000918 std::vector<MachineInstr*> phis;
919 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
Owen Anderson0c5714b2008-01-08 21:54:52 +0000920 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
921 BI != BE; ++BI)
922 if (BI->getOpcode() == TargetInstrInfo::PHI)
Owen Anderson97ca75e2008-01-22 23:58:54 +0000923 phis.push_back(BI);
924 }
925
926 for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
Owen Andersonc7c00362008-03-29 01:58:47 +0000927 I != E; ) {
928 MachineInstr* PInstr = *(I++);
929
Owen Anderson71ac0be2008-08-05 21:18:51 +0000930 // If this is a dead PHI node, then remove it from LiveIntervals.
931 unsigned DestReg = PInstr->getOperand(0).getReg();
932 LiveInterval& PI = LI.getInterval(DestReg);
933 if (PInstr->registerDefIsDead(DestReg)) {
934 if (PI.containsOneValue()) {
935 LI.removeInterval(DestReg);
936 } else {
937 unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
938 PI.removeRange(*PI.getLiveRangeContaining(idx), true);
939 }
940 } else {
Owen Andersone7b82052008-08-05 20:51:26 +0000941 // Trim live intervals of input registers. They are no longer live into
Owen Anderson9b491202008-08-06 18:36:17 +0000942 // this block if they died after the PHI. If they lived after it, don't
943 // trim them because they might have other legitimate uses.
Owen Andersone7b82052008-08-05 20:51:26 +0000944 for (unsigned i = 1; i < PInstr->getNumOperands(); i += 2) {
945 unsigned reg = PInstr->getOperand(i).getReg();
Owen Anderson883771f2008-08-06 22:08:58 +0000946
Owen Andersone7b82052008-08-05 20:51:26 +0000947 MachineBasicBlock* MBB = PInstr->getOperand(i+1).getMBB();
948 LiveInterval& InputI = LI.getInterval(reg);
949 if (MBB != PInstr->getParent() &&
Owen Anderson9b491202008-08-06 18:36:17 +0000950 InputI.liveAt(LI.getMBBStartIdx(PInstr->getParent())) &&
951 InputI.expiredAt(LI.getInstructionIndex(PInstr) +
952 LiveIntervals::InstrSlots::NUM))
Owen Andersone7b82052008-08-05 20:51:26 +0000953 InputI.removeRange(LI.getMBBStartIdx(PInstr->getParent()),
954 LI.getInstructionIndex(PInstr),
955 true);
Owen Andersond382f8a2008-03-26 03:03:23 +0000956 }
Owen Andersone7b82052008-08-05 20:51:26 +0000957
Owen Anderson71ac0be2008-08-05 21:18:51 +0000958 // If the PHI is not dead, then the valno defined by the PHI
959 // now has an unknown def.
960 unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
961 const LiveRange* PLR = PI.getLiveRangeContaining(idx);
962 PLR->valno->def = ~0U;
963 LiveRange R (LI.getMBBStartIdx(PInstr->getParent()),
964 PLR->start, PLR->valno);
965 PI.addRange(R);
Owen Andersond382f8a2008-03-26 03:03:23 +0000966 }
Owen Anderson59df8782008-04-02 02:12:45 +0000967
Owen Andersonc7c00362008-03-29 01:58:47 +0000968 LI.RemoveMachineInstrFromMaps(PInstr);
969 PInstr->eraseFromParent();
Owen Andersone46611e2008-03-24 04:11:27 +0000970 }
Owen Andersoncae8d8d2007-12-22 04:59:10 +0000971
Owen Anderson3947e4d2008-05-30 18:38:26 +0000972 LI.computeNumbering();
973
Owen Andersonc7c00362008-03-29 01:58:47 +0000974 return true;
Owen Andersona4ad2e72007-11-06 04:49:43 +0000975}