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 is a map from a PHI-defined register
56 // 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;
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;
64 // Store the DFS-in number of each block
65 DenseMap<MachineBasicBlock*, unsigned> preorder;
67 // Store the DFS-out number of each block
68 DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
70 bool runOnMachineFunction(MachineFunction &Fn);
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.addRequired<MachineDominatorTree>();
74 AU.addRequired<LiveIntervals>();
76 // TODO: Actually make this true.
77 AU.addPreserved<LiveIntervals>();
78 AU.addPreserved<RegisterCoalescer>();
79 MachineFunctionPass::getAnalysisUsage(AU);
82 virtual void releaseMemory() {
88 UsedByAnother.clear();
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.
97 struct DomForestNode {
99 // Store references to our children
100 std::vector<DomForestNode*> children;
101 // The register we represent
104 // Add another node as our child
105 void addChild(DomForestNode* DFN) { children.push_back(DFN); }
108 typedef std::vector<DomForestNode*>::iterator iterator;
110 // 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.
113 DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
115 parent->addChild(this);
119 for (iterator I = begin(), E = end(); I != E; ++I)
123 /// getReg - Return the regiser that this node represents
124 inline unsigned getReg() { return reg; }
126 // Provide iterator access to our children
127 inline DomForestNode::iterator begin() { return children.begin(); }
128 inline DomForestNode::iterator end() { return children.end(); }
131 void computeDFS(MachineFunction& MF);
132 void processBlock(MachineBasicBlock* MBB);
134 std::vector<DomForestNode*> computeDomForest(
135 std::map<unsigned, MachineBasicBlock*>& instrs,
136 MachineRegisterInfo& MRI);
137 void processPHIUnion(MachineInstr* Inst,
138 std::map<unsigned, MachineBasicBlock*>& PHIUnion,
139 std::vector<StrongPHIElimination::DomForestNode*>& DF,
140 std::vector<std::pair<unsigned, unsigned> >& locals);
141 void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
142 void InsertCopies(MachineDomTreeNode* MBB,
143 SmallPtrSet<MachineBasicBlock*, 16>& v);
144 void mergeLiveIntervals(unsigned primary, unsigned secondary);
148 char StrongPHIElimination::ID = 0;
149 static RegisterPass<StrongPHIElimination>
150 X("strong-phi-node-elimination",
151 "Eliminate PHI nodes for register allocation, intelligently");
153 const PassInfo *const llvm::StrongPHIEliminationID = &X;
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.
158 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
159 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
160 SmallPtrSet<MachineDomTreeNode*, 8> visited;
164 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
166 MachineDomTreeNode* node = DT.getRootNode();
168 std::vector<MachineDomTreeNode*> worklist;
169 worklist.push_back(node);
171 while (!worklist.empty()) {
172 MachineDomTreeNode* currNode = worklist.back();
174 if (!frontier.count(currNode)) {
175 frontier.insert(currNode);
177 preorder.insert(std::make_pair(currNode->getBlock(), time));
180 bool inserted = false;
181 for (MachineDomTreeNode::iterator I = currNode->begin(), E = currNode->end();
183 if (!frontier.count(*I) && !visited.count(*I)) {
184 worklist.push_back(*I);
190 frontier.erase(currNode);
191 visited.insert(currNode);
192 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
201 /// PreorderSorter - a helper class that is used to sort registers
202 /// according to the preorder number of their defining blocks
203 class PreorderSorter {
205 DenseMap<MachineBasicBlock*, unsigned>& preorder;
206 MachineRegisterInfo& MRI;
209 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
210 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
212 bool operator()(unsigned A, unsigned B) {
216 MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
217 MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
219 if (preorder[ABlock] < preorder[BBlock])
221 else if (preorder[ABlock] > preorder[BBlock])
230 /// computeDomForest - compute the subforest of the DomTree corresponding
231 /// to the defining blocks of the registers in question
232 std::vector<StrongPHIElimination::DomForestNode*>
233 StrongPHIElimination::computeDomForest(
234 std::map<unsigned, MachineBasicBlock*>& regs,
235 MachineRegisterInfo& MRI) {
236 // 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.
238 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
239 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
241 // Populate a worklist with the registers
242 std::vector<unsigned> worklist;
243 worklist.reserve(regs.size());
244 for (std::map<unsigned, MachineBasicBlock*>::iterator I = regs.begin(),
245 E = regs.end(); I != E; ++I)
246 worklist.push_back(I->first);
248 // Sort the registers by the DFS-in number of their defining block
249 PreorderSorter PS(preorder, MRI);
250 std::sort(worklist.begin(), worklist.end(), PS);
252 // Create a "current parent" stack, and put the virtual root on top of it
253 DomForestNode* CurrentParent = VirtualRoot;
254 std::vector<DomForestNode*> stack;
255 stack.push_back(VirtualRoot);
257 // Iterate over all the registers in the previously computed order
258 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
260 unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
261 MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
262 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
265 // 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.
267 while (pre > maxpreorder[parentBlock]) {
269 CurrentParent = stack.back();
271 parentBlock = CurrentParent->getReg() ?
272 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
276 // Now that we've found the appropriate parent, create a DomForestNode for
277 // this register and attach it to the forest
278 DomForestNode* child = new DomForestNode(*I, CurrentParent);
280 // Push this new node on the "current parent" stack
281 stack.push_back(child);
282 CurrentParent = child;
285 // Return a vector containing the children of the virtual root node
286 std::vector<DomForestNode*> ret;
287 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
291 /// isLiveIn - helper method that determines, from a regno, if a register
292 /// is live into a block
293 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
295 LiveInterval& I = LI.getOrCreateInterval(r);
296 unsigned idx = LI.getMBBStartIdx(MBB);
297 return I.liveBeforeAndAt(idx);
300 /// isLiveOut - help method that determines, from a regno, if a register is
301 /// live out of a block.
302 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
304 for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
305 E = MBB->succ_end(); PI != E; ++PI)
306 if (isLiveIn(r, *PI, LI))
312 /// 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
316 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
317 LiveIntervals& LV, unsigned mode) {
318 MachineInstr* def = 0;
319 MachineInstr* kill = 0;
321 // 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();
325 bool interference = false;
327 // Wallk the block, checking for interferences
328 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
330 MachineInstr* curr = MBI;
332 // Same defining block...
334 if (curr == MRI->getVRegDef(a)) {
335 // If we find our first definition, save it
338 // If there's already an unkilled definition, then
339 // this is an interference
343 // If there's a definition followed by a KillInst, then
344 // they can't interfere
346 interference = false;
349 // Symmetric with the above
350 } else if (curr == MRI->getVRegDef(b)) {
357 interference = false;
360 // Store KillInsts if they match up with the definition
361 } else if (curr->killsRegister(a)) {
362 if (def == MRI->getVRegDef(a)) {
364 } else if (curr->killsRegister(b)) {
365 if (def == MRI->getVRegDef(b)) {
370 // First properly dominates second...
371 } else if (mode == 1) {
372 if (curr == MRI->getVRegDef(b)) {
373 // Definition of second without kill of first is an interference
377 // Definition after a kill is a non-interference
379 interference = false;
382 // Save KillInsts of First
383 } else if (curr->killsRegister(a)) {
386 // Symmetric with the above
387 } else if (mode == 2) {
388 if (curr == MRI->getVRegDef(a)) {
393 interference = false;
396 } else if (curr->killsRegister(b)) {
405 /// 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
409 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
410 LiveIntervals& LI = getAnalysis<LiveIntervals>();
411 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
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;
417 // Iterate over all the PHI nodes in this block
418 MachineBasicBlock::iterator P = MBB->begin();
419 while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
420 unsigned DestReg = P->getOperand(0).getReg();
423 // Don't both doing PHI elimination for dead PHI's.
424 if (P->registerDefIsDead(DestReg)) {
429 LiveInterval& PI = LI.getOrCreateInterval(DestReg);
430 unsigned pIdx = LI.getDefIndex(LI.getInstructionIndex(P));
431 VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
432 PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
434 // 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.
438 std::map<unsigned, MachineBasicBlock*> PHIUnion;
439 SmallPtrSet<MachineBasicBlock*, 8> UnionedBlocks;
441 // Iterate over the operands of the PHI node
442 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
443 unsigned SrcReg = P->getOperand(i-1).getReg();
445 // Don't need to try to coalesce a register with itself.
446 if (SrcReg == DestReg) {
447 ProcessedNames.insert(SrcReg);
451 // 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
461 // 5) if any two operands are defined in the same block, insert copies
463 if (isLiveIn(SrcReg, P->getParent(), LI) ||
464 isLiveOut(P->getOperand(0).getReg(),
465 MRI.getVRegDef(SrcReg)->getParent(), LI) ||
466 ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
467 isLiveIn(P->getOperand(0).getReg(),
468 MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
469 ProcessedNames.count(SrcReg) ||
470 UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
472 // Add a copy for the selected register
473 MachineBasicBlock* From = P->getOperand(i).getMBB();
474 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
475 UsedByAnother.insert(SrcReg);
477 // Otherwise, add it to the renaming set
478 PHIUnion.insert(std::make_pair(SrcReg,P->getOperand(i).getMBB()));
479 UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
483 // 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
486 std::vector<StrongPHIElimination::DomForestNode*> DF =
487 computeDomForest(PHIUnion, MRI);
489 // 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.
492 std::vector<std::pair<unsigned, unsigned> > localInterferences;
493 processPHIUnion(P, PHIUnion, DF, localInterferences);
495 // 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
498 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
499 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()));
504 // The dominator forest walk may have returned some register pairs whose
505 // interference cannot be determined from dominator analysis. We now
506 // examine these pairs for local interferences.
507 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;
511 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
513 // Determine the block we need to scan and the relationship between
515 MachineBasicBlock* scan = 0;
517 if (MRI.getVRegDef(p.first)->getParent() ==
518 MRI.getVRegDef(p.second)->getParent()) {
519 scan = MRI.getVRegDef(p.first)->getParent();
520 mode = 0; // Same block
521 } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
522 MRI.getVRegDef(p.second)->getParent())) {
523 scan = MRI.getVRegDef(p.second)->getParent();
524 mode = 1; // First dominates second
526 scan = MRI.getVRegDef(p.first)->getParent();
527 mode = 2; // Second dominates first
530 // If there's an interference, we need to insert copies
531 if (interferes(p.first, p.second, scan, LI, mode)) {
532 // 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();
538 Waiting[From].insert(std::make_pair(SrcReg,
539 P->getOperand(0).getReg()));
540 UsedByAnother.insert(SrcReg);
542 PHIUnion.erase(SrcReg);
548 // Add the renaming set for this PHI node to our overall renaming information
549 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
551 // Remember which registers are already renamed, so that we don't try to
552 // rename them for another PHI node in this block
553 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
554 E = PHIUnion.end(); I != E; ++I)
555 ProcessedNames.insert(I->first);
561 /// processPHIUnion - Take a set of candidate registers to be coalesced when
562 /// 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.
565 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
566 std::map<unsigned, MachineBasicBlock*>& PHIUnion,
567 std::vector<StrongPHIElimination::DomForestNode*>& DF,
568 std::vector<std::pair<unsigned, unsigned> >& locals) {
570 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
571 SmallPtrSet<DomForestNode*, 4> visited;
573 // Code is still in SSA form, so we can use MRI::getVRegDef()
574 MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
576 LiveIntervals& LI = getAnalysis<LiveIntervals>();
577 unsigned DestReg = Inst->getOperand(0).getReg();
579 // DF walk on the DomForest
580 while (!worklist.empty()) {
581 DomForestNode* DFNode = worklist.back();
583 visited.insert(DFNode);
585 bool inserted = false;
586 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
588 DomForestNode* child = *CI;
590 // If the current node is live-out of the defining block of one of its
591 // 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.
595 if (isLiveOut(DFNode->getReg(),
596 MRI.getVRegDef(child->getReg())->getParent(), LI)) {
597 // Insert copies for parent
598 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
599 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
600 unsigned SrcReg = DFNode->getReg();
601 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
603 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
604 UsedByAnother.insert(SrcReg);
606 PHIUnion.erase(SrcReg);
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.
612 } else if (isLiveIn(DFNode->getReg(),
613 MRI.getVRegDef(child->getReg())->getParent(), LI) ||
614 MRI.getVRegDef(DFNode->getReg())->getParent() ==
615 MRI.getVRegDef(child->getReg())->getParent()) {
616 // Add (p, c) to possible local interferences
617 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
620 if (!visited.count(child)) {
621 worklist.push_back(child);
626 if (!inserted) worklist.pop_back();
630 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
631 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
634 /// Based on "Practical Improvements to the Construction and Destruction
635 /// of Static Single Assignment Form" by Briggs, et al.
636 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
637 std::set<unsigned>& pushed) {
638 // FIXME: This function needs to update LiveIntervals
639 std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
641 std::map<unsigned, unsigned> worklist;
642 std::map<unsigned, unsigned> map;
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));
650 if (!UsedByAnother.count(I->second)) {
653 // Avoid iterator invalidation
654 unsigned first = I->first;
656 copy_set.erase(first);
662 LiveIntervals& LI = getAnalysis<LiveIntervals>();
663 MachineFunction* MF = MBB->getParent();
664 MachineRegisterInfo& MRI = MF->getRegInfo();
665 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
667 SmallVector<std::pair<unsigned, MachineInstr*>, 4> InsertedPHIDests;
669 // 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);
675 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
677 if (isLiveOut(curr.second, MBB, LI)) {
678 // Create a temporary
679 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
681 // Insert copy from curr.second to a temporary at
682 // the Phi defining curr.second
683 MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
684 TII->copyRegToReg(*PI->getParent(), PI, t,
685 curr.second, RC, RC);
687 // Push temporary on Stacks
688 Stacks[curr.second].push_back(t);
690 // Insert curr.second in pushed
691 pushed.insert(curr.second);
693 // Create a live interval for this temporary
694 InsertedPHIDests.push_back(std::make_pair(t, --PI));
697 // Insert copy from map[curr.first] to curr.second
698 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
699 map[curr.first], RC, RC);
700 map[curr.first] = curr.second;
702 // 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));
707 // 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;
713 // Avoid iterator invalidation
715 copy_set.erase(temp.first);
716 worklist.insert(temp);
724 if (!copy_set.empty()) {
725 std::pair<unsigned, unsigned> curr = *copy_set.begin();
726 copy_set.erase(curr.first);
727 worklist.insert(curr);
729 LiveInterval& I = LI.getInterval(curr.second);
730 MachineBasicBlock::iterator term = MBB->getFirstTerminator();
732 if (term != MBB->end())
733 endIdx = LI.getInstructionIndex(term);
735 endIdx = LI.getMBBEndIdx(MBB);
737 if (I.liveAt(endIdx)) {
738 const TargetRegisterClass *RC =
739 MF->getRegInfo().getRegClass(curr.first);
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;
747 MachineBasicBlock::iterator TI = MBB->getFirstTerminator();
748 InsertedPHIDests.push_back(std::make_pair(t, --TI));
753 // Renumber the instructions so that we can perform the index computations
754 // needed to create new live intervals.
755 LI.computeNumbering();
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 =
764 InsertedPHIDests.begin(), E = InsertedPHIDests.end(); I != E; ++I) {
766 if (RegHandled.insert(I->first).second &&
767 !LI.getOrCreateInterval(I->first).liveAt(
768 LI.getMBBEndIdx(I->second->getParent())))
769 LI.addLiveRangeToEndOfBlock(I->first, I->second);
773 /// InsertCopies - insert copies into MBB and all of its successors
774 void StrongPHIElimination::InsertCopies(MachineDomTreeNode* MDTN,
775 SmallPtrSet<MachineBasicBlock*, 16>& visited) {
776 MachineBasicBlock* MBB = MDTN->getBlock();
779 std::set<unsigned> pushed;
781 LiveIntervals& LI = getAnalysis<LiveIntervals>();
782 // Rewrite register uses from Stacks
783 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
785 if (I->getOpcode() == TargetInstrInfo::PHI)
788 for (unsigned i = 0; i < I->getNumOperands(); ++i)
789 if (I->getOperand(i).isRegister() &&
790 Stacks[I->getOperand(i).getReg()].size()) {
791 // 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);
798 // Change the register
799 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
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)));
809 LiveRange LR (LI.getMBBStartIdx(I->getParent()),
810 LiveIntervals::getUseIndex(LI.getInstructionIndex(I)),
817 // Schedule the copies for this block
818 ScheduleCopies(MBB, pushed);
820 // 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()))
824 InsertCopies(*I, visited);
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();
832 void StrongPHIElimination::mergeLiveIntervals(unsigned primary,
833 unsigned secondary) {
835 LiveIntervals& LI = getAnalysis<LiveIntervals>();
836 LiveInterval& LHS = LI.getOrCreateInterval(primary);
837 LiveInterval& RHS = LI.getOrCreateInterval(secondary);
839 LI.computeNumbering();
841 SmallVector<VNInfo*, 4> VNSet (RHS.vni_begin(), RHS.vni_end());
842 DenseMap<VNInfo*, VNInfo*> VNMap;
843 for (SmallVector<VNInfo*, 4>::iterator VI = VNSet.begin(),
844 VE = VNSet.end(); VI != VE; ++VI) {
845 VNInfo* NewVN = LHS.getNextValue((*VI)->def,
847 LI.getVNInfoAllocator());
848 LHS.MergeValueInAsValue(RHS, *VI, NewVN);
849 RHS.removeValNo(*VI);
852 if (RHS.begin() == RHS.end())
853 LI.removeInterval(RHS.reg);
856 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
857 LiveIntervals& LI = getAnalysis<LiveIntervals>();
859 // Compute DFS numbers of each block
862 // Determine which phi node operands need copies
863 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
865 I->begin()->getOpcode() == TargetInstrInfo::PHI)
868 // 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*> >
873 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
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);
881 Waiting[OI->second].insert(std::make_pair(OI->first, I->first));
882 unsigned reg = OI->first;
884 I->second.erase(reg);
890 // FIXME: This process should probably preserve LiveIntervals
891 SmallPtrSet<MachineBasicBlock*, 16> visited;
892 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
893 InsertCopies(MDT.getRootNode(), visited);
896 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
898 while (I->second.size()) {
899 std::map<unsigned, MachineBasicBlock*>::iterator SI = I->second.begin();
901 if (SI->first != I->first) {
902 mergeLiveIntervals(I->first, SI->first);
903 Fn.getRegInfo().replaceRegWith(SI->first, I->first);
905 if (RenameSets.count(SI->first)) {
906 I->second.insert(RenameSets[SI->first].begin(),
907 RenameSets[SI->first].end());
908 RenameSets.erase(SI->first);
912 I->second.erase(SI->first);
915 // FIXME: Insert last-minute copies
918 std::vector<MachineInstr*> phis;
919 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
920 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
922 if (BI->getOpcode() == TargetInstrInfo::PHI)
926 for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
928 MachineInstr* PInstr = *(I++);
930 // 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);
937 unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
938 PI.removeRange(*PI.getLiveRangeContaining(idx), true);
941 // Trim live intervals of input registers. They are no longer live into
942 // 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.
944 for (unsigned i = 1; i < PInstr->getNumOperands(); i += 2) {
945 unsigned reg = PInstr->getOperand(i).getReg();
947 MachineBasicBlock* MBB = PInstr->getOperand(i+1).getMBB();
948 LiveInterval& InputI = LI.getInterval(reg);
949 if (MBB != PInstr->getParent() &&
950 InputI.liveAt(LI.getMBBStartIdx(PInstr->getParent())) &&
951 InputI.expiredAt(LI.getInstructionIndex(PInstr) +
952 LiveIntervals::InstrSlots::NUM))
953 InputI.removeRange(LI.getMBBStartIdx(PInstr->getParent()),
954 LI.getInstructionIndex(PInstr),
958 // 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);
968 LI.RemoveMachineInstrFromMaps(PInstr);
969 PInstr->eraseFromParent();
972 LI.computeNumbering();