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/LiveIntervalAnalysis.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/RegisterCoalescer.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/ADT/DepthFirstIterator.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Support/Compiler.h"
39 struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
40 static char ID; // Pass identification, replacement for typeid
41 StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
43 // Waiting stores, for each MBB, the set of copies that need to
44 // be inserted into that MBB
45 DenseMap<MachineBasicBlock*,
46 std::map<unsigned, unsigned> > Waiting;
48 // Stacks holds the renaming stack for each register
49 std::map<unsigned, std::vector<unsigned> > Stacks;
51 // Registers in UsedByAnother are PHI nodes that are themselves
52 // used as operands to another another PHI node
53 std::set<unsigned> UsedByAnother;
55 // RenameSets are the sets of operands (and their VNInfo IDs) to a PHI
56 // (the defining instruction of the key) that can be renamed without copies.
57 std::map<unsigned, std::map<unsigned, unsigned> > RenameSets;
59 // PhiValueNumber holds the ID numbers of the VNs for each phi that we're
60 // eliminating, indexed by the register defined by that phi.
61 std::map<unsigned, unsigned> PhiValueNumber;
63 // Store the DFS-in number of each block
64 DenseMap<MachineBasicBlock*, unsigned> preorder;
66 // Store the DFS-out number of each block
67 DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
69 bool runOnMachineFunction(MachineFunction &Fn);
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72 AU.addRequired<MachineDominatorTree>();
73 AU.addRequired<LiveIntervals>();
75 // TODO: Actually make this true.
76 AU.addPreserved<LiveIntervals>();
77 AU.addPreserved<RegisterCoalescer>();
78 MachineFunctionPass::getAnalysisUsage(AU);
81 virtual void releaseMemory() {
87 UsedByAnother.clear();
93 /// DomForestNode - Represents a node in the "dominator forest". This is
94 /// a forest in which the nodes represent registers and the edges
95 /// represent a dominance relation in the block defining those registers.
96 struct DomForestNode {
98 // Store references to our children
99 std::vector<DomForestNode*> children;
100 // The register we represent
103 // Add another node as our child
104 void addChild(DomForestNode* DFN) { children.push_back(DFN); }
107 typedef std::vector<DomForestNode*>::iterator iterator;
109 // Create a DomForestNode by providing the register it represents, and
110 // the node to be its parent. The virtual root node has register 0
111 // and a null parent.
112 DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
114 parent->addChild(this);
118 for (iterator I = begin(), E = end(); I != E; ++I)
122 /// getReg - Return the regiser that this node represents
123 inline unsigned getReg() { return reg; }
125 // Provide iterator access to our children
126 inline DomForestNode::iterator begin() { return children.begin(); }
127 inline DomForestNode::iterator end() { return children.end(); }
130 void computeDFS(MachineFunction& MF);
131 void processBlock(MachineBasicBlock* MBB);
133 std::vector<DomForestNode*> computeDomForest(std::map<unsigned, unsigned>& instrs,
134 MachineRegisterInfo& MRI);
135 void processPHIUnion(MachineInstr* Inst,
136 std::map<unsigned, unsigned>& PHIUnion,
137 std::vector<StrongPHIElimination::DomForestNode*>& DF,
138 std::vector<std::pair<unsigned, unsigned> >& locals);
139 void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
140 void InsertCopies(MachineBasicBlock* MBB,
141 SmallPtrSet<MachineBasicBlock*, 16>& v);
142 void mergeLiveIntervals(unsigned primary, unsigned secondary, unsigned VN);
146 char StrongPHIElimination::ID = 0;
147 static RegisterPass<StrongPHIElimination>
148 X("strong-phi-node-elimination",
149 "Eliminate PHI nodes for register allocation, intelligently");
151 const PassInfo *const llvm::StrongPHIEliminationID = &X;
153 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
154 /// of the given MachineFunction. These numbers are then used in other parts
155 /// of the PHI elimination process.
156 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
157 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
158 SmallPtrSet<MachineDomTreeNode*, 8> visited;
162 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
164 MachineDomTreeNode* node = DT.getRootNode();
166 std::vector<MachineDomTreeNode*> worklist;
167 worklist.push_back(node);
169 while (!worklist.empty()) {
170 MachineDomTreeNode* currNode = worklist.back();
172 if (!frontier.count(currNode)) {
173 frontier.insert(currNode);
175 preorder.insert(std::make_pair(currNode->getBlock(), time));
178 bool inserted = false;
179 for (MachineDomTreeNode::iterator I = currNode->begin(), E = currNode->end();
181 if (!frontier.count(*I) && !visited.count(*I)) {
182 worklist.push_back(*I);
188 frontier.erase(currNode);
189 visited.insert(currNode);
190 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
199 /// PreorderSorter - a helper class that is used to sort registers
200 /// according to the preorder number of their defining blocks
201 class PreorderSorter {
203 DenseMap<MachineBasicBlock*, unsigned>& preorder;
204 MachineRegisterInfo& MRI;
207 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
208 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
210 bool operator()(unsigned A, unsigned B) {
214 MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
215 MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
217 if (preorder[ABlock] < preorder[BBlock])
219 else if (preorder[ABlock] > preorder[BBlock])
228 /// computeDomForest - compute the subforest of the DomTree corresponding
229 /// to the defining blocks of the registers in question
230 std::vector<StrongPHIElimination::DomForestNode*>
231 StrongPHIElimination::computeDomForest(std::map<unsigned, unsigned>& regs,
232 MachineRegisterInfo& MRI) {
233 // Begin by creating a virtual root node, since the actual results
234 // may well be a forest. Assume this node has maximum DFS-out number.
235 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
236 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
238 // Populate a worklist with the registers
239 std::vector<unsigned> worklist;
240 worklist.reserve(regs.size());
241 for (std::map<unsigned, unsigned>::iterator I = regs.begin(), E = regs.end();
243 worklist.push_back(I->first);
245 // Sort the registers by the DFS-in number of their defining block
246 PreorderSorter PS(preorder, MRI);
247 std::sort(worklist.begin(), worklist.end(), PS);
249 // Create a "current parent" stack, and put the virtual root on top of it
250 DomForestNode* CurrentParent = VirtualRoot;
251 std::vector<DomForestNode*> stack;
252 stack.push_back(VirtualRoot);
254 // Iterate over all the registers in the previously computed order
255 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
257 unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
258 MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
259 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
262 // If the DFS-in number of the register is greater than the DFS-out number
263 // of the current parent, repeatedly pop the parent stack until it isn't.
264 while (pre > maxpreorder[parentBlock]) {
266 CurrentParent = stack.back();
268 parentBlock = CurrentParent->getReg() ?
269 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
273 // Now that we've found the appropriate parent, create a DomForestNode for
274 // this register and attach it to the forest
275 DomForestNode* child = new DomForestNode(*I, CurrentParent);
277 // Push this new node on the "current parent" stack
278 stack.push_back(child);
279 CurrentParent = child;
282 // Return a vector containing the children of the virtual root node
283 std::vector<DomForestNode*> ret;
284 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
288 /// isLiveIn - helper method that determines, from a regno, if a register
289 /// is live into a block
290 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
292 LiveInterval& I = LI.getOrCreateInterval(r);
293 unsigned idx = LI.getMBBStartIdx(MBB);
294 return I.liveBeforeAndAt(idx);
297 /// isLiveOut - help method that determines, from a regno, if a register is
298 /// live out of a block.
299 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
301 for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
302 E = MBB->succ_end(); PI != E; ++PI) {
303 if (isLiveIn(r, *PI, LI))
310 /// interferes - checks for local interferences by scanning a block. The only
311 /// trick parameter is 'mode' which tells it the relationship of the two
312 /// registers. 0 - defined in the same block, 1 - first properly dominates
313 /// second, 2 - second properly dominates first
314 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
315 LiveIntervals& LV, unsigned mode) {
316 MachineInstr* def = 0;
317 MachineInstr* kill = 0;
319 // The code is still in SSA form at this point, so there is only one
320 // definition per VReg. Thus we can safely use MRI->getVRegDef().
321 const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
323 bool interference = false;
325 // Wallk the block, checking for interferences
326 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
328 MachineInstr* curr = MBI;
330 // Same defining block...
332 if (curr == MRI->getVRegDef(a)) {
333 // If we find our first definition, save it
336 // If there's already an unkilled definition, then
337 // this is an interference
341 // If there's a definition followed by a KillInst, then
342 // they can't interfere
344 interference = false;
347 // Symmetric with the above
348 } else if (curr == MRI->getVRegDef(b)) {
355 interference = false;
358 // Store KillInsts if they match up with the definition
359 } else if (curr->killsRegister(a)) {
360 if (def == MRI->getVRegDef(a)) {
362 } else if (curr->killsRegister(b)) {
363 if (def == MRI->getVRegDef(b)) {
368 // First properly dominates second...
369 } else if (mode == 1) {
370 if (curr == MRI->getVRegDef(b)) {
371 // Definition of second without kill of first is an interference
375 // Definition after a kill is a non-interference
377 interference = false;
380 // Save KillInsts of First
381 } else if (curr->killsRegister(a)) {
384 // Symmetric with the above
385 } else if (mode == 2) {
386 if (curr == MRI->getVRegDef(a)) {
391 interference = false;
394 } else if (curr->killsRegister(b)) {
403 /// processBlock - Determine how to break up PHIs in the current block. Each
404 /// PHI is broken up by some combination of renaming its operands and inserting
405 /// copies. This method is responsible for determining which operands receive
407 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
408 LiveIntervals& LI = getAnalysis<LiveIntervals>();
409 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
411 // Holds names that have been added to a set in any PHI within this block
412 // before the current one.
413 std::set<unsigned> ProcessedNames;
415 // Iterate over all the PHI nodes in this block
416 MachineBasicBlock::iterator P = MBB->begin();
417 while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
418 unsigned DestReg = P->getOperand(0).getReg();
420 // Don't both doing PHI elimination for dead PHI's.
421 if (P->registerDefIsDead(DestReg)) {
426 LiveInterval& PI = LI.getOrCreateInterval(DestReg);
427 unsigned pIdx = LI.getDefIndex(LI.getInstructionIndex(P));
428 VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
429 PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
431 // PHIUnion is the set of incoming registers to the PHI node that
432 // are going to be renames rather than having copies inserted. This set
433 // is refinded over the course of this function. UnionedBlocks is the set
434 // of corresponding MBBs.
435 std::map<unsigned, unsigned> PHIUnion;
436 SmallPtrSet<MachineBasicBlock*, 8> UnionedBlocks;
438 // Iterate over the operands of the PHI node
439 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
440 unsigned SrcReg = P->getOperand(i-1).getReg();
442 // Check for trivial interferences via liveness information, allowing us
443 // to avoid extra work later. Any registers that interfere cannot both
444 // be in the renaming set, so choose one and add copies for it instead.
445 // The conditions are:
446 // 1) if the operand is live into the PHI node's block OR
447 // 2) if the PHI node is live out of the operand's defining block OR
448 // 3) if the operand is itself a PHI node and the original PHI is
449 // live into the operand's defining block OR
450 // 4) if the operand is already being renamed for another PHI node
452 // 5) if any two operands are defined in the same block, insert copies
454 if (isLiveIn(SrcReg, P->getParent(), LI) ||
455 isLiveOut(P->getOperand(0).getReg(),
456 MRI.getVRegDef(SrcReg)->getParent(), LI) ||
457 ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
458 isLiveIn(P->getOperand(0).getReg(),
459 MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
460 ProcessedNames.count(SrcReg) ||
461 UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
463 // Add a copy for the selected register
464 MachineBasicBlock* From = P->getOperand(i).getMBB();
465 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
466 UsedByAnother.insert(SrcReg);
468 // Otherwise, add it to the renaming set
469 LiveInterval& I = LI.getOrCreateInterval(SrcReg);
470 unsigned idx = LI.getMBBEndIdx(P->getOperand(i).getMBB());
471 VNInfo* VN = I.getLiveRangeContaining(idx)->valno;
473 assert(VN && "No VNInfo for register?");
475 PHIUnion.insert(std::make_pair(SrcReg, VN->id));
476 UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
480 // Compute the dominator forest for the renaming set. This is a forest
481 // where the nodes are the registers and the edges represent dominance
482 // relations between the defining blocks of the registers
483 std::vector<StrongPHIElimination::DomForestNode*> DF =
484 computeDomForest(PHIUnion, MRI);
486 // Walk DomForest to resolve interferences at an inter-block level. This
487 // will remove registers from the renaming set (and insert copies for them)
488 // if interferences are found.
489 std::vector<std::pair<unsigned, unsigned> > localInterferences;
490 processPHIUnion(P, PHIUnion, DF, localInterferences);
492 // If one of the inputs is defined in the same block as the current PHI
493 // then we need to check for a local interference between that input and
495 for (std::map<unsigned, unsigned>::iterator I = PHIUnion.begin(),
496 E = PHIUnion.end(); I != E; ++I)
497 if (MRI.getVRegDef(I->first)->getParent() == P->getParent())
498 localInterferences.push_back(std::make_pair(I->first,
499 P->getOperand(0).getReg()));
501 // The dominator forest walk may have returned some register pairs whose
502 // interference cannot be determined from dominator analysis. We now
503 // examine these pairs for local interferences.
504 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
505 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
506 std::pair<unsigned, unsigned> p = *I;
508 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
510 // Determine the block we need to scan and the relationship between
512 MachineBasicBlock* scan = 0;
514 if (MRI.getVRegDef(p.first)->getParent() ==
515 MRI.getVRegDef(p.second)->getParent()) {
516 scan = MRI.getVRegDef(p.first)->getParent();
517 mode = 0; // Same block
518 } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
519 MRI.getVRegDef(p.second)->getParent())) {
520 scan = MRI.getVRegDef(p.second)->getParent();
521 mode = 1; // First dominates second
523 scan = MRI.getVRegDef(p.first)->getParent();
524 mode = 2; // Second dominates first
527 // If there's an interference, we need to insert copies
528 if (interferes(p.first, p.second, scan, LI, mode)) {
529 // Insert copies for First
530 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
531 if (P->getOperand(i-1).getReg() == p.first) {
532 unsigned SrcReg = p.first;
533 MachineBasicBlock* From = P->getOperand(i).getMBB();
535 Waiting[From].insert(std::make_pair(SrcReg,
536 P->getOperand(0).getReg()));
537 UsedByAnother.insert(SrcReg);
539 PHIUnion.erase(SrcReg);
545 // Add the renaming set for this PHI node to our overall renaming information
546 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
548 // Remember which registers are already renamed, so that we don't try to
549 // rename them for another PHI node in this block
550 for (std::map<unsigned, unsigned>::iterator I = PHIUnion.begin(),
551 E = PHIUnion.end(); I != E; ++I)
552 ProcessedNames.insert(I->first);
558 /// processPHIUnion - Take a set of candidate registers to be coalesced when
559 /// decomposing the PHI instruction. Use the DominanceForest to remove the ones
560 /// that are known to interfere, and flag others that need to be checked for
561 /// local interferences.
562 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
563 std::map<unsigned, unsigned>& PHIUnion,
564 std::vector<StrongPHIElimination::DomForestNode*>& DF,
565 std::vector<std::pair<unsigned, unsigned> >& locals) {
567 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
568 SmallPtrSet<DomForestNode*, 4> visited;
570 // Code is still in SSA form, so we can use MRI::getVRegDef()
571 MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
573 LiveIntervals& LI = getAnalysis<LiveIntervals>();
574 unsigned DestReg = Inst->getOperand(0).getReg();
576 // DF walk on the DomForest
577 while (!worklist.empty()) {
578 DomForestNode* DFNode = worklist.back();
580 visited.insert(DFNode);
582 bool inserted = false;
583 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
585 DomForestNode* child = *CI;
587 // If the current node is live-out of the defining block of one of its
588 // children, insert a copy for it. NOTE: The paper actually calls for
589 // a more elaborate heuristic for determining whether to insert copies
590 // for the child or the parent. In the interest of simplicity, we're
591 // just always choosing the parent.
592 if (isLiveOut(DFNode->getReg(),
593 MRI.getVRegDef(child->getReg())->getParent(), LI)) {
594 // Insert copies for parent
595 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
596 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
597 unsigned SrcReg = DFNode->getReg();
598 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
600 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
601 UsedByAnother.insert(SrcReg);
603 PHIUnion.erase(SrcReg);
607 // If a node is live-in to the defining block of one of its children, but
608 // not live-out, then we need to scan that block for local interferences.
609 } else if (isLiveIn(DFNode->getReg(),
610 MRI.getVRegDef(child->getReg())->getParent(), LI) ||
611 MRI.getVRegDef(DFNode->getReg())->getParent() ==
612 MRI.getVRegDef(child->getReg())->getParent()) {
613 // Add (p, c) to possible local interferences
614 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
617 if (!visited.count(child)) {
618 worklist.push_back(child);
623 if (!inserted) worklist.pop_back();
627 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
628 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
631 /// Based on "Practical Improvements to the Construction and Destruction
632 /// of Static Single Assignment Form" by Briggs, et al.
633 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
634 std::set<unsigned>& pushed) {
635 // FIXME: This function needs to update LiveVariables
636 std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
638 std::map<unsigned, unsigned> worklist;
639 std::map<unsigned, unsigned> map;
641 // Setup worklist of initial copies
642 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
643 E = copy_set.end(); I != E; ) {
644 map.insert(std::make_pair(I->first, I->first));
645 map.insert(std::make_pair(I->second, I->second));
647 if (!UsedByAnother.count(I->second)) {
650 // Avoid iterator invalidation
651 unsigned first = I->first;
653 copy_set.erase(first);
659 LiveIntervals& LI = getAnalysis<LiveIntervals>();
660 MachineFunction* MF = MBB->getParent();
661 MachineRegisterInfo& MRI = MF->getRegInfo();
662 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
664 // Iterate over the worklist, inserting copies
665 while (!worklist.empty() || !copy_set.empty()) {
666 while (!worklist.empty()) {
667 std::pair<unsigned, unsigned> curr = *worklist.begin();
668 worklist.erase(curr.first);
670 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
672 if (isLiveOut(curr.second, MBB, LI)) {
673 // Create a temporary
674 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
676 // Insert copy from curr.second to a temporary at
677 // the Phi defining curr.second
678 MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
679 TII->copyRegToReg(*PI->getParent(), PI, t,
680 curr.second, RC, RC);
682 // Push temporary on Stacks
683 Stacks[curr.second].push_back(t);
685 // Insert curr.second in pushed
686 pushed.insert(curr.second);
689 // Insert copy from map[curr.first] to curr.second
690 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
691 map[curr.first], RC, RC);
692 map[curr.first] = curr.second;
694 // If curr.first is a destination in copy_set...
695 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
696 E = copy_set.end(); I != E; )
697 if (curr.first == I->second) {
698 std::pair<unsigned, unsigned> temp = *I;
700 // Avoid iterator invalidation
702 copy_set.erase(temp.first);
703 worklist.insert(temp);
711 if (!copy_set.empty()) {
712 std::pair<unsigned, unsigned> curr = *copy_set.begin();
713 copy_set.erase(curr.first);
715 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
717 // Insert a copy from dest to a new temporary t at the end of b
718 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
719 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
720 curr.second, RC, RC);
721 map[curr.second] = t;
723 worklist.insert(curr);
728 /// InsertCopies - insert copies into MBB and all of its successors
729 void StrongPHIElimination::InsertCopies(MachineBasicBlock* MBB,
730 SmallPtrSet<MachineBasicBlock*, 16>& visited) {
733 std::set<unsigned> pushed;
735 // Rewrite register uses from Stacks
736 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
738 for (unsigned i = 0; i < I->getNumOperands(); ++i)
739 if (I->getOperand(i).isRegister() &&
740 Stacks[I->getOperand(i).getReg()].size()) {
741 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
744 // Schedule the copies for this block
745 ScheduleCopies(MBB, pushed);
747 // Recur to our successors
748 for (GraphTraits<MachineBasicBlock*>::ChildIteratorType I =
749 GraphTraits<MachineBasicBlock*>::child_begin(MBB), E =
750 GraphTraits<MachineBasicBlock*>::child_end(MBB); I != E; ++I)
751 if (!visited.count(*I))
752 InsertCopies(*I, visited);
754 // As we exit this block, pop the names we pushed while processing it
755 for (std::set<unsigned>::iterator I = pushed.begin(),
756 E = pushed.end(); I != E; ++I)
757 Stacks[*I].pop_back();
760 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
761 /// compute what the resultant value numbers for each value in the input two
762 /// ranges will be. This is complicated by copies between the two which can
763 /// and will commonly cause multiple value numbers to be merged into one.
765 /// VN is the value number that we're trying to resolve. InstDefiningValue
766 /// keeps track of the new InstDefiningValue assignment for the result
767 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
768 /// whether a value in this or other is a copy from the opposite set.
769 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
770 /// already been assigned.
772 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
773 /// contains the value number the copy is from.
775 static unsigned ComputeUltimateVN(VNInfo *VNI,
776 SmallVector<VNInfo*, 16> &NewVNInfo,
777 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
778 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
779 SmallVector<int, 16> &ThisValNoAssignments,
780 SmallVector<int, 16> &OtherValNoAssignments) {
781 unsigned VN = VNI->id;
783 // If the VN has already been computed, just return it.
784 if (ThisValNoAssignments[VN] >= 0)
785 return ThisValNoAssignments[VN];
786 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
788 // If this val is not a copy from the other val, then it must be a new value
789 // number in the destination.
790 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
791 if (I == ThisFromOther.end()) {
792 NewVNInfo.push_back(VNI);
793 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
795 VNInfo *OtherValNo = I->second;
797 // Otherwise, this *is* a copy from the RHS. If the other side has already
798 // been computed, return it.
799 if (OtherValNoAssignments[OtherValNo->id] >= 0)
800 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
802 // Mark this value number as currently being computed, then ask what the
803 // ultimate value # of the other value is.
804 ThisValNoAssignments[VN] = -2;
805 unsigned UltimateVN =
806 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
807 OtherValNoAssignments, ThisValNoAssignments);
808 return ThisValNoAssignments[VN] = UltimateVN;
811 void StrongPHIElimination::mergeLiveIntervals(unsigned primary,
813 unsigned secondaryVN) {
815 LiveIntervals& LI = getAnalysis<LiveIntervals>();
816 LiveInterval& LHS = LI.getOrCreateInterval(primary);
817 LiveInterval& RHS = LI.getOrCreateInterval(secondary);
819 // Compute the final value assignment, assuming that the live ranges can be
821 SmallVector<int, 16> LHSValNoAssignments;
822 SmallVector<int, 16> RHSValNoAssignments;
823 SmallVector<VNInfo*, 16> NewVNInfo;
825 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
826 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
827 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
829 for (LiveInterval::vni_iterator I = LHS.vni_begin(), E = LHS.vni_end();
832 unsigned VN = VNI->id;
833 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
836 NewVNInfo.push_back(VNI);
837 LHSValNoAssignments[VN] = NewVNInfo.size()-1;
840 for (LiveInterval::vni_iterator I = RHS.vni_begin(), E = RHS.vni_end();
843 unsigned VN = VNI->id;
844 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
847 NewVNInfo.push_back(VNI);
848 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
851 // If we get here, we know that we can coalesce the live ranges. Ask the
852 // intervals to coalesce themselves now.
854 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
855 LI.removeInterval(secondary);
857 // The valno that was previously the input to the PHI node
858 // now has a PHIKill.
859 LHS.getValNumInfo(RHSValNoAssignments[secondaryVN])->hasPHIKill = true;
862 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
863 LiveIntervals& LI = getAnalysis<LiveIntervals>();
865 // Compute DFS numbers of each block
868 // Determine which phi node operands need copies
869 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
871 I->begin()->getOpcode() == TargetInstrInfo::PHI)
875 // FIXME: This process should probably preserve LiveVariables
876 SmallPtrSet<MachineBasicBlock*, 16> visited;
877 InsertCopies(Fn.begin(), visited);
880 typedef std::map<unsigned, std::map<unsigned, unsigned> > RenameSetType;
881 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
883 for (std::map<unsigned, unsigned>::iterator SI = I->second.begin(),
884 SE = I->second.end(); SI != SE; ++SI) {
885 mergeLiveIntervals(I->first, SI->first, SI->second);
886 Fn.getRegInfo().replaceRegWith(SI->first, I->first);
889 // FIXME: Insert last-minute copies
892 std::vector<MachineInstr*> phis;
893 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
894 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
896 if (BI->getOpcode() == TargetInstrInfo::PHI)
900 for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
902 MachineInstr* PInstr = *(I++);
904 // If this is a dead PHI node, then remove it from LiveIntervals.
905 unsigned DestReg = PInstr->getOperand(0).getReg();
906 LiveInterval& PI = LI.getInterval(DestReg);
907 if (PInstr->registerDefIsDead(DestReg)) {
908 if (PI.containsOneValue()) {
909 LI.removeInterval(DestReg);
911 unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
912 PI.removeRange(*PI.getLiveRangeContaining(idx), true);
915 // If the PHI is not dead, then the valno defined by the PHI
916 // now has an unknown def.
917 unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
918 PI.getLiveRangeContaining(idx)->valno->def = ~0U;
921 LI.RemoveMachineInstrFromMaps(PInstr);
922 PInstr->eraseFromParent();
925 LI.computeNumbering();