1 //===- StrongPhiElimination.cpp - Eliminate PHI nodes by inserting copies -===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Owen Anderson and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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:
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
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "strongphielim"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/BreakCriticalMachineEdge.h"
25 #include "llvm/CodeGen/LiveVariables.h"
26 #include "llvm/CodeGen/MachineDominators.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/SSARegMap.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Compiler.h"
38 struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
39 static char ID; // Pass identification, replacement for typeid
40 StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
42 bool runOnMachineFunction(MachineFunction &Fn);
44 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
45 AU.addPreserved<LiveVariables>();
46 AU.addPreservedID(PHIEliminationID);
47 AU.addRequired<MachineDominatorTree>();
48 AU.addRequired<LiveVariables>();
50 MachineFunctionPass::getAnalysisUsage(AU);
53 virtual void releaseMemory() {
61 struct DomForestNode {
63 std::vector<DomForestNode*> children;
66 void addChild(DomForestNode* DFN) { children.push_back(DFN); }
69 typedef std::vector<DomForestNode*>::iterator iterator;
71 DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
73 parent->addChild(this);
77 for (iterator I = begin(), E = end(); I != E; ++I)
81 inline unsigned getReg() { return reg; }
83 inline DomForestNode::iterator begin() { return children.begin(); }
84 inline DomForestNode::iterator end() { return children.end(); }
87 DenseMap<MachineBasicBlock*, unsigned> preorder;
88 DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
90 DenseMap<MachineBasicBlock*, std::vector<MachineInstr*> > waiting;
93 void computeDFS(MachineFunction& MF);
94 void processBlock(MachineBasicBlock* MBB);
96 std::vector<DomForestNode*> computeDomForest(std::set<unsigned>& instrs);
97 void breakCriticalEdges(MachineFunction &Fn);
101 char StrongPHIElimination::ID = 0;
102 RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
103 "Eliminate PHI nodes for register allocation, intelligently");
106 const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
108 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
109 /// of the given MachineFunction. These numbers are then used in other parts
110 /// of the PHI elimination process.
111 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
112 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
113 SmallPtrSet<MachineDomTreeNode*, 8> visited;
117 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
119 MachineDomTreeNode* node = DT.getRootNode();
121 std::vector<MachineDomTreeNode*> worklist;
122 worklist.push_back(node);
124 while (!worklist.empty()) {
125 MachineDomTreeNode* currNode = worklist.back();
127 if (!frontier.count(currNode)) {
128 frontier.insert(currNode);
130 preorder.insert(std::make_pair(currNode->getBlock(), time));
133 bool inserted = false;
134 for (MachineDomTreeNode::iterator I = node->begin(), E = node->end();
136 if (!frontier.count(*I) && !visited.count(*I)) {
137 worklist.push_back(*I);
143 frontier.erase(currNode);
144 visited.insert(currNode);
145 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
152 /// PreorderSorter - a helper class that is used to sort registers
153 /// according to the preorder number of their defining blocks
154 class PreorderSorter {
156 DenseMap<MachineBasicBlock*, unsigned>& preorder;
160 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
161 LiveVariables& L) : preorder(p), LV(L) { }
163 bool operator()(unsigned A, unsigned B) {
167 MachineBasicBlock* ABlock = LV.getVarInfo(A).DefInst->getParent();
168 MachineBasicBlock* BBlock = LV.getVarInfo(A).DefInst->getParent();
170 if (preorder[ABlock] < preorder[BBlock])
172 else if (preorder[ABlock] > preorder[BBlock])
175 assert(0 && "Error sorting by dominance!");
180 /// computeDomForest - compute the subforest of the DomTree corresponding
181 /// to the defining blocks of the registers in question
182 std::vector<StrongPHIElimination::DomForestNode*>
183 StrongPHIElimination::computeDomForest(std::set<unsigned>& regs) {
184 LiveVariables& LV = getAnalysis<LiveVariables>();
186 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
187 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
189 std::vector<unsigned> worklist;
190 worklist.reserve(regs.size());
191 for (std::set<unsigned>::iterator I = regs.begin(), E = regs.end();
193 worklist.push_back(*I);
195 PreorderSorter PS(preorder, LV);
196 std::sort(worklist.begin(), worklist.end(), PS);
198 DomForestNode* CurrentParent = VirtualRoot;
199 std::vector<DomForestNode*> stack;
200 stack.push_back(VirtualRoot);
202 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
204 unsigned pre = preorder[LV.getVarInfo(*I).DefInst->getParent()];
205 MachineBasicBlock* parentBlock =
206 LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent();
208 while (pre > maxpreorder[parentBlock]) {
210 CurrentParent = stack.back();
212 parentBlock = LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent();
215 DomForestNode* child = new DomForestNode(*I, CurrentParent);
216 stack.push_back(child);
217 CurrentParent = child;
220 std::vector<DomForestNode*> ret;
221 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
225 /// isLiveIn - helper method that determines, from a VarInfo, if a register
226 /// is live into a block
227 bool isLiveIn(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
228 if (V.AliveBlocks.test(MBB->getNumber()))
231 if (V.DefInst->getParent() != MBB &&
232 V.UsedBlocks.test(MBB->getNumber()))
238 /// isLiveOut - help method that determines, from a VarInfo, if a register is
239 /// live out of a block.
240 bool isLiveOut(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
241 if (MBB == V.DefInst->getParent() ||
242 V.UsedBlocks.test(MBB->getNumber())) {
243 for (std::vector<MachineInstr*>::iterator I = V.Kills.begin(),
244 E = V.Kills.end(); I != E; ++I)
245 if ((*I)->getParent() == MBB)
254 /// processBlock - Eliminate PHIs in the given block
255 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
256 LiveVariables& LV = getAnalysis<LiveVariables>();
258 // Holds names that have been added to a set in any PHI within this block
259 // before the current one.
260 std::set<unsigned> ProcessedNames;
262 MachineBasicBlock::iterator P = MBB->begin();
263 while (P->getOpcode() == TargetInstrInfo::PHI) {
264 LiveVariables::VarInfo& PHIInfo = LV.getVarInfo(P->getOperand(0).getReg());
266 // Hold the names that are currently in the candidate set.
267 std::set<unsigned> PHIUnion;
268 std::set<MachineBasicBlock*> UnionedBlocks;
270 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
271 unsigned SrcReg = P->getOperand(i-1).getReg();
272 LiveVariables::VarInfo& SrcInfo = LV.getVarInfo(SrcReg);
274 if (isLiveIn(SrcInfo, P->getParent())) {
275 // add a copy from a_i to p in Waiting[From[a_i]]
276 } else if (isLiveOut(PHIInfo, SrcInfo.DefInst->getParent())) {
277 // add a copy to Waiting[From[a_i]]
278 } else if (PHIInfo.DefInst->getOpcode() == TargetInstrInfo::PHI &&
279 isLiveIn(PHIInfo, SrcInfo.DefInst->getParent())) {
280 // add a copy to Waiting[From[a_i]]
281 } else if (ProcessedNames.count(SrcReg)) {
282 // add a copy to Waiting[From[a_i]]
283 } else if (UnionedBlocks.count(SrcInfo.DefInst->getParent())) {
284 // add a copy to Waiting[From[a_i]]
286 PHIUnion.insert(SrcReg);
287 UnionedBlocks.insert(SrcInfo.DefInst->getParent());
291 std::vector<StrongPHIElimination::DomForestNode*> DF =
292 computeDomForest(PHIUnion);
296 ProcessedNames.insert(PHIUnion.begin(), PHIUnion.end());
301 /// breakCriticalEdges - Break critical edges coming into blocks with PHI
302 /// nodes, preserving dominator and livevariable info.
303 void StrongPHIElimination::breakCriticalEdges(MachineFunction &Fn) {
304 typedef std::pair<MachineBasicBlock*, MachineBasicBlock*> MBB_pair;
306 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
307 LiveVariables& LV = getAnalysis<LiveVariables>();
309 // Find critical edges
310 std::vector<MBB_pair> criticals;
311 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
313 I->begin()->getOpcode() == TargetInstrInfo::PHI &&
315 for (MachineBasicBlock::pred_iterator PI = I->pred_begin(),
316 PE = I->pred_end(); PI != PE; ++PI)
317 if ((*PI)->succ_size() > 1)
318 criticals.push_back(std::make_pair(*PI, I));
320 for (std::vector<MBB_pair>::iterator I = criticals.begin(),
321 E = criticals.end(); I != E; ++I) {
323 MachineBasicBlock* new_bb = SplitCriticalMachineEdge(I->first, I->second);
326 MDT.splitBlock(I->first);
328 // Update livevariables
329 for (unsigned var = 1024; var < Fn.getSSARegMap()->getLastVirtReg(); ++var)
330 if (isLiveOut(LV.getVarInfo(var), I->first))
331 LV.getVarInfo(var).AliveBlocks.set(new_bb->getNumber());
335 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
336 breakCriticalEdges(Fn);
339 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
341 I->begin()->getOpcode() == TargetInstrInfo::PHI)