1 //===- StrongPhiElimination.cpp - Eliminate PHI nodes by inserting copies -===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/LiveVariables.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/ADT/DepthFirstIterator.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 DenseMap<MachineBasicBlock*,
43 std::map<unsigned, unsigned> > Waiting;
45 std::map<unsigned, std::vector<unsigned> > Stacks;
46 std::set<unsigned> UsedByAnother;
47 std::map<unsigned, std::set<unsigned> > RenameSets;
49 bool runOnMachineFunction(MachineFunction &Fn);
51 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
52 AU.addRequired<MachineDominatorTree>();
53 AU.addRequired<LiveVariables>();
54 MachineFunctionPass::getAnalysisUsage(AU);
57 virtual void releaseMemory() {
65 struct DomForestNode {
67 std::vector<DomForestNode*> children;
70 void addChild(DomForestNode* DFN) { children.push_back(DFN); }
73 typedef std::vector<DomForestNode*>::iterator iterator;
75 DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
77 parent->addChild(this);
81 for (iterator I = begin(), E = end(); I != E; ++I)
85 inline unsigned getReg() { return reg; }
87 inline DomForestNode::iterator begin() { return children.begin(); }
88 inline DomForestNode::iterator end() { return children.end(); }
91 DenseMap<MachineBasicBlock*, unsigned> preorder;
92 DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
95 void computeDFS(MachineFunction& MF);
96 void processBlock(MachineBasicBlock* MBB);
98 std::vector<DomForestNode*> computeDomForest(std::set<unsigned>& instrs);
99 void processPHIUnion(MachineInstr* Inst,
100 std::set<unsigned>& PHIUnion,
101 std::vector<StrongPHIElimination::DomForestNode*>& DF,
102 std::vector<std::pair<unsigned, unsigned> >& locals);
103 void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
104 void InsertCopies(MachineBasicBlock* MBB, std::set<MachineBasicBlock*>& v);
107 char StrongPHIElimination::ID = 0;
108 RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
109 "Eliminate PHI nodes for register allocation, intelligently");
112 const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
114 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
115 /// of the given MachineFunction. These numbers are then used in other parts
116 /// of the PHI elimination process.
117 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
118 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
119 SmallPtrSet<MachineDomTreeNode*, 8> visited;
123 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
125 MachineDomTreeNode* node = DT.getRootNode();
127 std::vector<MachineDomTreeNode*> worklist;
128 worklist.push_back(node);
130 while (!worklist.empty()) {
131 MachineDomTreeNode* currNode = worklist.back();
133 if (!frontier.count(currNode)) {
134 frontier.insert(currNode);
136 preorder.insert(std::make_pair(currNode->getBlock(), time));
139 bool inserted = false;
140 for (MachineDomTreeNode::iterator I = node->begin(), E = node->end();
142 if (!frontier.count(*I) && !visited.count(*I)) {
143 worklist.push_back(*I);
149 frontier.erase(currNode);
150 visited.insert(currNode);
151 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
158 /// PreorderSorter - a helper class that is used to sort registers
159 /// according to the preorder number of their defining blocks
160 class PreorderSorter {
162 DenseMap<MachineBasicBlock*, unsigned>& preorder;
166 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
167 LiveVariables& L) : preorder(p), LV(L) { }
169 bool operator()(unsigned A, unsigned B) {
173 MachineBasicBlock* ABlock = LV.getVarInfo(A).DefInst->getParent();
174 MachineBasicBlock* BBlock = LV.getVarInfo(A).DefInst->getParent();
176 if (preorder[ABlock] < preorder[BBlock])
178 else if (preorder[ABlock] > preorder[BBlock])
185 /// computeDomForest - compute the subforest of the DomTree corresponding
186 /// to the defining blocks of the registers in question
187 std::vector<StrongPHIElimination::DomForestNode*>
188 StrongPHIElimination::computeDomForest(std::set<unsigned>& regs) {
189 LiveVariables& LV = getAnalysis<LiveVariables>();
191 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
192 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
194 std::vector<unsigned> worklist;
195 worklist.reserve(regs.size());
196 for (std::set<unsigned>::iterator I = regs.begin(), E = regs.end();
198 worklist.push_back(*I);
200 PreorderSorter PS(preorder, LV);
201 std::sort(worklist.begin(), worklist.end(), PS);
203 DomForestNode* CurrentParent = VirtualRoot;
204 std::vector<DomForestNode*> stack;
205 stack.push_back(VirtualRoot);
207 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
209 unsigned pre = preorder[LV.getVarInfo(*I).DefInst->getParent()];
210 MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
211 LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent() :
214 while (pre > maxpreorder[parentBlock]) {
216 CurrentParent = stack.back();
218 parentBlock = CurrentParent->getReg() ?
219 LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent() :
223 DomForestNode* child = new DomForestNode(*I, CurrentParent);
224 stack.push_back(child);
225 CurrentParent = child;
228 std::vector<DomForestNode*> ret;
229 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
233 /// isLiveIn - helper method that determines, from a VarInfo, if a register
234 /// is live into a block
235 static bool isLiveIn(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
236 if (V.AliveBlocks.test(MBB->getNumber()))
239 if (V.DefInst->getParent() != MBB &&
240 V.UsedBlocks.test(MBB->getNumber()))
246 /// isLiveOut - help method that determines, from a VarInfo, if a register is
247 /// live out of a block.
248 static bool isLiveOut(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
249 if (MBB == V.DefInst->getParent() ||
250 V.UsedBlocks.test(MBB->getNumber())) {
251 for (std::vector<MachineInstr*>::iterator I = V.Kills.begin(),
252 E = V.Kills.end(); I != E; ++I)
253 if ((*I)->getParent() == MBB)
262 /// isKillInst - helper method that determines, from a VarInfo, if an
263 /// instruction kills a given register
264 static bool isKillInst(LiveVariables::VarInfo& V, MachineInstr* MI) {
265 return std::find(V.Kills.begin(), V.Kills.end(), MI) != V.Kills.end();
268 /// interferes - checks for local interferences by scanning a block. The only
269 /// trick parameter is 'mode' which tells it the relationship of the two
270 /// registers. 0 - defined in the same block, 1 - first properly dominates
271 /// second, 2 - second properly dominates first
272 static bool interferes(LiveVariables::VarInfo& First, LiveVariables::VarInfo& Second,
273 MachineBasicBlock* scan, unsigned mode) {
274 MachineInstr* def = 0;
275 MachineInstr* kill = 0;
277 bool interference = false;
279 // Wallk the block, checking for interferences
280 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
282 MachineInstr* curr = MBI;
284 // Same defining block...
286 if (curr == First.DefInst) {
287 // If we find our first DefInst, save it
290 // If there's already an unkilled DefInst, then
291 // this is an interference
295 // If there's a DefInst followed by a KillInst, then
296 // they can't interfere
298 interference = false;
301 // Symmetric with the above
302 } else if (curr == Second.DefInst ) {
309 interference = false;
312 // Store KillInsts if they match up with the DefInst
313 } else if (isKillInst(First, curr)) {
314 if (def == First.DefInst) {
316 } else if (isKillInst(Second, curr)) {
317 if (def == Second.DefInst) {
322 // First properly dominates second...
323 } else if (mode == 1) {
324 if (curr == Second.DefInst) {
325 // DefInst of second without kill of first is an interference
329 // DefInst after a kill is a non-interference
331 interference = false;
334 // Save KillInsts of First
335 } else if (isKillInst(First, curr)) {
338 // Symmetric with the above
339 } else if (mode == 2) {
340 if (curr == First.DefInst) {
345 interference = false;
348 } else if (isKillInst(Second, curr)) {
357 /// processBlock - Eliminate PHIs in the given block
358 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
359 LiveVariables& LV = getAnalysis<LiveVariables>();
361 // Holds names that have been added to a set in any PHI within this block
362 // before the current one.
363 std::set<unsigned> ProcessedNames;
365 MachineBasicBlock::iterator P = MBB->begin();
366 while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
367 LiveVariables::VarInfo& PHIInfo = LV.getVarInfo(P->getOperand(0).getReg());
369 unsigned DestReg = P->getOperand(0).getReg();
371 // Hold the names that are currently in the candidate set.
372 std::set<unsigned> PHIUnion;
373 std::set<MachineBasicBlock*> UnionedBlocks;
375 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
376 unsigned SrcReg = P->getOperand(i-1).getReg();
377 LiveVariables::VarInfo& SrcInfo = LV.getVarInfo(SrcReg);
379 // Check for trivial interferences
380 if (isLiveIn(SrcInfo, P->getParent()) ||
381 isLiveOut(PHIInfo, SrcInfo.DefInst->getParent()) ||
382 ( PHIInfo.DefInst->getOpcode() == TargetInstrInfo::PHI &&
383 isLiveIn(PHIInfo, SrcInfo.DefInst->getParent()) ) ||
384 ProcessedNames.count(SrcReg) ||
385 UnionedBlocks.count(SrcInfo.DefInst->getParent())) {
387 // add a copy from a_i to p in Waiting[From[a_i]]
388 MachineBasicBlock* From = P->getOperand(i).getMBB();
389 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
390 UsedByAnother.insert(SrcReg);
392 PHIUnion.insert(SrcReg);
393 UnionedBlocks.insert(SrcInfo.DefInst->getParent());
397 std::vector<StrongPHIElimination::DomForestNode*> DF =
398 computeDomForest(PHIUnion);
400 // Walk DomForest to resolve interferences
401 std::vector<std::pair<unsigned, unsigned> > localInterferences;
402 processPHIUnion(P, PHIUnion, DF, localInterferences);
404 // Check for local interferences
405 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
406 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
407 std::pair<unsigned, unsigned> p = *I;
409 LiveVariables::VarInfo& FirstInfo = LV.getVarInfo(p.first);
410 LiveVariables::VarInfo& SecondInfo = LV.getVarInfo(p.second);
412 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
414 // Determine the block we need to scan and the relationship between
416 MachineBasicBlock* scan = 0;
418 if (FirstInfo.DefInst->getParent() == SecondInfo.DefInst->getParent()) {
419 scan = FirstInfo.DefInst->getParent();
420 mode = 0; // Same block
421 } else if (MDT.dominates(FirstInfo.DefInst->getParent(),
422 SecondInfo.DefInst->getParent())) {
423 scan = SecondInfo.DefInst->getParent();
424 mode = 1; // First dominates second
426 scan = FirstInfo.DefInst->getParent();
427 mode = 2; // Second dominates first
430 // If there's an interference, we need to insert copies
431 if (interferes(FirstInfo, SecondInfo, scan, mode)) {
432 // Insert copies for First
433 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
434 if (P->getOperand(i-1).getReg() == p.first) {
435 unsigned SrcReg = p.first;
436 MachineBasicBlock* From = P->getOperand(i).getMBB();
438 Waiting[From].insert(std::make_pair(SrcReg,
439 P->getOperand(0).getReg()));
440 UsedByAnother.insert(SrcReg);
442 PHIUnion.erase(SrcReg);
448 // Cache renaming information
449 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
451 ProcessedNames.insert(PHIUnion.begin(), PHIUnion.end());
456 /// processPHIUnion - Take a set of candidate registers to be coallesced when
457 /// decomposing the PHI instruction. Use the DominanceForest to remove the ones
458 /// that are known to interfere, and flag others that need to be checked for
459 /// local interferences.
460 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
461 std::set<unsigned>& PHIUnion,
462 std::vector<StrongPHIElimination::DomForestNode*>& DF,
463 std::vector<std::pair<unsigned, unsigned> >& locals) {
465 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
466 SmallPtrSet<DomForestNode*, 4> visited;
468 LiveVariables& LV = getAnalysis<LiveVariables>();
469 unsigned DestReg = Inst->getOperand(0).getReg();
471 // DF walk on the DomForest
472 while (!worklist.empty()) {
473 DomForestNode* DFNode = worklist.back();
475 LiveVariables::VarInfo& Info = LV.getVarInfo(DFNode->getReg());
476 visited.insert(DFNode);
478 bool inserted = false;
479 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
481 DomForestNode* child = *CI;
482 LiveVariables::VarInfo& CInfo = LV.getVarInfo(child->getReg());
484 if (isLiveOut(Info, CInfo.DefInst->getParent())) {
485 // Insert copies for parent
486 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
487 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
488 unsigned SrcReg = DFNode->getReg();
489 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
491 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
492 UsedByAnother.insert(SrcReg);
494 PHIUnion.erase(SrcReg);
497 } else if (isLiveIn(Info, CInfo.DefInst->getParent()) ||
498 Info.DefInst->getParent() == CInfo.DefInst->getParent()) {
499 // Add (p, c) to possible local interferences
500 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
503 if (!visited.count(child)) {
504 worklist.push_back(child);
509 if (!inserted) worklist.pop_back();
513 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
514 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
517 /// Based on "Practical Improvements to the Construction and Destruction
518 /// of Static Single Assignment Form" by Briggs, et al.
519 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
520 std::set<unsigned>& pushed) {
521 // FIXME: This function needs to update LiveVariables
522 std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
524 std::map<unsigned, unsigned> worklist;
525 std::map<unsigned, unsigned> map;
527 // Setup worklist of initial copies
528 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
529 E = copy_set.end(); I != E; ) {
530 map.insert(std::make_pair(I->first, I->first));
531 map.insert(std::make_pair(I->second, I->second));
533 if (!UsedByAnother.count(I->first)) {
536 // Avoid iterator invalidation
537 unsigned first = I->first;
539 copy_set.erase(first);
545 LiveVariables& LV = getAnalysis<LiveVariables>();
546 MachineFunction* MF = MBB->getParent();
547 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
549 // Iterate over the worklist, inserting copies
550 while (!worklist.empty() || !copy_set.empty()) {
551 while (!worklist.empty()) {
552 std::pair<unsigned, unsigned> curr = *worklist.begin();
553 worklist.erase(curr.first);
555 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
557 if (isLiveOut(LV.getVarInfo(curr.second), MBB)) {
558 // Create a temporary
559 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
561 // Insert copy from curr.second to a temporary at
562 // the Phi defining curr.second
563 LiveVariables::VarInfo VI = LV.getVarInfo(curr.second);
564 MachineBasicBlock::iterator PI = VI.DefInst;
565 TII->copyRegToReg(*VI.DefInst->getParent(), PI, t,
566 curr.second, RC, RC);
568 // Push temporary on Stacks
569 Stacks[curr.second].push_back(t);
571 // Insert curr.second in pushed
572 pushed.insert(curr.second);
575 // Insert copy from map[curr.first] to curr.second
576 TII->copyRegToReg(*MBB, MBB->end(), curr.second,
577 map[curr.first], RC, RC);
578 map[curr.first] = curr.second;
580 // If curr.first is a destination in copy_set...
581 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
582 E = copy_set.end(); I != E; )
583 if (curr.first == I->second) {
584 std::pair<unsigned, unsigned> temp = *I;
586 // Avoid iterator invalidation
588 copy_set.erase(temp.first);
589 worklist.insert(temp);
597 if (!copy_set.empty()) {
598 std::pair<unsigned, unsigned> curr = *copy_set.begin();
599 copy_set.erase(curr.first);
601 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
603 // Insert a copy from dest to a new temporary t at the end of b
604 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
605 TII->copyRegToReg(*MBB, MBB->end(), t,
606 curr.second, RC, RC);
607 map[curr.second] = t;
609 worklist.insert(curr);
614 /// InsertCopies - insert copies into MBB and all of its successors
615 void StrongPHIElimination::InsertCopies(MachineBasicBlock* MBB,
616 std::set<MachineBasicBlock*>& visited) {
619 std::set<unsigned> pushed;
621 // Rewrite register uses from Stacks
622 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
624 for (unsigned i = 0; i < I->getNumOperands(); ++i)
625 if (I->getOperand(i).isRegister() &&
626 Stacks[I->getOperand(i).getReg()].size()) {
627 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
630 // Schedule the copies for this block
631 ScheduleCopies(MBB, pushed);
633 // Recur to our successors
634 for (GraphTraits<MachineBasicBlock*>::ChildIteratorType I =
635 GraphTraits<MachineBasicBlock*>::child_begin(MBB), E =
636 GraphTraits<MachineBasicBlock*>::child_end(MBB); I != E; ++I)
637 if (!visited.count(*I))
638 InsertCopies(*I, visited);
640 // As we exit this block, pop the names we pushed while processing it
641 for (std::set<unsigned>::iterator I = pushed.begin(),
642 E = pushed.end(); I != E; ++I)
643 Stacks[*I].pop_back();
646 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
647 // Compute DFS numbers of each block
650 // Determine which phi node operands need copies
651 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
653 I->begin()->getOpcode() == TargetInstrInfo::PHI)
657 // FIXME: This process should probably preserve LiveVariables
658 std::set<MachineBasicBlock*> visited;
659 InsertCopies(Fn.begin(), visited);
662 typedef std::map<unsigned, std::set<unsigned> > RenameSetType;
663 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
665 for (std::set<unsigned>::iterator SI = I->second.begin(),
666 SE = I->second.end(); SI != SE; ++SI)
667 Fn.getRegInfo().replaceRegWith(*SI, I->first);
669 // FIXME: Insert last-minute copies
672 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
673 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
675 if (BI->getOpcode() == TargetInstrInfo::PHI)
676 BI->eraseFromParent();