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/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/RegisterCoalescer.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/ADT/DepthFirstIterator.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Support/Debug.h"
40 struct StrongPHIElimination : public MachineFunctionPass {
41 static char ID; // Pass identification, replacement for typeid
42 StrongPHIElimination() : MachineFunctionPass(ID) {}
44 // Waiting stores, for each MBB, the set of copies that need to
45 // be inserted into that MBB
46 DenseMap<MachineBasicBlock*,
47 std::multimap<unsigned, unsigned> > Waiting;
49 // Stacks holds the renaming stack for each register
50 std::map<unsigned, std::vector<unsigned> > Stacks;
52 // Registers in UsedByAnother are PHI nodes that are themselves
53 // used as operands to another PHI node
54 std::set<unsigned> UsedByAnother;
56 // RenameSets are the is a map from a PHI-defined register
57 // to the input registers to be coalesced along with the
58 // predecessor block for those input registers.
59 std::map<unsigned, std::map<unsigned, MachineBasicBlock*> > RenameSets;
61 // PhiValueNumber holds the ID numbers of the VNs for each phi that we're
62 // eliminating, indexed by the register defined by that phi.
63 std::map<unsigned, unsigned> PhiValueNumber;
65 // Store the DFS-in number of each block
66 DenseMap<MachineBasicBlock*, unsigned> preorder;
68 // Store the DFS-out number of each block
69 DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
71 bool runOnMachineFunction(MachineFunction &Fn);
73 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addRequired<MachineDominatorTree>();
76 AU.addRequired<SlotIndexes>();
77 AU.addPreserved<SlotIndexes>();
78 AU.addRequired<LiveIntervals>();
80 // TODO: Actually make this true.
81 AU.addPreserved<LiveIntervals>();
82 AU.addPreserved<RegisterCoalescer>();
83 MachineFunctionPass::getAnalysisUsage(AU);
86 virtual void releaseMemory() {
92 UsedByAnother.clear();
98 /// DomForestNode - Represents a node in the "dominator forest". This is
99 /// a forest in which the nodes represent registers and the edges
100 /// represent a dominance relation in the block defining those registers.
101 struct DomForestNode {
103 // Store references to our children
104 std::vector<DomForestNode*> children;
105 // The register we represent
108 // Add another node as our child
109 void addChild(DomForestNode* DFN) { children.push_back(DFN); }
112 typedef std::vector<DomForestNode*>::iterator iterator;
114 // Create a DomForestNode by providing the register it represents, and
115 // the node to be its parent. The virtual root node has register 0
116 // and a null parent.
117 DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
119 parent->addChild(this);
123 for (iterator I = begin(), E = end(); I != E; ++I)
127 /// getReg - Return the regiser that this node represents
128 inline unsigned getReg() { return reg; }
130 // Provide iterator access to our children
131 inline DomForestNode::iterator begin() { return children.begin(); }
132 inline DomForestNode::iterator end() { return children.end(); }
135 void computeDFS(MachineFunction& MF);
136 void processBlock(MachineBasicBlock* MBB);
138 std::vector<DomForestNode*> computeDomForest(
139 std::map<unsigned, MachineBasicBlock*>& instrs,
140 MachineRegisterInfo& MRI);
141 void processPHIUnion(MachineInstr* Inst,
142 std::map<unsigned, MachineBasicBlock*>& PHIUnion,
143 std::vector<StrongPHIElimination::DomForestNode*>& DF,
144 std::vector<std::pair<unsigned, unsigned> >& locals);
145 void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
146 void InsertCopies(MachineDomTreeNode* MBB,
147 SmallPtrSet<MachineBasicBlock*, 16>& v);
148 bool mergeLiveIntervals(unsigned primary, unsigned secondary);
152 char StrongPHIElimination::ID = 0;
153 INITIALIZE_PASS_BEGIN(StrongPHIElimination, "strong-phi-node-elimination",
154 "Eliminate PHI nodes for register allocation, intelligently", false, false)
155 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
156 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
157 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
158 INITIALIZE_PASS_END(StrongPHIElimination, "strong-phi-node-elimination",
159 "Eliminate PHI nodes for register allocation, intelligently", false, false)
161 char &llvm::StrongPHIEliminationID = StrongPHIElimination::ID;
163 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
164 /// of the given MachineFunction. These numbers are then used in other parts
165 /// of the PHI elimination process.
166 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
167 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
168 SmallPtrSet<MachineDomTreeNode*, 8> visited;
172 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
174 MachineDomTreeNode* node = DT.getRootNode();
176 std::vector<MachineDomTreeNode*> worklist;
177 worklist.push_back(node);
179 while (!worklist.empty()) {
180 MachineDomTreeNode* currNode = worklist.back();
182 if (!frontier.count(currNode)) {
183 frontier.insert(currNode);
185 preorder.insert(std::make_pair(currNode->getBlock(), time));
188 bool inserted = false;
189 for (MachineDomTreeNode::iterator I = currNode->begin(), E = currNode->end();
191 if (!frontier.count(*I) && !visited.count(*I)) {
192 worklist.push_back(*I);
198 frontier.erase(currNode);
199 visited.insert(currNode);
200 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
209 /// PreorderSorter - a helper class that is used to sort registers
210 /// according to the preorder number of their defining blocks
211 class PreorderSorter {
213 DenseMap<MachineBasicBlock*, unsigned>& preorder;
214 MachineRegisterInfo& MRI;
217 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
218 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
220 bool operator()(unsigned A, unsigned B) {
224 MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
225 MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
227 if (preorder[ABlock] < preorder[BBlock])
229 else if (preorder[ABlock] > preorder[BBlock])
238 /// computeDomForest - compute the subforest of the DomTree corresponding
239 /// to the defining blocks of the registers in question
240 std::vector<StrongPHIElimination::DomForestNode*>
241 StrongPHIElimination::computeDomForest(
242 std::map<unsigned, MachineBasicBlock*>& regs,
243 MachineRegisterInfo& MRI) {
244 // Begin by creating a virtual root node, since the actual results
245 // may well be a forest. Assume this node has maximum DFS-out number.
246 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
247 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
249 // Populate a worklist with the registers
250 std::vector<unsigned> worklist;
251 worklist.reserve(regs.size());
252 for (std::map<unsigned, MachineBasicBlock*>::iterator I = regs.begin(),
253 E = regs.end(); I != E; ++I)
254 worklist.push_back(I->first);
256 // Sort the registers by the DFS-in number of their defining block
257 PreorderSorter PS(preorder, MRI);
258 std::sort(worklist.begin(), worklist.end(), PS);
260 // Create a "current parent" stack, and put the virtual root on top of it
261 DomForestNode* CurrentParent = VirtualRoot;
262 std::vector<DomForestNode*> stack;
263 stack.push_back(VirtualRoot);
265 // Iterate over all the registers in the previously computed order
266 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
268 unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
269 MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
270 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
273 // If the DFS-in number of the register is greater than the DFS-out number
274 // of the current parent, repeatedly pop the parent stack until it isn't.
275 while (pre > maxpreorder[parentBlock]) {
277 CurrentParent = stack.back();
279 parentBlock = CurrentParent->getReg() ?
280 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
284 // Now that we've found the appropriate parent, create a DomForestNode for
285 // this register and attach it to the forest
286 DomForestNode* child = new DomForestNode(*I, CurrentParent);
288 // Push this new node on the "current parent" stack
289 stack.push_back(child);
290 CurrentParent = child;
293 // Return a vector containing the children of the virtual root node
294 std::vector<DomForestNode*> ret;
295 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
299 /// isLiveIn - helper method that determines, from a regno, if a register
300 /// is live into a block
301 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
303 LiveInterval& I = LI.getOrCreateInterval(r);
304 SlotIndex idx = LI.getMBBStartIdx(MBB);
305 return I.liveAt(idx);
308 /// isLiveOut - help method that determines, from a regno, if a register is
309 /// live out of a block.
310 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
312 for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
313 E = MBB->succ_end(); PI != E; ++PI)
314 if (isLiveIn(r, *PI, LI))
320 /// interferes - checks for local interferences by scanning a block. The only
321 /// trick parameter is 'mode' which tells it the relationship of the two
322 /// registers. 0 - defined in the same block, 1 - first properly dominates
323 /// second, 2 - second properly dominates first
324 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
325 LiveIntervals& LV, unsigned mode) {
326 MachineInstr* def = 0;
327 MachineInstr* kill = 0;
329 // The code is still in SSA form at this point, so there is only one
330 // definition per VReg. Thus we can safely use MRI->getVRegDef().
331 const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
333 bool interference = false;
335 // Wallk the block, checking for interferences
336 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
338 MachineInstr* curr = MBI;
340 // Same defining block...
342 if (curr == MRI->getVRegDef(a)) {
343 // If we find our first definition, save it
346 // If there's already an unkilled definition, then
347 // this is an interference
351 // If there's a definition followed by a KillInst, then
352 // they can't interfere
354 interference = false;
357 // Symmetric with the above
358 } else if (curr == MRI->getVRegDef(b)) {
365 interference = false;
368 // Store KillInsts if they match up with the definition
369 } else if (curr->killsRegister(a)) {
370 if (def == MRI->getVRegDef(a)) {
372 } else if (curr->killsRegister(b)) {
373 if (def == MRI->getVRegDef(b)) {
378 // First properly dominates second...
379 } else if (mode == 1) {
380 if (curr == MRI->getVRegDef(b)) {
381 // Definition of second without kill of first is an interference
385 // Definition after a kill is a non-interference
387 interference = false;
390 // Save KillInsts of First
391 } else if (curr->killsRegister(a)) {
394 // Symmetric with the above
395 } else if (mode == 2) {
396 if (curr == MRI->getVRegDef(a)) {
401 interference = false;
404 } else if (curr->killsRegister(b)) {
413 /// processBlock - Determine how to break up PHIs in the current block. Each
414 /// PHI is broken up by some combination of renaming its operands and inserting
415 /// copies. This method is responsible for determining which operands receive
417 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
418 LiveIntervals& LI = getAnalysis<LiveIntervals>();
419 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
421 // Holds names that have been added to a set in any PHI within this block
422 // before the current one.
423 std::set<unsigned> ProcessedNames;
425 // Iterate over all the PHI nodes in this block
426 MachineBasicBlock::iterator P = MBB->begin();
427 while (P != MBB->end() && P->isPHI()) {
428 unsigned DestReg = P->getOperand(0).getReg();
430 // Don't both doing PHI elimination for dead PHI's.
431 if (P->registerDefIsDead(DestReg)) {
436 LiveInterval& PI = LI.getOrCreateInterval(DestReg);
437 SlotIndex pIdx = LI.getInstructionIndex(P).getDefIndex();
438 VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
439 PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
441 // PHIUnion is the set of incoming registers to the PHI node that
442 // are going to be renames rather than having copies inserted. This set
443 // is refinded over the course of this function. UnionedBlocks is the set
444 // of corresponding MBBs.
445 std::map<unsigned, MachineBasicBlock*> PHIUnion;
446 SmallPtrSet<MachineBasicBlock*, 8> UnionedBlocks;
448 // Iterate over the operands of the PHI node
449 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
450 unsigned SrcReg = P->getOperand(i-1).getReg();
452 // Don't need to try to coalesce a register with itself.
453 if (SrcReg == DestReg) {
454 ProcessedNames.insert(SrcReg);
458 // We don't need to insert copies for implicit_defs.
459 MachineInstr* DefMI = MRI.getVRegDef(SrcReg);
460 if (DefMI->isImplicitDef())
461 ProcessedNames.insert(SrcReg);
463 // Check for trivial interferences via liveness information, allowing us
464 // to avoid extra work later. Any registers that interfere cannot both
465 // be in the renaming set, so choose one and add copies for it instead.
466 // The conditions are:
467 // 1) if the operand is live into the PHI node's block OR
468 // 2) if the PHI node is live out of the operand's defining block OR
469 // 3) if the operand is itself a PHI node and the original PHI is
470 // live into the operand's defining block OR
471 // 4) if the operand is already being renamed for another PHI node
473 // 5) if any two operands are defined in the same block, insert copies
475 if (isLiveIn(SrcReg, P->getParent(), LI) ||
476 isLiveOut(P->getOperand(0).getReg(),
477 MRI.getVRegDef(SrcReg)->getParent(), LI) ||
478 ( MRI.getVRegDef(SrcReg)->isPHI() &&
479 isLiveIn(P->getOperand(0).getReg(),
480 MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
481 ProcessedNames.count(SrcReg) ||
482 UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
484 // Add a copy for the selected register
485 MachineBasicBlock* From = P->getOperand(i).getMBB();
486 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
487 UsedByAnother.insert(SrcReg);
489 // Otherwise, add it to the renaming set
490 PHIUnion.insert(std::make_pair(SrcReg,P->getOperand(i).getMBB()));
491 UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
495 // Compute the dominator forest for the renaming set. This is a forest
496 // where the nodes are the registers and the edges represent dominance
497 // relations between the defining blocks of the registers
498 std::vector<StrongPHIElimination::DomForestNode*> DF =
499 computeDomForest(PHIUnion, MRI);
501 // Walk DomForest to resolve interferences at an inter-block level. This
502 // will remove registers from the renaming set (and insert copies for them)
503 // if interferences are found.
504 std::vector<std::pair<unsigned, unsigned> > localInterferences;
505 processPHIUnion(P, PHIUnion, DF, localInterferences);
507 // If one of the inputs is defined in the same block as the current PHI
508 // then we need to check for a local interference between that input and
510 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
511 E = PHIUnion.end(); I != E; ++I)
512 if (MRI.getVRegDef(I->first)->getParent() == P->getParent())
513 localInterferences.push_back(std::make_pair(I->first,
514 P->getOperand(0).getReg()));
516 // The dominator forest walk may have returned some register pairs whose
517 // interference cannot be determined from dominator analysis. We now
518 // examine these pairs for local interferences.
519 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
520 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
521 std::pair<unsigned, unsigned> p = *I;
523 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
525 // Determine the block we need to scan and the relationship between
527 MachineBasicBlock* scan = 0;
529 if (MRI.getVRegDef(p.first)->getParent() ==
530 MRI.getVRegDef(p.second)->getParent()) {
531 scan = MRI.getVRegDef(p.first)->getParent();
532 mode = 0; // Same block
533 } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
534 MRI.getVRegDef(p.second)->getParent())) {
535 scan = MRI.getVRegDef(p.second)->getParent();
536 mode = 1; // First dominates second
538 scan = MRI.getVRegDef(p.first)->getParent();
539 mode = 2; // Second dominates first
542 // If there's an interference, we need to insert copies
543 if (interferes(p.first, p.second, scan, LI, mode)) {
544 // Insert copies for First
545 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
546 if (P->getOperand(i-1).getReg() == p.first) {
547 unsigned SrcReg = p.first;
548 MachineBasicBlock* From = P->getOperand(i).getMBB();
550 Waiting[From].insert(std::make_pair(SrcReg,
551 P->getOperand(0).getReg()));
552 UsedByAnother.insert(SrcReg);
554 PHIUnion.erase(SrcReg);
560 // Add the renaming set for this PHI node to our overall renaming information
561 for (std::map<unsigned, MachineBasicBlock*>::iterator QI = PHIUnion.begin(),
562 QE = PHIUnion.end(); QI != QE; ++QI) {
563 DEBUG(dbgs() << "Adding Renaming: " << QI->first << " -> "
564 << P->getOperand(0).getReg() << "\n");
567 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
569 // Remember which registers are already renamed, so that we don't try to
570 // rename them for another PHI node in this block
571 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
572 E = PHIUnion.end(); I != E; ++I)
573 ProcessedNames.insert(I->first);
579 /// processPHIUnion - Take a set of candidate registers to be coalesced when
580 /// decomposing the PHI instruction. Use the DominanceForest to remove the ones
581 /// that are known to interfere, and flag others that need to be checked for
582 /// local interferences.
583 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
584 std::map<unsigned, MachineBasicBlock*>& PHIUnion,
585 std::vector<StrongPHIElimination::DomForestNode*>& DF,
586 std::vector<std::pair<unsigned, unsigned> >& locals) {
588 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
589 SmallPtrSet<DomForestNode*, 4> visited;
591 // Code is still in SSA form, so we can use MRI::getVRegDef()
592 MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
594 LiveIntervals& LI = getAnalysis<LiveIntervals>();
595 unsigned DestReg = Inst->getOperand(0).getReg();
597 // DF walk on the DomForest
598 while (!worklist.empty()) {
599 DomForestNode* DFNode = worklist.back();
601 visited.insert(DFNode);
603 bool inserted = false;
604 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
606 DomForestNode* child = *CI;
608 // If the current node is live-out of the defining block of one of its
609 // children, insert a copy for it. NOTE: The paper actually calls for
610 // a more elaborate heuristic for determining whether to insert copies
611 // for the child or the parent. In the interest of simplicity, we're
612 // just always choosing the parent.
613 if (isLiveOut(DFNode->getReg(),
614 MRI.getVRegDef(child->getReg())->getParent(), LI)) {
615 // Insert copies for parent
616 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
617 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
618 unsigned SrcReg = DFNode->getReg();
619 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
621 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
622 UsedByAnother.insert(SrcReg);
624 PHIUnion.erase(SrcReg);
628 // If a node is live-in to the defining block of one of its children, but
629 // not live-out, then we need to scan that block for local interferences.
630 } else if (isLiveIn(DFNode->getReg(),
631 MRI.getVRegDef(child->getReg())->getParent(), LI) ||
632 MRI.getVRegDef(DFNode->getReg())->getParent() ==
633 MRI.getVRegDef(child->getReg())->getParent()) {
634 // Add (p, c) to possible local interferences
635 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
638 if (!visited.count(child)) {
639 worklist.push_back(child);
644 if (!inserted) worklist.pop_back();
648 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
649 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
652 /// Based on "Practical Improvements to the Construction and Destruction
653 /// of Static Single Assignment Form" by Briggs, et al.
654 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
655 std::set<unsigned>& pushed) {
656 // FIXME: This function needs to update LiveIntervals
657 std::multimap<unsigned, unsigned>& copy_set= Waiting[MBB];
659 std::multimap<unsigned, unsigned> worklist;
660 std::map<unsigned, unsigned> map;
662 // Setup worklist of initial copies
663 for (std::multimap<unsigned, unsigned>::iterator I = copy_set.begin(),
664 E = copy_set.end(); I != E; ) {
665 map.insert(std::make_pair(I->first, I->first));
666 map.insert(std::make_pair(I->second, I->second));
668 if (!UsedByAnother.count(I->second)) {
671 // Avoid iterator invalidation
672 std::multimap<unsigned, unsigned>::iterator OI = I;
680 LiveIntervals& LI = getAnalysis<LiveIntervals>();
681 MachineFunction* MF = MBB->getParent();
682 MachineRegisterInfo& MRI = MF->getRegInfo();
683 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
685 SmallVector<std::pair<unsigned, MachineInstr*>, 4> InsertedPHIDests;
687 // Iterate over the worklist, inserting copies
688 while (!worklist.empty() || !copy_set.empty()) {
689 while (!worklist.empty()) {
690 std::multimap<unsigned, unsigned>::iterator WI = worklist.begin();
691 std::pair<unsigned, unsigned> curr = *WI;
694 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
696 if (isLiveOut(curr.second, MBB, LI)) {
697 // Create a temporary
698 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
700 // Insert copy from curr.second to a temporary at
701 // the Phi defining curr.second
702 MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
703 BuildMI(*PI->getParent(), PI, DebugLoc(), TII->get(TargetOpcode::COPY),
704 t).addReg(curr.second);
705 DEBUG(dbgs() << "Inserted copy from " << curr.second << " to " << t
708 // Push temporary on Stacks
709 Stacks[curr.second].push_back(t);
711 // Insert curr.second in pushed
712 pushed.insert(curr.second);
714 // Create a live interval for this temporary
715 InsertedPHIDests.push_back(std::make_pair(t, --PI));
718 // Insert copy from map[curr.first] to curr.second
719 BuildMI(*MBB, MBB->getFirstTerminator(), DebugLoc(),
720 TII->get(TargetOpcode::COPY), curr.second).addReg(map[curr.first]);
721 map[curr.first] = curr.second;
722 DEBUG(dbgs() << "Inserted copy from " << curr.first << " to "
723 << curr.second << "\n");
725 // Push this copy onto InsertedPHICopies so we can
726 // update LiveIntervals with it.
727 MachineBasicBlock::iterator MI = MBB->getFirstTerminator();
728 InsertedPHIDests.push_back(std::make_pair(curr.second, --MI));
730 // If curr.first is a destination in copy_set...
731 for (std::multimap<unsigned, unsigned>::iterator I = copy_set.begin(),
732 E = copy_set.end(); I != E; )
733 if (curr.first == I->second) {
734 std::pair<unsigned, unsigned> temp = *I;
735 worklist.insert(temp);
737 // Avoid iterator invalidation
738 std::multimap<unsigned, unsigned>::iterator OI = I;
748 if (!copy_set.empty()) {
749 std::multimap<unsigned, unsigned>::iterator CI = copy_set.begin();
750 std::pair<unsigned, unsigned> curr = *CI;
751 worklist.insert(curr);
754 LiveInterval& I = LI.getInterval(curr.second);
755 MachineBasicBlock::iterator term = MBB->getFirstTerminator();
756 SlotIndex endIdx = SlotIndex();
757 if (term != MBB->end())
758 endIdx = LI.getInstructionIndex(term);
760 endIdx = LI.getMBBEndIdx(MBB);
762 if (I.liveAt(endIdx)) {
763 const TargetRegisterClass *RC =
764 MF->getRegInfo().getRegClass(curr.first);
766 // Insert a copy from dest to a new temporary t at the end of b
767 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
768 BuildMI(*MBB, MBB->getFirstTerminator(), DebugLoc(),
769 TII->get(TargetOpcode::COPY), t).addReg(curr.second);
770 map[curr.second] = t;
772 MachineBasicBlock::iterator TI = MBB->getFirstTerminator();
773 InsertedPHIDests.push_back(std::make_pair(t, --TI));
778 // Renumber the instructions so that we can perform the index computations
779 // needed to create new live intervals.
782 // For copies that we inserted at the ends of predecessors, we construct
783 // live intervals. This is pretty easy, since we know that the destination
784 // register cannot have be in live at that point previously. We just have
785 // to make sure that, for registers that serve as inputs to more than one
786 // PHI, we don't create multiple overlapping live intervals.
787 std::set<unsigned> RegHandled;
788 for (SmallVector<std::pair<unsigned, MachineInstr*>, 4>::iterator I =
789 InsertedPHIDests.begin(), E = InsertedPHIDests.end(); I != E; ++I) {
790 if (RegHandled.insert(I->first).second) {
791 LiveInterval& Int = LI.getOrCreateInterval(I->first);
792 SlotIndex instrIdx = LI.getInstructionIndex(I->second);
793 if (Int.liveAt(instrIdx.getDefIndex()))
794 Int.removeRange(instrIdx.getDefIndex(),
795 LI.getMBBEndIdx(I->second->getParent()).getNextSlot(),
798 LiveRange R = LI.addLiveRangeToEndOfBlock(I->first, I->second);
799 R.valno->setCopy(I->second);
800 R.valno->def = LI.getInstructionIndex(I->second).getDefIndex();
805 /// InsertCopies - insert copies into MBB and all of its successors
806 void StrongPHIElimination::InsertCopies(MachineDomTreeNode* MDTN,
807 SmallPtrSet<MachineBasicBlock*, 16>& visited) {
808 MachineBasicBlock* MBB = MDTN->getBlock();
811 std::set<unsigned> pushed;
813 LiveIntervals& LI = getAnalysis<LiveIntervals>();
814 // Rewrite register uses from Stacks
815 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
820 for (unsigned i = 0; i < I->getNumOperands(); ++i)
821 if (I->getOperand(i).isReg() &&
822 Stacks[I->getOperand(i).getReg()].size()) {
823 // Remove the live range for the old vreg.
824 LiveInterval& OldInt = LI.getInterval(I->getOperand(i).getReg());
825 LiveInterval::iterator OldLR =
826 OldInt.FindLiveRangeContaining(LI.getInstructionIndex(I).getUseIndex());
827 if (OldLR != OldInt.end())
828 OldInt.removeRange(*OldLR, true);
830 // Change the register
831 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
833 // Add a live range for the new vreg
834 LiveInterval& Int = LI.getInterval(I->getOperand(i).getReg());
835 VNInfo* FirstVN = *Int.vni_begin();
836 FirstVN->setHasPHIKill(false);
837 LiveRange LR (LI.getMBBStartIdx(I->getParent()),
838 LI.getInstructionIndex(I).getUseIndex().getNextSlot(),
845 // Schedule the copies for this block
846 ScheduleCopies(MBB, pushed);
848 // Recur down the dominator tree.
849 for (MachineDomTreeNode::iterator I = MDTN->begin(),
850 E = MDTN->end(); I != E; ++I)
851 if (!visited.count((*I)->getBlock()))
852 InsertCopies(*I, visited);
854 // As we exit this block, pop the names we pushed while processing it
855 for (std::set<unsigned>::iterator I = pushed.begin(),
856 E = pushed.end(); I != E; ++I)
857 Stacks[*I].pop_back();
860 bool StrongPHIElimination::mergeLiveIntervals(unsigned primary,
861 unsigned secondary) {
863 LiveIntervals& LI = getAnalysis<LiveIntervals>();
864 LiveInterval& LHS = LI.getOrCreateInterval(primary);
865 LiveInterval& RHS = LI.getOrCreateInterval(secondary);
869 DenseMap<VNInfo*, VNInfo*> VNMap;
870 for (LiveInterval::iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
873 SlotIndex Start = R.start;
874 SlotIndex End = R.end;
875 if (LHS.getLiveRangeContaining(Start))
878 if (LHS.getLiveRangeContaining(End))
881 LiveInterval::iterator RI = std::upper_bound(LHS.begin(), LHS.end(), R);
882 if (RI != LHS.end() && RI->start < End)
886 for (LiveInterval::iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
888 VNInfo* OldVN = R.valno;
889 VNInfo*& NewVN = VNMap[OldVN];
891 NewVN = LHS.createValueCopy(OldVN, LI.getVNInfoAllocator());
894 LiveRange LR (R.start, R.end, NewVN);
898 LI.removeInterval(RHS.reg);
903 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
904 LiveIntervals& LI = getAnalysis<LiveIntervals>();
906 // Compute DFS numbers of each block
909 // Determine which phi node operands need copies
910 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
911 if (!I->empty() && I->begin()->isPHI())
914 // Break interferences where two different phis want to coalesce
915 // in the same register.
916 std::set<unsigned> seen;
917 typedef std::map<unsigned, std::map<unsigned, MachineBasicBlock*> >
919 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
921 for (std::map<unsigned, MachineBasicBlock*>::iterator
922 OI = I->second.begin(), OE = I->second.end(); OI != OE; ) {
923 if (!seen.count(OI->first)) {
924 seen.insert(OI->first);
927 Waiting[OI->second].insert(std::make_pair(OI->first, I->first));
928 unsigned reg = OI->first;
930 I->second.erase(reg);
931 DEBUG(dbgs() << "Removing Renaming: " << reg << " -> " << I->first
938 // FIXME: This process should probably preserve LiveIntervals
939 SmallPtrSet<MachineBasicBlock*, 16> visited;
940 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
941 InsertCopies(MDT.getRootNode(), visited);
944 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
946 while (I->second.size()) {
947 std::map<unsigned, MachineBasicBlock*>::iterator SI = I->second.begin();
949 DEBUG(dbgs() << "Renaming: " << SI->first << " -> " << I->first << "\n");
951 if (SI->first != I->first) {
952 if (mergeLiveIntervals(I->first, SI->first)) {
953 Fn.getRegInfo().replaceRegWith(SI->first, I->first);
955 if (RenameSets.count(SI->first)) {
956 I->second.insert(RenameSets[SI->first].begin(),
957 RenameSets[SI->first].end());
958 RenameSets.erase(SI->first);
961 // Insert a last-minute copy if a conflict was detected.
962 const TargetInstrInfo *TII = Fn.getTarget().getInstrInfo();
963 BuildMI(*SI->second, SI->second->getFirstTerminator(), DebugLoc(),
964 TII->get(TargetOpcode::COPY), I->first).addReg(SI->first);
968 LiveInterval& Int = LI.getOrCreateInterval(I->first);
970 LI.getInstructionIndex(--SI->second->getFirstTerminator());
971 if (Int.liveAt(instrIdx.getDefIndex()))
972 Int.removeRange(instrIdx.getDefIndex(),
973 LI.getMBBEndIdx(SI->second).getNextSlot(), true);
975 LiveRange R = LI.addLiveRangeToEndOfBlock(I->first,
976 --SI->second->getFirstTerminator());
977 R.valno->setCopy(--SI->second->getFirstTerminator());
978 R.valno->def = instrIdx.getDefIndex();
980 DEBUG(dbgs() << "Renaming failed: " << SI->first << " -> "
981 << I->first << "\n");
985 LiveInterval& Int = LI.getOrCreateInterval(I->first);
986 const LiveRange* LR =
987 Int.getLiveRangeContaining(LI.getMBBEndIdx(SI->second));
988 LR->valno->setHasPHIKill(true);
990 I->second.erase(SI->first);
994 std::vector<MachineInstr*> phis;
995 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
996 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
1002 for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
1004 MachineInstr* PInstr = *(I++);
1006 // If this is a dead PHI node, then remove it from LiveIntervals.
1007 unsigned DestReg = PInstr->getOperand(0).getReg();
1008 LiveInterval& PI = LI.getInterval(DestReg);
1009 if (PInstr->registerDefIsDead(DestReg)) {
1010 if (PI.containsOneValue()) {
1011 LI.removeInterval(DestReg);
1013 SlotIndex idx = LI.getInstructionIndex(PInstr).getDefIndex();
1014 PI.removeRange(*PI.getLiveRangeContaining(idx), true);
1017 // Trim live intervals of input registers. They are no longer live into
1018 // this block if they died after the PHI. If they lived after it, don't
1019 // trim them because they might have other legitimate uses.
1020 for (unsigned i = 1; i < PInstr->getNumOperands(); i += 2) {
1021 unsigned reg = PInstr->getOperand(i).getReg();
1023 MachineBasicBlock* MBB = PInstr->getOperand(i+1).getMBB();
1024 LiveInterval& InputI = LI.getInterval(reg);
1025 if (MBB != PInstr->getParent() &&
1026 InputI.liveAt(LI.getMBBStartIdx(PInstr->getParent())) &&
1027 InputI.expiredAt(LI.getInstructionIndex(PInstr).getNextIndex()))
1028 InputI.removeRange(LI.getMBBStartIdx(PInstr->getParent()),
1029 LI.getInstructionIndex(PInstr),
1033 // If the PHI is not dead, then the valno defined by the PHI
1034 // now has an unknown def.
1035 SlotIndex idx = LI.getInstructionIndex(PInstr).getDefIndex();
1036 const LiveRange* PLR = PI.getLiveRangeContaining(idx);
1037 PLR->valno->setIsPHIDef(true);
1038 LiveRange R (LI.getMBBStartIdx(PInstr->getParent()),
1039 PLR->start, PLR->valno);
1043 LI.RemoveMachineInstrFromMaps(PInstr);
1044 PInstr->eraseFromParent();